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
Walter-Stroebel/Jllama
src/main/java/nl/infcomtec/jllama/Vagrant.java
[ { "identifier": "ARROWS", "path": "src/main/java/nl/infcomtec/tools/ARROWS.java", "snippet": "public class ARROWS {\n\n public static final String RIGHT = \"\\u27A1\";\n public static final String LEFT = \"\\u2190\";\n public static final String UP = \"\\u2191\";\n public static final String...
import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelExec; import com.jcraft.jsch.JSch; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.nio.charset.StandardCharsets; import java.util.Objects; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.logging.Logger; import nl.infcomtec.tools.ARROWS; import nl.infcomtec.tools.ToolManager;
3,049
/** * Parse and execute. * * @param text with markers. * @return */ public String execMarked(String text) { StringBuilder sb = new StringBuilder(text); StringBuilder output = new StringBuilder(); int cmdStart = sb.indexOf(MARK_START); while (cmdStart >= 0) { int cmdEnd = sb.indexOf(MARK_END, cmdStart); if (cmdEnd > 2) { String cmd = sb.substring(cmdStart + 2, cmdEnd).trim(); // in case the LLM got fancy with whitespace execOnBox(cmd, output); sb.delete(cmdStart, cmdEnd + 2); cmdStart = sb.indexOf(MARK_START); } } // any non-whitespace left plus any output String disp = sb.toString().trim() + System.lineSeparator() + output.toString(); return disp; } /** * Execute. * * @param cmd command. * @param input Optional input for the command. * @return */ public String exec(String cmd, String input) { StringBuilder output = new StringBuilder(); this.input.set(input); execOnBox(cmd, output); return output.toString(); } private void execOnBox(final String cmd, final StringBuilder output) { while (Step.running != state.get()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, ex); } } try { log("Vagrant execute:", cmd); final Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(cmd); final ByteArrayOutputStream errStream = new ByteArrayOutputStream(); ((ChannelExec) channel).setErrStream(errStream); channel.connect(); final String inp = input.getAndSet(null); if (null != inp) { final OutputStream outStream = channel.getOutputStream(); new Thread(new Runnable() { @Override public void run() { try { byte[] inputBytes = inp.getBytes(); int offset = 0; int chunkSize = 1024; while (offset < inputBytes.length) { int length = Math.min(chunkSize, inputBytes.length - offset); outStream.write(inputBytes, offset, length); doCallBack(onInputPassed, inputBytes, offset, length); outStream.flush(); offset += length; } } catch (IOException e) { log("Error writing input to channel:", e.getMessage()); } finally { try { outStream.close(); } catch (IOException e) { log("Error closing output stream:", e.getMessage()); } } } }).start(); } final BufferedReader bfr; try { bfr = new BufferedReader(new InputStreamReader(channel.getInputStream())); for (String line = bfr.readLine(); null != line; line = bfr.readLine()) { doCallBack(onOutputReceived, line); doCallBack(onOutputReceived, System.lineSeparator()); output.append(line).append(System.lineSeparator()); } } catch (IOException e) { Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, e); } // Append stderr to output output.append(errStream.toString()); channel.disconnect(); log("Output:", output.toString()); } catch (Exception e) { log("Failed to execute on Vagrant:", e.getMessage()); Step old = state.get(); state.set(Step.stopped); doCallBack(onStateChange, old.name(), state.get().name()); } } private void doCallBack(AtomicReference<CallBack> cb, String s) { CallBack get = cb.get(); if (null != get) { get.cb(s); } } private void doCallBack(AtomicReference<CallBack> cb, String f, String t) { CallBack get = cb.get(); if (null != get) {
package nl.infcomtec.jllama; /** * Wrapper around Vagrant. * * @author walter */ public class Vagrant extends ToolManager { public static final File VAGRANT_DIR = new File(System.getProperty("user.home"), "vagrant/Worker"); public static final File VAGRANT_KEY = new File(VAGRANT_DIR, ".vagrant/machines/default/virtualbox/private_key"); public static final String MARK_START = "$#"; public static final String MARK_END = "#$"; private final AtomicReference<String> input = new AtomicReference<>(null); private com.jcraft.jsch.Session session; public final AtomicReference<Step> state = new AtomicReference<>(Step.stopped); public final StringBuilder log = new StringBuilder(); private final String EOLN = System.lineSeparator(); public AtomicReference<CallBack> onStateChange = new AtomicReference<>(null); public AtomicReference<CallBack> onInputPassed = new AtomicReference<>(null); public AtomicReference<CallBack> onOutputReceived = new AtomicReference<>(null); public Vagrant() { } public void stop() { Step old = state.get(); state.set(Step.stop); doCallBack(onStateChange, old.name(), state.get().name()); new Thread(this).start(); } public void start() { Step old = state.get(); state.set(Step.start); doCallBack(onStateChange, old.name(), state.get().name()); new Thread(this).start(); } /** * Internal use only, must be called within synchronized(log). */ private void logTimeStamp() { log.append(String.format("%1$tF %1$tT:", System.currentTimeMillis())); } public void log(String... msg) { synchronized (log) { logTimeStamp(); if (null == msg) { log.append(" Log called without any message."); } else { for (String s : msg) { if (!Character.isWhitespace(log.charAt(log.length() - 1))) { log.append(' '); } log.append(s); } } log.append(EOLN); } } @Override public void run() { switch (state.get()) { case stopped: log("Run was called in the ", state.get().name(), " state. That should not happen."); break; case start: log("Starting Vagrant."); setWorkingDir(VAGRANT_DIR); setCommand("vagrant", "up"); internalRun(); if (exitCode != 0) { log("Running vagrant failed, rc=", Integer.toString(exitCode)); } if (stdoutStream instanceof ByteArrayOutputStream) { log("Vagrant start up:", EOLN, new String(((ByteArrayOutputStream) stdoutStream).toByteArray(), StandardCharsets.UTF_8)); stdoutStream = null; } else { log("Vagrant start up:", Objects.toString(stdoutStream)); } if (stderrBuilder.length() > 0) { log("Vagrant error output:" + stderrBuilder.toString()); } stderrBuilder.setLength(0); try { JSch jsch = new JSch(); jsch.addIdentity(VAGRANT_KEY.getAbsolutePath()); session = jsch.getSession("vagrant", "localhost", 2222); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Step old = state.get(); state.set(Step.running); doCallBack(onStateChange, old.name(), state.get().name()); } catch (Exception e) { log("Failed to connect to Vagrant:", e.getMessage()); Step old = state.get(); state.set(Step.stopped); doCallBack(onStateChange, old.name(), state.get().name()); } break; case stop: log("Stopping Vagrant."); if (null != session) { try { session.disconnect(); } catch (Exception any) { // we don't care, we tried. } session = null; } setWorkingDir(VAGRANT_DIR); setCommand("vagrant", "halt"); internalRun(); log("Vagrant should be stopped."); break; default: log("Run was called in the ", state.get().name(), " state. That REALLY should not happen."); break; } } /** * Parse and execute. * * @param text with markers. * @return */ public String execMarked(String text) { StringBuilder sb = new StringBuilder(text); StringBuilder output = new StringBuilder(); int cmdStart = sb.indexOf(MARK_START); while (cmdStart >= 0) { int cmdEnd = sb.indexOf(MARK_END, cmdStart); if (cmdEnd > 2) { String cmd = sb.substring(cmdStart + 2, cmdEnd).trim(); // in case the LLM got fancy with whitespace execOnBox(cmd, output); sb.delete(cmdStart, cmdEnd + 2); cmdStart = sb.indexOf(MARK_START); } } // any non-whitespace left plus any output String disp = sb.toString().trim() + System.lineSeparator() + output.toString(); return disp; } /** * Execute. * * @param cmd command. * @param input Optional input for the command. * @return */ public String exec(String cmd, String input) { StringBuilder output = new StringBuilder(); this.input.set(input); execOnBox(cmd, output); return output.toString(); } private void execOnBox(final String cmd, final StringBuilder output) { while (Step.running != state.get()) { try { Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, ex); } } try { log("Vagrant execute:", cmd); final Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(cmd); final ByteArrayOutputStream errStream = new ByteArrayOutputStream(); ((ChannelExec) channel).setErrStream(errStream); channel.connect(); final String inp = input.getAndSet(null); if (null != inp) { final OutputStream outStream = channel.getOutputStream(); new Thread(new Runnable() { @Override public void run() { try { byte[] inputBytes = inp.getBytes(); int offset = 0; int chunkSize = 1024; while (offset < inputBytes.length) { int length = Math.min(chunkSize, inputBytes.length - offset); outStream.write(inputBytes, offset, length); doCallBack(onInputPassed, inputBytes, offset, length); outStream.flush(); offset += length; } } catch (IOException e) { log("Error writing input to channel:", e.getMessage()); } finally { try { outStream.close(); } catch (IOException e) { log("Error closing output stream:", e.getMessage()); } } } }).start(); } final BufferedReader bfr; try { bfr = new BufferedReader(new InputStreamReader(channel.getInputStream())); for (String line = bfr.readLine(); null != line; line = bfr.readLine()) { doCallBack(onOutputReceived, line); doCallBack(onOutputReceived, System.lineSeparator()); output.append(line).append(System.lineSeparator()); } } catch (IOException e) { Logger.getLogger(Vagrant.class.getName()).log(Level.SEVERE, null, e); } // Append stderr to output output.append(errStream.toString()); channel.disconnect(); log("Output:", output.toString()); } catch (Exception e) { log("Failed to execute on Vagrant:", e.getMessage()); Step old = state.get(); state.set(Step.stopped); doCallBack(onStateChange, old.name(), state.get().name()); } } private void doCallBack(AtomicReference<CallBack> cb, String s) { CallBack get = cb.get(); if (null != get) { get.cb(s); } } private void doCallBack(AtomicReference<CallBack> cb, String f, String t) { CallBack get = cb.get(); if (null != get) {
get.cb(f + ARROWS.RIGHT + t);
0
2023-11-16 00:37:47+00:00
4k
jimbro1000/DriveWire4Rebuild
src/main/java/org/thelair/dw4/drivewire/ports/serial/DWSerialPort.java
[ { "identifier": "BasePortDef", "path": "src/main/java/org/thelair/dw4/drivewire/ports/BasePortDef.java", "snippet": "public abstract class BasePortDef implements DWIPortType {\n}" }, { "identifier": "DWIPort", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPort.java", "snippet...
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.thelair.dw4.drivewire.ports.BasePortDef; import org.thelair.dw4.drivewire.ports.DWIPort; import org.thelair.dw4.drivewire.ports.DWIPortManager; import org.thelair.dw4.drivewire.ports.InvalidPortTypeDefinition; import org.thelair.dw4.drivewire.ports.serial.hardware.DWISerial; import java.util.Map;
2,769
package org.thelair.dw4.drivewire.ports.serial; /** * RS232 Serial port definition. */ public final class DWSerialPort implements DWIPort { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class); /** * Serial port definition. */ private SerialPortDef portDef; /** * Port manager. */ private final DWIPortManager portManager; /** * concrete com port object. */ private DWISerial comPort; /** * Serial port handler. */ private final SerialPortHardware portHandler; /** * Unique port identifier. */ private final int portId; /** * Create serial port with reference to manager. * @param manager port manager handling this port * @param port identifier * @param hardPorts host serial hardware */ public DWSerialPort( final DWIPortManager manager, final int port, final SerialPortHardware hardPorts ) { this.portManager = manager; this.portId = port; this.portHandler = hardPorts; LOGGER.info("Serial port created " + port); } @Override public void openWith(final BasePortDef port)
package org.thelair.dw4.drivewire.ports.serial; /** * RS232 Serial port definition. */ public final class DWSerialPort implements DWIPort { /** * Log appender. */ private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class); /** * Serial port definition. */ private SerialPortDef portDef; /** * Port manager. */ private final DWIPortManager portManager; /** * concrete com port object. */ private DWISerial comPort; /** * Serial port handler. */ private final SerialPortHardware portHandler; /** * Unique port identifier. */ private final int portId; /** * Create serial port with reference to manager. * @param manager port manager handling this port * @param port identifier * @param hardPorts host serial hardware */ public DWSerialPort( final DWIPortManager manager, final int port, final SerialPortHardware hardPorts ) { this.portManager = manager; this.portId = port; this.portHandler = hardPorts; LOGGER.info("Serial port created " + port); } @Override public void openWith(final BasePortDef port)
throws InvalidPortTypeDefinition {
3
2023-11-18 11:35:16+00:00
4k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/entities/EntityRegister.java
[ { "identifier": "Gunscraft", "path": "src/main/java/sheridan/gunscraft/Gunscraft.java", "snippet": "@Mod(\"gunscraft\")\npublic class Gunscraft {\n\n // Directly reference a log4j logger.\n private static final Logger LOGGER = LogManager.getLogger();\n\n public static IProxy proxy = DistExecuto...
import net.minecraft.entity.EntityClassification; import net.minecraft.entity.EntityType; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.RegistryObject; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.entities.projectile.GenericProjectile; import sheridan.gunscraft.render.entities.GenericProjectileRenderer;
2,738
package sheridan.gunscraft.entities; public class EntityRegister { public static final DeferredRegister<EntityType<?>> ENTITIES; //public static final EntityType<GenericProjectile> GENERIC_PROJECTILE = EntityType.Builder.createGenericRecoil(GenericProjectile::new, EntityClassification.MISC).size(0.25f, 0.5f).updateInterval(1).build(new ResourceLocation(Gunscraft.MOD_ID ,"generic_projectile").toString()); public static final RegistryObject<EntityType<GenericProjectile>> GENERIC_PROJECTILE; static {
package sheridan.gunscraft.entities; public class EntityRegister { public static final DeferredRegister<EntityType<?>> ENTITIES; //public static final EntityType<GenericProjectile> GENERIC_PROJECTILE = EntityType.Builder.createGenericRecoil(GenericProjectile::new, EntityClassification.MISC).size(0.25f, 0.5f).updateInterval(1).build(new ResourceLocation(Gunscraft.MOD_ID ,"generic_projectile").toString()); public static final RegistryObject<EntityType<GenericProjectile>> GENERIC_PROJECTILE; static {
ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Gunscraft.MOD_ID);
0
2023-11-14 14:00:55+00:00
4k
zpascual/5419-Arm-Example
src/main/java/com/team5419/frc2023/subsystems/Arm.java
[ { "identifier": "Util", "path": "src/main/java/com/team254/lib/util/Util.java", "snippet": "public class Util {\n\n public static final double kEpsilon = 1e-12;\n\n /**\n * Prevent this class from being instantiated.\n */\n private Util() {\n }\n\n /**\n * Limits the given inp...
import com.ctre.phoenix.motorcontrol.NeutralMode; import com.team254.lib.util.Util; import com.team5419.frc2023.Constants; import com.team5419.frc2023.loops.ILooper; import com.team5419.frc2023.loops.Loop; import com.team5419.lib.requests.Request;
2,524
package com.team5419.frc2023.subsystems; public class Arm extends ServoMotorSubsystem { private static Arm mInstance; public static Arm getInstance(){ if (mInstance == null) { mInstance = new Arm(kArmConstants); } return mInstance; }
package com.team5419.frc2023.subsystems; public class Arm extends ServoMotorSubsystem { private static Arm mInstance; public static Arm getInstance(){ if (mInstance == null) { mInstance = new Arm(kArmConstants); } return mInstance; }
private static final ServoMotorSubsystemConstants kArmConstants = Constants.Arm.kArmServoConstants;
1
2023-11-14 06:44:40+00:00
4k
Ouest-France/querydsl-postgrest
src/test/java/fr/ouestfrance/querydsl/postgrest/PostgrestRepositoryGetMockTest.java
[ { "identifier": "Page", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Page.java", "snippet": "public interface Page<T> extends Iterable<T> {\n\n /**\n * Create simple page from items\n *\n * @param items items\n * @param <T> type of items\n * @return one page of...
import fr.ouestfrance.querydsl.postgrest.app.*; import fr.ouestfrance.querydsl.postgrest.model.Page; import fr.ouestfrance.querydsl.postgrest.model.Pageable; import fr.ouestfrance.querydsl.postgrest.model.Sort; import fr.ouestfrance.querydsl.postgrest.model.exceptions.PostgrestRequestException; import fr.ouestfrance.querydsl.postgrest.utils.QueryStringUtils; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMapAdapter; import java.time.LocalDate; import java.util.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.when;
3,551
package fr.ouestfrance.querydsl.postgrest; @Slf4j class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest { @Mock private PostgrestWebClient webClient; private PostgrestRepository<Post> repository; @BeforeEach void beforeEach() { repository = new PostRepository(webClient); } @Test void shouldSearchAllPosts() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(null); assertNotNull(search); assertNotNull(search.iterator()); assertEquals(2, search.size()); } private ResponseEntity<List<Object>> ok(List<Object> data) { MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size()))); return new ResponseEntity<>(data, headers, HttpStatus.OK); } @Test void shouldSearchWithPaginate() { PostRequest request = new PostRequest(); request.setUserId(1); request.setId(1); request.setTitle("Test*"); request.setCodes(List.of("a", "b", "c")); request.setExcludes(List.of("z")); request.setValidDate(LocalDate.of(2023, 11, 10)); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast()))); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertEquals("eq.1", queries.getFirst("userId")); assertEquals("neq.1", queries.getFirst("id")); assertEquals("lte.2023-11-10", queries.getFirst("startDate")); assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or")); assertEquals("like.Test*", queries.getFirst("title")); assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order")); assertEquals("*,authors(*)", queries.getFirst("select")); assertEquals(2, queries.get("status").size()); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldSearchWithoutOrder() { PostRequest request = new PostRequest(); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10)); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertNull(queries.getFirst("order")); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldRaiseExceptionOnMultipleOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
package fr.ouestfrance.querydsl.postgrest; @Slf4j class PostgrestRepositoryGetMockTest extends AbstractRepositoryMockTest { @Mock private PostgrestWebClient webClient; private PostgrestRepository<Post> repository; @BeforeEach void beforeEach() { repository = new PostRepository(webClient); } @Test void shouldSearchAllPosts() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(null); assertNotNull(search); assertNotNull(search.iterator()); assertEquals(2, search.size()); } private ResponseEntity<List<Object>> ok(List<Object> data) { MultiValueMap<String, String> headers = new MultiValueMapAdapter<>(Map.of("Content-Range", List.of("0-" + data.size() + "/" + data.size()))); return new ResponseEntity<>(data, headers, HttpStatus.OK); } @Test void shouldSearchWithPaginate() { PostRequest request = new PostRequest(); request.setUserId(1); request.setId(1); request.setTitle("Test*"); request.setCodes(List.of("a", "b", "c")); request.setExcludes(List.of("z")); request.setValidDate(LocalDate.of(2023, 11, 10)); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10, Sort.by(Sort.Order.asc("id"), Sort.Order.desc("title").nullsFirst(), Sort.Order.asc("author").nullsLast()))); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertEquals("eq.1", queries.getFirst("userId")); assertEquals("neq.1", queries.getFirst("id")); assertEquals("lte.2023-11-10", queries.getFirst("startDate")); assertEquals("(endDate.gte.2023-11-10,endDate.is.null)", queries.getFirst("or")); assertEquals("like.Test*", queries.getFirst("title")); assertEquals("id,title.desc.nullsfirst,author.nullslast", queries.getFirst("order")); assertEquals("*,authors(*)", queries.getFirst("select")); assertEquals(2, queries.get("status").size()); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldSearchWithoutOrder() { PostRequest request = new PostRequest(); ArgumentCaptor<MultiValueMap<String, String>> queryArgs = multiMapCaptor(); ArgumentCaptor<MultiValueMap<String, String>> headerArgs = multiMapCaptor(); when(webClient.search(anyString(), queryArgs.capture(), headerArgs.capture(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post())); Page<Post> search = repository.search(request, Pageable.ofSize(10)); assertNotNull(search); assertEquals(2, search.size()); // Assert query captors MultiValueMap<String, String> queries = queryArgs.getValue(); log.info("queries {}", queries); assertNull(queries.getFirst("order")); // Assert headers captors MultiValueMap<String, String> value = headerArgs.getValue(); assertEquals("0-9", value.getFirst("Range")); assertEquals("items", value.getFirst("Range-Unit")); } @Test void shouldRaiseExceptionOnMultipleOne() { when(webClient.search(anyString(), any(), any(), eq(Post.class))).thenReturn(Page.of(new Post(), new Post()));
assertThrows(PostgrestRequestException.class, () -> repository.findOne(null));
3
2023-11-14 10:45:54+00:00
4k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/dialogs/SigningOptionsDialog.java
[ { "identifier": "APKSignActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/APKSignActivity.java", "snippet": "public class APKSignActivity extends AppCompatActivity {\n\n private AppCompatImageButton mClearKey, mClearCert;\n private MaterialTextView mKeySummary, mCertSumma...
import android.app.Activity; import android.content.Context; import android.content.Intent; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.APKSignActivity; import com.threethan.questpatcher.utils.tasks.ResignAPKs; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.Dialog.sSingleItemDialog;
2,738
package com.threethan.questpatcher.utils.dialogs; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 30, 2023 */ public class SigningOptionsDialog extends sSingleItemDialog { private final Context mContext; private final boolean mExit; private final String mPackageName; public SigningOptionsDialog(String packageName, boolean exit, Context context) { super(0, null, new String[] { context.getString(R.string.signing_default), context.getString(R.string.signing_custom) }, context); mPackageName = packageName; mExit = exit; mContext = context; } @Override public void onItemSelected(int position) { sCommonUtils.saveBoolean("firstSigning", true, mContext); if (position == 0) {
package com.threethan.questpatcher.utils.dialogs; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on January 30, 2023 */ public class SigningOptionsDialog extends sSingleItemDialog { private final Context mContext; private final boolean mExit; private final String mPackageName; public SigningOptionsDialog(String packageName, boolean exit, Context context) { super(0, null, new String[] { context.getString(R.string.signing_default), context.getString(R.string.signing_custom) }, context); mPackageName = packageName; mExit = exit; mContext = context; } @Override public void onItemSelected(int position) { sCommonUtils.saveBoolean("firstSigning", true, mContext); if (position == 0) {
new ResignAPKs(mPackageName,false, mExit, (Activity) mContext).execute();
1
2023-11-18 15:13:30+00:00
4k
jenkinsci/harbor-plugin
src/main/java/io/jenkins/plugins/harbor/client/HarborClient.java
[ { "identifier": "HarborException", "path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java", "snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throw...
import edu.umd.cs.findbugs.annotations.Nullable; import io.jenkins.plugins.harbor.HarborException; import io.jenkins.plugins.harbor.client.models.Artifact; import io.jenkins.plugins.harbor.client.models.NativeReportSummary; import io.jenkins.plugins.harbor.client.models.Repository; import java.io.IOException; import java.util.Map;
2,914
package io.jenkins.plugins.harbor.client; public interface HarborClient { /** * Get the vulnerabilities addition of the specific artifact * <p> * Get the vulnerabilities addition of the artifact specified by the reference under the project and repository. * * @param projectName The project name of Harbor * @param repositoryName The name of * @param reference The reference can be digest or tag. */ NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference); /** * Ping Harbor to check if it's alive. * <p> * This API simply replies a pong to indicate the process to handle API is up, * disregarding the health status of dependent components. * * @return If the request succeeds, the 'Pong' string is returned * @throws IOException The HTTP request failed * @throws HarborException httpUrl is null */ String getPing() throws IOException; /** * List all authorized repositories * * @return Return to the list of repositories */ Repository[] listAllRepositories() throws IOException;
package io.jenkins.plugins.harbor.client; public interface HarborClient { /** * Get the vulnerabilities addition of the specific artifact * <p> * Get the vulnerabilities addition of the artifact specified by the reference under the project and repository. * * @param projectName The project name of Harbor * @param repositoryName The name of * @param reference The reference can be digest or tag. */ NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference); /** * Ping Harbor to check if it's alive. * <p> * This API simply replies a pong to indicate the process to handle API is up, * disregarding the health status of dependent components. * * @return If the request succeeds, the 'Pong' string is returned * @throws IOException The HTTP request failed * @throws HarborException httpUrl is null */ String getPing() throws IOException; /** * List all authorized repositories * * @return Return to the list of repositories */ Repository[] listAllRepositories() throws IOException;
Artifact[] listArtifacts(String projectName, String repositoryName, @Nullable Map<String, String> extraParams)
1
2023-11-11 14:54:53+00:00
4k
someElseIsHere/potato-golem
common/src/main/java/org/theplaceholder/potatogolem/PotatoGolemEntity.java
[ { "identifier": "PotatoOwnerHurtByTargetGoal", "path": "common/src/main/java/org/theplaceholder/potatogolem/goal/PotatoOwnerHurtByTargetGoal.java", "snippet": "public class PotatoOwnerHurtByTargetGoal extends TargetGoal {\n private final PotatoGolemEntity tameAnimal;\n private LivingEntity ownerLa...
import net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.players.OldUsersConverter; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.*; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.*; import net.minecraft.world.entity.ai.goal.target.*; import net.minecraft.world.entity.animal.IronGolem; import net.minecraft.world.entity.monster.Creeper; import net.minecraft.world.entity.monster.Enemy; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.theplaceholder.potatogolem.goal.PotatoOwnerHurtByTargetGoal; import org.theplaceholder.potatogolem.goal.PotatoOwnerHurtTargetGoal; import java.util.Optional; import java.util.UUID;
1,998
package org.theplaceholder.potatogolem; public class PotatoGolemEntity extends IronGolem implements OwnableEntity { protected static final EntityDataAccessor<Optional<UUID>> DATA_OWNERUUID_ID = SynchedEntityData.defineId(PotatoGolemEntity.class, EntityDataSerializers.OPTIONAL_UUID);; public PotatoGolemEntity(EntityType<PotatoGolemEntity> entityType, Level level) { super(entityType, level); } @Override protected void playStepSound(BlockPos blockPos, BlockState blockState) { this.playSound(PotatoGolemSounds.STEP.get(), 1.0F, 1.0F); } @Override public boolean hurt(DamageSource damageSource, float f) { Crackiness crackiness = this.getCrackiness(); boolean bl = super.hurt(damageSource, f); if (bl && this.getCrackiness() != crackiness) { this.playSound(PotatoGolemSounds.DAMAGE.get(), 1.0F, 1.0F); } return bl; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_OWNERUUID_ID, Optional.empty()); } @Override public boolean doHurtTarget(Entity entity) { this.attackAnimationTick = 17; this.level().broadcastEntityEvent(this, (byte)4); float f = this.getAttackDamage(); float g = (int)f > 0 ? f / 2.0F + (float)this.random.nextInt((int)f) : f; boolean bl = entity.hurt(this.damageSources().mobAttack(this), g); if (bl) { double d; if (entity instanceof LivingEntity livingEntity) { d = livingEntity.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE); } else { d = 0.0; } double e = Math.max(0.0, 1.0 - d); entity.setDeltaMovement(entity.getDeltaMovement().add(0.0, 0.4000000059604645 * e, 0.0)); this.doEnchantDamageEffects(this, entity); } this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F); return bl; } @Override protected @NotNull InteractionResult mobInteract(Player player, InteractionHand interactionHand) { ItemStack itemStack = player.getItemInHand(interactionHand); if (itemStack.is(Items.DIRT) && !isTamed()) { setOwnerUUID(player.getUUID()); if(!player.isCreative()) itemStack.shrink(1); spawnTamingParticles(); } if (!itemStack.is(Items.POTATO)) { return InteractionResult.PASS; } else { float f = this.getHealth(); this.heal(25.0F); if (this.getHealth() == f) { return InteractionResult.PASS; } else { float g = 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F; this.playSound(PotatoGolemSounds.REPAIR.get(), 1.0F, g); if (!player.getAbilities().instabuild) { itemStack.shrink(1); } return InteractionResult.sidedSuccess(this.level().isClientSide); } } } @Override public void handleEntityEvent(byte b) { if (b == 4) { this.attackAnimationTick = 17; this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F); } else { super.handleEntityEvent(b); } } @Override protected void registerGoals() { this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.0, true)); this.goalSelector.addGoal(2, new MoveTowardsTargetGoal(this, 0.9, 32.0F)); this.goalSelector.addGoal(7, new LookAtPlayerGoal(this, Player.class, 6.0F)); this.goalSelector.addGoal(8, new RandomLookAroundGoal(this)); this.targetSelector.addGoal(2, new HurtByTargetGoal(this)); this.targetSelector.addGoal(3, new NearestAttackableTargetGoal<>(this, Mob.class, 5, false, false, (livingEntity) -> livingEntity instanceof Enemy && !(livingEntity instanceof Creeper))); this.targetSelector.addGoal(5, new PotatoOwnerHurtByTargetGoal(this));
package org.theplaceholder.potatogolem; public class PotatoGolemEntity extends IronGolem implements OwnableEntity { protected static final EntityDataAccessor<Optional<UUID>> DATA_OWNERUUID_ID = SynchedEntityData.defineId(PotatoGolemEntity.class, EntityDataSerializers.OPTIONAL_UUID);; public PotatoGolemEntity(EntityType<PotatoGolemEntity> entityType, Level level) { super(entityType, level); } @Override protected void playStepSound(BlockPos blockPos, BlockState blockState) { this.playSound(PotatoGolemSounds.STEP.get(), 1.0F, 1.0F); } @Override public boolean hurt(DamageSource damageSource, float f) { Crackiness crackiness = this.getCrackiness(); boolean bl = super.hurt(damageSource, f); if (bl && this.getCrackiness() != crackiness) { this.playSound(PotatoGolemSounds.DAMAGE.get(), 1.0F, 1.0F); } return bl; } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_OWNERUUID_ID, Optional.empty()); } @Override public boolean doHurtTarget(Entity entity) { this.attackAnimationTick = 17; this.level().broadcastEntityEvent(this, (byte)4); float f = this.getAttackDamage(); float g = (int)f > 0 ? f / 2.0F + (float)this.random.nextInt((int)f) : f; boolean bl = entity.hurt(this.damageSources().mobAttack(this), g); if (bl) { double d; if (entity instanceof LivingEntity livingEntity) { d = livingEntity.getAttributeValue(Attributes.KNOCKBACK_RESISTANCE); } else { d = 0.0; } double e = Math.max(0.0, 1.0 - d); entity.setDeltaMovement(entity.getDeltaMovement().add(0.0, 0.4000000059604645 * e, 0.0)); this.doEnchantDamageEffects(this, entity); } this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F); return bl; } @Override protected @NotNull InteractionResult mobInteract(Player player, InteractionHand interactionHand) { ItemStack itemStack = player.getItemInHand(interactionHand); if (itemStack.is(Items.DIRT) && !isTamed()) { setOwnerUUID(player.getUUID()); if(!player.isCreative()) itemStack.shrink(1); spawnTamingParticles(); } if (!itemStack.is(Items.POTATO)) { return InteractionResult.PASS; } else { float f = this.getHealth(); this.heal(25.0F); if (this.getHealth() == f) { return InteractionResult.PASS; } else { float g = 1.0F + (this.random.nextFloat() - this.random.nextFloat()) * 0.2F; this.playSound(PotatoGolemSounds.REPAIR.get(), 1.0F, g); if (!player.getAbilities().instabuild) { itemStack.shrink(1); } return InteractionResult.sidedSuccess(this.level().isClientSide); } } } @Override public void handleEntityEvent(byte b) { if (b == 4) { this.attackAnimationTick = 17; this.playSound(PotatoGolemSounds.ATTACK.get(), 1.0F, 1.0F); } else { super.handleEntityEvent(b); } } @Override protected void registerGoals() { this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.0, true)); this.goalSelector.addGoal(2, new MoveTowardsTargetGoal(this, 0.9, 32.0F)); this.goalSelector.addGoal(7, new LookAtPlayerGoal(this, Player.class, 6.0F)); this.goalSelector.addGoal(8, new RandomLookAroundGoal(this)); this.targetSelector.addGoal(2, new HurtByTargetGoal(this)); this.targetSelector.addGoal(3, new NearestAttackableTargetGoal<>(this, Mob.class, 5, false, false, (livingEntity) -> livingEntity instanceof Enemy && !(livingEntity instanceof Creeper))); this.targetSelector.addGoal(5, new PotatoOwnerHurtByTargetGoal(this));
this.targetSelector.addGoal(6, new PotatoOwnerHurtTargetGoal(this));
1
2023-11-12 10:44:12+00:00
4k
mike1226/SpringMVCExample-01
src/main/java/com/example/servingwebcontent/repository/CustomerMapper.java
[ { "identifier": "CustomerDynamicSqlSupport", "path": "src/main/java/com/example/servingwebcontent/repository/CustomerDynamicSqlSupport.java", "snippet": "public final class CustomerDynamicSqlSupport {\n\n\t@Generated(value = \"org.mybatis.generator.api.MyBatisGenerator\", date = \"2023-11-14T00:52:28.55...
import static com.example.servingwebcontent.repository.CustomerDynamicSqlSupport.*; import static org.mybatis.dynamic.sql.SqlBuilder.*; import java.util.Collection; import java.util.List; import java.util.Optional; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.ResultMap; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.SelectProvider; import org.apache.ibatis.type.JdbcType; import org.mybatis.dynamic.sql.BasicColumn; import org.mybatis.dynamic.sql.delete.DeleteDSLCompleter; import org.mybatis.dynamic.sql.select.CountDSLCompleter; import org.mybatis.dynamic.sql.select.SelectDSLCompleter; import org.mybatis.dynamic.sql.select.render.SelectStatementProvider; import org.mybatis.dynamic.sql.update.UpdateDSL; import org.mybatis.dynamic.sql.update.UpdateDSLCompleter; import org.mybatis.dynamic.sql.update.UpdateModel; import org.mybatis.dynamic.sql.util.SqlProviderAdapter; import org.mybatis.dynamic.sql.util.mybatis3.CommonCountMapper; import org.mybatis.dynamic.sql.util.mybatis3.CommonDeleteMapper; import org.mybatis.dynamic.sql.util.mybatis3.CommonInsertMapper; import org.mybatis.dynamic.sql.util.mybatis3.CommonUpdateMapper; import org.mybatis.dynamic.sql.util.mybatis3.MyBatis3Utils; import com.example.servingwebcontent.entity.Customer; import jakarta.annotation.Generated;
1,918
package com.example.servingwebcontent.repository; @Mapper public interface CustomerMapper
package com.example.servingwebcontent.repository; @Mapper public interface CustomerMapper
extends CommonCountMapper, CommonDeleteMapper, CommonInsertMapper<Customer>, CommonUpdateMapper {
1
2023-11-12 08:22:27+00:00
4k
thewaterfall/fluent-request
src/main/java/com/thewaterfall/request/FluentRequest.java
[ { "identifier": "FluentHttpMethod", "path": "src/main/java/com/thewaterfall/request/misc/FluentHttpMethod.java", "snippet": "public enum FluentHttpMethod {\n GET,\n HEAD,\n POST,\n PUT,\n PATCH,\n DELETE,\n OPTIONS,\n TRACE\n}" }, { "identifier": "FluentIOException", "path": "src/mai...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.thewaterfall.request.misc.FluentHttpMethod; import com.thewaterfall.request.misc.FluentIOException; import com.thewaterfall.request.misc.FluentMappingException; import com.thewaterfall.request.misc.FluentResponse; import okhttp3.*; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit;
2,928
package com.thewaterfall.request; /** * <p>The FluentRequest class is a versatile HTTP request builder that provides a fluent interface * for constructing and sending HTTP requests using the OkHttp library. The builder supports various HTTP methods, * request body types, headers, and authentication methods.</p> * * <p>It uses a predefined OkHttpClient and if it needs to be customized and configured, * use {@link FluentRequest#overrideClient(OkHttpClient)}. Same for Jackson ObjectMapper, * use {@link FluentRequest#overrideMapper(ObjectMapper)}</p> * * <p>Example usage:</p> * <pre>{@code FluentRequest.request("https://api.example.com", Example.class) * .bearer(EXAMPLE_TOKEN) * .body(body) * .post();}</pre> */ public class FluentRequest { private static OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30,TimeUnit.SECONDS) .build(); private static ObjectMapper mapper = new ObjectMapper(); /** * Overrides the default OkHttpClient used for making HTTP requests. * * @param newClient The OkHttpClient to use for HTTP requests. */ private static void overrideClient(OkHttpClient newClient) { client = newClient; } /** * Overrides the default ObjectMapper used for JSON serialization and deserialization. * * @param newMapper The ObjectMapper to use for JSON processing. */ private static void overrideMapper(ObjectMapper newMapper) { mapper = newMapper; } /** * Initiates a new HTTP request builder with the specified URL and response type. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType, OkHttpClient client) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object). * * @param url The URL for the HTTP request. * @param client The OkHttpClient to use for this specific request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url, OkHttpClient client) { return new Builder<>(url, Object.class, client); } /** * Initiates a new HTTP request builder with the specified URL and response type, * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object), * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url) { return new Builder<>(url, Object.class, client); } /** * The Builder class is an inner class of FluentRequest and represents the actual builder * for constructing FluentRequest instances with specific configurations. * * @param <T> The type of the expected response. */ public static class Builder<T> { private OkHttpClient client; private final String url; private final Class<T> responseType; private final Map<String, String> headers; private final Map<String, Object> urlVariables; private final Map<String, Object> queryParameters; private RequestBody body; public Builder(String url, Class<T> responseType) { this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Constructs a new Builder instance with the specified URL, response type, and OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. */ public Builder(String url, Class<T> responseType, OkHttpClient client) { this.client = client; this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Sets the request body for the HTTP request. * * @param body The request body object. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body object to JSON. */ public Builder<T> body(Object body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using key-value pairs. * * @param body The map representing the request body. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body map to JSON. */ public Builder<T> body(Map<String, String> body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using a custom RequestBody. Use * {@link FluentRequest.Builder#multipart()} to build multipart body and * {@link FluentRequest.Builder#form()} to build form body. * * @param body The custom RequestBody. * @return The Builder instance for method chaining. * @see FluentRequest.Builder#multipart() * @see FluentRequest.Builder#form() */ public Builder<T> body(RequestBody body) { this.body = body; return this; } /** * Adds a URL variable to the request. * * @param name The name of the URL variable. * @param value The value of the URL variable. * @return The Builder instance for method chaining. */ public Builder<T> variable(String name, Object value) { if (Objects.nonNull(value)) { this.urlVariables.put(name, String.valueOf(value)); } return this; } /** * Adds multiple URL variables to the request. * * @param variables The map of URL variables. * @return The Builder instance for method chaining. */ public Builder<T> variables(Map<String, Object> variables) { this.urlVariables.putAll(variables); return this; } /** * Adds a query parameter to the request. * * @param name The name of the query parameter. * @param value The value of the query parameter. * @return The Builder instance for method chaining. */ public Builder<T> parameter(String name, Object value) { if (Objects.nonNull(value)) { this.queryParameters.put(name, Collections.singletonList(String.valueOf(value))); } return this; } /** * Adds multiple query parameters to the request. * * @param parameters The map of query parameters. * @return The Builder instance for method chaining. */ public Builder<T> parameters(Map<String, Object> parameters) { this.queryParameters.putAll(parameters); return this; } /** * Adds a header to the request. * * @param name The name of the header. * @param value The value of the header. * @return The Builder instance for method chaining. */ public Builder<T> header(String name, String value) { headers.put(name, value); return this; } /** * Adds a bearer token to the request for bearer authentication. * * @param token The bearer token. * @return The Builder instance for method chaining. */ public Builder<T> bearer(String token) { this.headers.put("Authorization", "Bearer " + token); return this; } /** * Adds basic authentication to the request. * * @param name The username for basic authentication. * @param password The password for basic authentication. * @return The Builder instance for method chaining. */ public Builder<T> basic(String name, String password) { this.headers.put("Authorization", Credentials.basic(name, password)); return this; } /** * Initiates a multipart form data request. * * @return A FluentMultipartBody instance for configuring multipart form data. * @see FluentMultipartBody */ public FluentMultipartBody<T> multipart() { return new FluentMultipartBody<>(this); } /** * Initiates a form-urlencoded request. * * @return A FluentFormBody instance for configuring form-urlencoded parameters. * @see FluentFormBody */ public FluentFormBody<T> form() { return new FluentFormBody<>(this); } /** * Sends a GET request synchronously and returns the response. * * @return The FluentResponse containing the response body and HTTP response details. */
package com.thewaterfall.request; /** * <p>The FluentRequest class is a versatile HTTP request builder that provides a fluent interface * for constructing and sending HTTP requests using the OkHttp library. The builder supports various HTTP methods, * request body types, headers, and authentication methods.</p> * * <p>It uses a predefined OkHttpClient and if it needs to be customized and configured, * use {@link FluentRequest#overrideClient(OkHttpClient)}. Same for Jackson ObjectMapper, * use {@link FluentRequest#overrideMapper(ObjectMapper)}</p> * * <p>Example usage:</p> * <pre>{@code FluentRequest.request("https://api.example.com", Example.class) * .bearer(EXAMPLE_TOKEN) * .body(body) * .post();}</pre> */ public class FluentRequest { private static OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) .readTimeout(30,TimeUnit.SECONDS) .build(); private static ObjectMapper mapper = new ObjectMapper(); /** * Overrides the default OkHttpClient used for making HTTP requests. * * @param newClient The OkHttpClient to use for HTTP requests. */ private static void overrideClient(OkHttpClient newClient) { client = newClient; } /** * Overrides the default ObjectMapper used for JSON serialization and deserialization. * * @param newMapper The ObjectMapper to use for JSON processing. */ private static void overrideMapper(ObjectMapper newMapper) { mapper = newMapper; } /** * Initiates a new HTTP request builder with the specified URL and response type. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType, OkHttpClient client) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object). * * @param url The URL for the HTTP request. * @param client The OkHttpClient to use for this specific request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url, OkHttpClient client) { return new Builder<>(url, Object.class, client); } /** * Initiates a new HTTP request builder with the specified URL and response type, * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param <T> The type of the expected response. * @return A Builder instance for configuring the request. */ public static <T> Builder<T> request(String url, Class<T> responseType) { return new Builder<>(url, responseType, client); } /** * Initiates a new HTTP request builder with the specified URL and default response type (Object), * using the default OkHttpClient. * * @param url The URL for the HTTP request. * @return A Builder instance for configuring the request. */ public static Builder<Object> request(String url) { return new Builder<>(url, Object.class, client); } /** * The Builder class is an inner class of FluentRequest and represents the actual builder * for constructing FluentRequest instances with specific configurations. * * @param <T> The type of the expected response. */ public static class Builder<T> { private OkHttpClient client; private final String url; private final Class<T> responseType; private final Map<String, String> headers; private final Map<String, Object> urlVariables; private final Map<String, Object> queryParameters; private RequestBody body; public Builder(String url, Class<T> responseType) { this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Constructs a new Builder instance with the specified URL, response type, and OkHttpClient. * * @param url The URL for the HTTP request. * @param responseType The class type of the expected response. * @param client The OkHttpClient to use for this specific request. */ public Builder(String url, Class<T> responseType, OkHttpClient client) { this.client = client; this.url = url; this.responseType = responseType; this.urlVariables = new HashMap<>(); this.queryParameters = new HashMap<>(); this.headers = new HashMap<>(); } /** * Sets the request body for the HTTP request. * * @param body The request body object. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body object to JSON. */ public Builder<T> body(Object body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using key-value pairs. * * @param body The map representing the request body. * @return The Builder instance for method chaining. * @throws FluentMappingException If there is an issue with mapping the body map to JSON. */ public Builder<T> body(Map<String, String> body) throws FluentMappingException { this.body = RequestBody.create(getBodyAsString(body), MediaType.get("application/json")); return this; } /** * Sets the request body for the HTTP request using a custom RequestBody. Use * {@link FluentRequest.Builder#multipart()} to build multipart body and * {@link FluentRequest.Builder#form()} to build form body. * * @param body The custom RequestBody. * @return The Builder instance for method chaining. * @see FluentRequest.Builder#multipart() * @see FluentRequest.Builder#form() */ public Builder<T> body(RequestBody body) { this.body = body; return this; } /** * Adds a URL variable to the request. * * @param name The name of the URL variable. * @param value The value of the URL variable. * @return The Builder instance for method chaining. */ public Builder<T> variable(String name, Object value) { if (Objects.nonNull(value)) { this.urlVariables.put(name, String.valueOf(value)); } return this; } /** * Adds multiple URL variables to the request. * * @param variables The map of URL variables. * @return The Builder instance for method chaining. */ public Builder<T> variables(Map<String, Object> variables) { this.urlVariables.putAll(variables); return this; } /** * Adds a query parameter to the request. * * @param name The name of the query parameter. * @param value The value of the query parameter. * @return The Builder instance for method chaining. */ public Builder<T> parameter(String name, Object value) { if (Objects.nonNull(value)) { this.queryParameters.put(name, Collections.singletonList(String.valueOf(value))); } return this; } /** * Adds multiple query parameters to the request. * * @param parameters The map of query parameters. * @return The Builder instance for method chaining. */ public Builder<T> parameters(Map<String, Object> parameters) { this.queryParameters.putAll(parameters); return this; } /** * Adds a header to the request. * * @param name The name of the header. * @param value The value of the header. * @return The Builder instance for method chaining. */ public Builder<T> header(String name, String value) { headers.put(name, value); return this; } /** * Adds a bearer token to the request for bearer authentication. * * @param token The bearer token. * @return The Builder instance for method chaining. */ public Builder<T> bearer(String token) { this.headers.put("Authorization", "Bearer " + token); return this; } /** * Adds basic authentication to the request. * * @param name The username for basic authentication. * @param password The password for basic authentication. * @return The Builder instance for method chaining. */ public Builder<T> basic(String name, String password) { this.headers.put("Authorization", Credentials.basic(name, password)); return this; } /** * Initiates a multipart form data request. * * @return A FluentMultipartBody instance for configuring multipart form data. * @see FluentMultipartBody */ public FluentMultipartBody<T> multipart() { return new FluentMultipartBody<>(this); } /** * Initiates a form-urlencoded request. * * @return A FluentFormBody instance for configuring form-urlencoded parameters. * @see FluentFormBody */ public FluentFormBody<T> form() { return new FluentFormBody<>(this); } /** * Sends a GET request synchronously and returns the response. * * @return The FluentResponse containing the response body and HTTP response details. */
public FluentResponse<T> get() throws FluentIOException {
3
2023-11-14 12:53:50+00:00
4k
wangxianhui111/xuechengzaixian
xuecheng-plus-media/xuecheng-plus-media-service/src/main/java/com/xuecheng/media/service/impl/MediaFileProcessServiceImpl.java
[ { "identifier": "MediaFilesMapper", "path": "xuecheng-plus-media/xuecheng-plus-media-service/src/main/java/com/xuecheng/media/mapper/MediaFilesMapper.java", "snippet": "public interface MediaFilesMapper extends BaseMapper<MediaFiles> {\n\n}" }, { "identifier": "MediaProcessHistoryMapper", "p...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.xuecheng.media.mapper.MediaFilesMapper; import com.xuecheng.media.mapper.MediaProcessHistoryMapper; import com.xuecheng.media.mapper.MediaProcessMapper; import com.xuecheng.media.model.po.MediaFiles; import com.xuecheng.media.model.po.MediaProcess; import com.xuecheng.media.model.po.MediaProcessHistory; import com.xuecheng.media.service.MediaFileProcessService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.time.LocalDateTime; import java.util.List; import java.util.Objects;
2,037
package com.xuecheng.media.service.impl; /** * 视频处理服务实现类 * * @author Wuxy * @version 1.0 * @ClassName MediaFileProcessServiceImpl * @since 2023/1/25 16:09 */ @Slf4j @Service public class MediaFileProcessServiceImpl implements MediaFileProcessService { @Resource private MediaFilesMapper mediaFilesMapper; @Resource
package com.xuecheng.media.service.impl; /** * 视频处理服务实现类 * * @author Wuxy * @version 1.0 * @ClassName MediaFileProcessServiceImpl * @since 2023/1/25 16:09 */ @Slf4j @Service public class MediaFileProcessServiceImpl implements MediaFileProcessService { @Resource private MediaFilesMapper mediaFilesMapper; @Resource
private MediaProcessMapper mediaProcessMapper;
2
2023-11-13 11:39:35+00:00
4k
dynatrace-research/ShuffleBench
shuffle-hzcast/src/main/java/com/dynatrace/research/shufflebench/HazelcastShuffle.java
[ { "identifier": "AdvancedStateConsumer", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/AdvancedStateConsumer.java", "snippet": "public class AdvancedStateConsumer implements StatefulConsumer {\n\n private static final long serialVersionUID = 0L;\n\n private static final i...
import com.dynatrace.research.shufflebench.consumer.AdvancedStateConsumer; import com.dynatrace.research.shufflebench.consumer.State; import com.dynatrace.research.shufflebench.consumer.StatefulConsumer; import com.dynatrace.research.shufflebench.matcher.MatcherService; import com.dynatrace.research.shufflebench.matcher.SimpleMatcherService; import com.dynatrace.research.shufflebench.record.*; import com.hazelcast.config.JoinConfig; import com.hazelcast.core.Hazelcast; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.jet.Job; import com.hazelcast.jet.Traversers; import com.hazelcast.jet.Util; import com.hazelcast.jet.config.EdgeConfig; import com.hazelcast.jet.config.JobConfig; import com.hazelcast.jet.config.ProcessingGuarantee; import com.hazelcast.jet.kafka.KafkaSinks; import com.hazelcast.jet.kafka.KafkaSources; import com.hazelcast.jet.pipeline.Pipeline; import com.hazelcast.jet.pipeline.ServiceFactory; import com.hazelcast.spi.properties.ClusterProperty; import io.smallrye.config.SmallRyeConfig; import java.util.Map; import java.util.Optional; import java.util.Properties; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.ByteArrayDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.eclipse.microprofile.config.Config; import org.eclipse.microprofile.config.ConfigProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.hazelcast.jet.pipeline.ServiceFactories.nonSharedService;
3,127
package com.dynatrace.research.shufflebench; public class HazelcastShuffle { private static final String APPLICATION_ID = "shufflebench-hzcast"; private static final Logger LOGGER = LoggerFactory.getLogger(HazelcastShuffle.class); private final Pipeline pipeline; private HazelcastInstance hazelcast; public HazelcastShuffle() { final SmallRyeConfig config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class); final Properties kafkaProps = new Properties(); kafkaProps.put( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getValue("kafka.bootstrap.servers", String.class)); final Properties kafkaConsumerProps = new Properties(); kafkaConsumerProps.putAll(kafkaProps); kafkaConsumerProps.put( ConsumerConfig.GROUP_ID_CONFIG, APPLICATION_ID); // props.put( // ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, // true); kafkaConsumerProps.put( ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class); kafkaConsumerProps.put( ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, RecordSerde.RecordDeserializer.class); kafkaConsumerProps.putAll( config.getOptionalValues("kafka.consumer", String.class, String.class).orElse(Map.of())); final Properties kafkaProducerProps = new Properties(); kafkaProducerProps.putAll(kafkaProps); kafkaProducerProps.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); kafkaProducerProps.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ConsumerEventSerde.ConsumerEventSerializer.class); kafkaProducerProps.putAll( config.getOptionalValues("kafka.producer", String.class, String.class).orElse(Map.of())); final String kafkaInputTopic = config.getValue("kafka.topic.input", String.class); final String kafkaOutputTopic = config.getValue("kafka.topic.output", String.class); final SmallRyeConfig smallRyeConfig = config.unwrap(SmallRyeConfig.class); final Map<Double, Integer> selectivities = smallRyeConfig.getOptionalValues("matcher.selectivities", Double.class, Integer.class).orElse(null); final double totalSelectivity = config.getValue("matcher.zipf.total.selectivity", Double.class); final int numRules = config.getValue("matcher.zipf.num.rules", Integer.class); final double s = config.getValue("matcher.zipf.s", Double.class); final int outputRate = config.getValue("consumer.output.rate", Integer.class); final int stateSizeBytes = config.getValue("consumer.state.size.bytes", Integer.class); final boolean initCountRandom = config.getValue("consumer.init.count.random", Boolean.class); final long initCountSeed = config.getValue("consumer.init.count.seed", Long.class); ServiceFactory<?, MatcherService<TimestampedRecord>> matcherServiceFactory = nonSharedService( pctx -> { if (selectivities != null) { return SimpleMatcherService.createFromFrequencyMap(selectivities, 0x2e3fac4f58fc98b4L); } else { return SimpleMatcherService.createFromZipf( numRules, totalSelectivity, s, 0x2e3fac4f58fc98b4L); } });
package com.dynatrace.research.shufflebench; public class HazelcastShuffle { private static final String APPLICATION_ID = "shufflebench-hzcast"; private static final Logger LOGGER = LoggerFactory.getLogger(HazelcastShuffle.class); private final Pipeline pipeline; private HazelcastInstance hazelcast; public HazelcastShuffle() { final SmallRyeConfig config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class); final Properties kafkaProps = new Properties(); kafkaProps.put( ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, config.getValue("kafka.bootstrap.servers", String.class)); final Properties kafkaConsumerProps = new Properties(); kafkaConsumerProps.putAll(kafkaProps); kafkaConsumerProps.put( ConsumerConfig.GROUP_ID_CONFIG, APPLICATION_ID); // props.put( // ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, // true); kafkaConsumerProps.put( ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class); kafkaConsumerProps.put( ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, RecordSerde.RecordDeserializer.class); kafkaConsumerProps.putAll( config.getOptionalValues("kafka.consumer", String.class, String.class).orElse(Map.of())); final Properties kafkaProducerProps = new Properties(); kafkaProducerProps.putAll(kafkaProps); kafkaProducerProps.put( ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); kafkaProducerProps.put( ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ConsumerEventSerde.ConsumerEventSerializer.class); kafkaProducerProps.putAll( config.getOptionalValues("kafka.producer", String.class, String.class).orElse(Map.of())); final String kafkaInputTopic = config.getValue("kafka.topic.input", String.class); final String kafkaOutputTopic = config.getValue("kafka.topic.output", String.class); final SmallRyeConfig smallRyeConfig = config.unwrap(SmallRyeConfig.class); final Map<Double, Integer> selectivities = smallRyeConfig.getOptionalValues("matcher.selectivities", Double.class, Integer.class).orElse(null); final double totalSelectivity = config.getValue("matcher.zipf.total.selectivity", Double.class); final int numRules = config.getValue("matcher.zipf.num.rules", Integer.class); final double s = config.getValue("matcher.zipf.s", Double.class); final int outputRate = config.getValue("consumer.output.rate", Integer.class); final int stateSizeBytes = config.getValue("consumer.state.size.bytes", Integer.class); final boolean initCountRandom = config.getValue("consumer.init.count.random", Boolean.class); final long initCountSeed = config.getValue("consumer.init.count.seed", Long.class); ServiceFactory<?, MatcherService<TimestampedRecord>> matcherServiceFactory = nonSharedService( pctx -> { if (selectivities != null) { return SimpleMatcherService.createFromFrequencyMap(selectivities, 0x2e3fac4f58fc98b4L); } else { return SimpleMatcherService.createFromZipf( numRules, totalSelectivity, s, 0x2e3fac4f58fc98b4L); } });
final StatefulConsumer consumer = new AdvancedStateConsumer("counter", outputRate, stateSizeBytes, initCountRandom, initCountSeed);
2
2023-11-17 08:53:15+00:00
4k
KafeinDev/InteractiveNpcs
src/main/java/dev/kafein/interactivenpcs/InteractiveNpcs.java
[ { "identifier": "Command", "path": "src/main/java/dev/kafein/interactivenpcs/command/Command.java", "snippet": "public interface Command {\n CommandProperties getProperties();\n\n String getName();\n\n List<String> getAliases();\n\n boolean isAlias(@NotNull String alias);\n\n String getDe...
import com.google.common.collect.ImmutableSet; import dev.kafein.interactivenpcs.command.Command; import dev.kafein.interactivenpcs.commands.InteractionCommand; import dev.kafein.interactivenpcs.compatibility.Compatibility; import dev.kafein.interactivenpcs.compatibility.CompatibilityFactory; import dev.kafein.interactivenpcs.compatibility.CompatibilityType; import dev.kafein.interactivenpcs.configuration.Config; import dev.kafein.interactivenpcs.configuration.ConfigVariables; import dev.kafein.interactivenpcs.conversation.ConversationManager; import dev.kafein.interactivenpcs.conversation.text.font.CharWidthMap; import dev.kafein.interactivenpcs.plugin.AbstractBukkitPlugin; import dev.kafein.interactivenpcs.tasks.MovementControlTask; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.scheduler.BukkitScheduler; import java.util.Set;
3,544
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override public Set<Command> getCommands() { return ImmutableSet.of(
package dev.kafein.interactivenpcs; public final class InteractiveNpcs extends AbstractBukkitPlugin { private ConversationManager conversationManager; private CharWidthMap charWidthMap; public InteractiveNpcs(Plugin plugin) { super(plugin); } @Override public void onLoad() {} @Override public void onEnable() { this.charWidthMap = new CharWidthMap(this); this.charWidthMap.initialize(); this.conversationManager = new ConversationManager(this); this.conversationManager.initialize(); PluginManager pluginManager = Bukkit.getPluginManager(); for (CompatibilityType compatibilityType : CompatibilityType.values()) { if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) { continue; } Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this); if (compatibility != null) { compatibility.initialize(); } } } @Override public void onDisable() { } @Override public Set<Command> getCommands() { return ImmutableSet.of(
new InteractionCommand(this)
1
2023-11-18 10:12:16+00:00
4k
ZhiQinIsZhen/dubbo-springboot3
dubbo-service/dubbo-service-staff/staff-biz/src/main/java/com/liyz/boot3/service/staff/provider/RemoteStaffRoleServiceImpl.java
[ { "identifier": "BeanUtil", "path": "dubbo-common/dubbo-common-service/src/main/java/com/liyz/boot3/common/service/util/BeanUtil.java", "snippet": "@UtilityClass\npublic final class BeanUtil {\n\n /**\n * 单个对象拷贝\n *\n * @param source 原对象\n * @param targetSupplier 目标对象\n * @return ...
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.liyz.boot3.common.service.util.BeanUtil; import com.liyz.boot3.service.staff.bo.StaffRoleBO; import com.liyz.boot3.service.staff.model.StaffRoleDO; import com.liyz.boot3.service.staff.remote.RemoteStaffRoleService; import com.liyz.boot3.service.staff.service.StaffRoleService; import org.apache.dubbo.config.annotation.DubboService; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List;
1,823
package com.liyz.boot3.service.staff.provider; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/3/13 13:44 */ @DubboService public class RemoteStaffRoleServiceImpl implements RemoteStaffRoleService { @Resource private StaffRoleService staffRoleService; /** * 给员工绑定一个角色 * * @param staffRoleBO 员工角色参数 * @return 员工角色 */ @Override @Transactional(rollbackFor = Exception.class) public StaffRoleBO bindRole(StaffRoleBO staffRoleBO) {
package com.liyz.boot3.service.staff.provider; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/3/13 13:44 */ @DubboService public class RemoteStaffRoleServiceImpl implements RemoteStaffRoleService { @Resource private StaffRoleService staffRoleService; /** * 给员工绑定一个角色 * * @param staffRoleBO 员工角色参数 * @return 员工角色 */ @Override @Transactional(rollbackFor = Exception.class) public StaffRoleBO bindRole(StaffRoleBO staffRoleBO) {
staffRoleService.save(BeanUtil.copyProperties(staffRoleBO, StaffRoleDO::new));
0
2023-11-13 01:28:21+00:00
4k
glowingstone124/QAPI3
src/main/java/org/qo/UserProcess.java
[ { "identifier": "AvatarCache", "path": "src/main/java/org/qo/server/AvatarCache.java", "snippet": "public class AvatarCache {\n public static final String CachePath = \"avatars/\";\n public static void init() throws IOException {\n if (!Files.exists(Path.of(CachePath))){\n Files....
import jakarta.servlet.http.HttpServletRequest; import org.json.JSONException; import org.json.JSONObject; import org.qo.server.AvatarCache; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.sql.*; import java.util.Calendar; import java.util.Objects; import static org.qo.Logger.LogLevel.*; import static org.qo.Algorithm.hashSHA256;
2,419
result.put("error", e.getMessage()); } return result; } public static boolean SQLAvliable() { boolean success = true; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)){ } catch (SQLException e){ success = false; } return success; } public static boolean queryForum(String username) throws Exception { boolean resultExists = false; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { String selectQuery = "SELECT * FROM forum WHERE username = ?"; Logger.log(selectQuery, INFO); try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) { preparedStatement.setString(1, username); try (ResultSet resultSet = preparedStatement.executeQuery()) { resultExists = resultSet.next(); } } } return resultExists; } public static String queryHash(String hash) throws Exception { String jsonContent = new String(Files.readAllBytes(Path.of(CODE)), StandardCharsets.UTF_8); JSONObject codeObject = new JSONObject(jsonContent); if (codeObject.has(hash)) { String username = codeObject.getString(hash); String finalOutput = username; // codeObject.remove(hash); Files.write(Path.of(CODE), codeObject.toString().getBytes(StandardCharsets.UTF_8)); System.out.println(username); return finalOutput; } else { System.out.println("mismatched"); return null; } } public static String queryArticles(int ArticleID, int ArticleSheets) throws Exception { String ArticleSheet; switch (ArticleSheets){ case 0: ArticleSheet = "serverArticles"; break; case 1: ArticleSheet = "commandArticles"; break; case 2: ArticleSheet = "attractionsArticles"; break; case 3: ArticleSheet = "noticeArticles"; break; default: ArticleSheet = null; break; } try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { String selectQuery = "SELECT * FROM " + ArticleSheet +" WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) { preparedStatement.setInt(1, ArticleID); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { String resultName = resultSet.getString("Name"); return resultName; } else { return null; } } } } } public static String queryReg(String name) throws Exception{ try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM users WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Long uid = resultSet.getLong("uid"); Boolean frozen = resultSet.getBoolean("frozen"); int eco = resultSet.getInt("economy"); JSONObject responseJson = new JSONObject(); responseJson.put("code", 0); responseJson.put("frozen", frozen); responseJson.put("qq", uid); responseJson.put("economy", eco); return responseJson.toString(); } resultSet.close(); preparedStatement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } JSONObject responseJson = new JSONObject(); responseJson.put("code", 1); responseJson.put("qq", -1); return responseJson.toString(); } public static void regforum(String username, String password) throws Exception{ // 解析JSON数据为JSONArray Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从0开始计数的 int day = calendar.get(Calendar.DAY_OF_MONTH); String date = year + "-" + month + "-" + day;
package org.qo; public class UserProcess { public static final String CODE = "users/recoverycode/index.json"; private static final String FILE_PATH = "usermap.json"; private static final String SERVER_FILE_PATH = "playermap.json"; public static final String SQL_CONFIGURATION = "data/sql/info.json"; public static String jdbcUrl = getDatabaseInfo("url"); public static String sqlusername = getDatabaseInfo("username"); public static String sqlpassword = getDatabaseInfo("password"); public static String firstLoginSearch(String name, HttpServletRequest request) { try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM forum WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Boolean first = resultSet.getBoolean("firstLogin"); JSONObject responseJson = new JSONObject(); responseJson.put("code", 0); responseJson.put("first", first); resultSet.close(); preparedStatement.close(); return responseJson.toString(); } String updateQuery = "UPDATE forum SET firstLogin = ? WHERE username = ?"; PreparedStatement apreparedStatement = connection.prepareStatement(updateQuery); apreparedStatement.setBoolean(1, false); apreparedStatement.setString(2, name); Logger.log(IPUtil.getIpAddr(request) + " username " + name + " qureied firstlogin.", INFO); int rowsAffected = apreparedStatement.executeUpdate(); apreparedStatement.close(); connection.close(); resultSet.close(); preparedStatement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } JSONObject responseJson = new JSONObject(); responseJson.put("code", 1); responseJson.put("first", -1); Logger.log(IPUtil.getIpAddr(request) + " username " + name + " qureied firstlogin but unsuccessful.", INFO); return responseJson.toString(); } public static String fetchMyinfo(String name, HttpServletRequest request) throws Exception { String date; Boolean premium; Boolean donate; if (name.isEmpty()) { } try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM forum WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { date = resultSet.getString("date"); premium = resultSet.getBoolean("premium"); donate = resultSet.getBoolean("donate"); String linkto = resultSet.getString("linkto"); JSONObject responseJson = new JSONObject(); responseJson.put("date", date); responseJson.put("premium", premium); responseJson.put("donate", donate); responseJson.put("code", 0); responseJson.put("linkto", linkto); responseJson.put("username", name); Logger.log(IPUtil.getIpAddr(request) + "username " + name + " qureied myinfo.", INFO); return responseJson.toString(); } else { // No rows found for the given username JSONObject responseJson = new JSONObject(); responseJson.put("code", -1); Logger.log(IPUtil.getIpAddr(request) + "username " + name + " qureied myinfo, but unsuccessful.", INFO); return responseJson.toString(); } } catch (SQLException e) { e.printStackTrace(); JSONObject responseJson = new JSONObject(); Logger.log("username " + name + " qureied myinfo, but unsuccessful.", INFO); responseJson.put("code", -1); return responseJson.toString(); } } public static String getDatabaseInfo(String type) { JSONObject sqlObject = null; try { sqlObject = new JSONObject(Files.readString(Path.of(SQL_CONFIGURATION))); } catch (IOException e) { Logger.log("ERROR: SQL CONFIG NOT FOUND",ERROR); } switch (type){ case "password": return sqlObject.getString("password"); case "username": return sqlObject.getString("username"); case "url": return sqlObject.getString("url"); default: return null; } } public static void handleTime(String name, int time){ try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "INSERT INTO timeTables (name, time) VALUES (?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); preparedStatement.setInt(2, time); preparedStatement.executeUpdate(); preparedStatement.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } public static JSONObject getTime(String username) { JSONObject result = null; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { result = new JSONObject(); String query = "SELECT * FROM timeTables WHERE name = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, username); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { int time = resultSet.getInt("time"); result.put("name", username); result.put("time", time); } else { result.put("error", -1); } resultSet.close(); preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); result.put("error", e.getMessage()); } return result; } public static boolean SQLAvliable() { boolean success = true; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)){ } catch (SQLException e){ success = false; } return success; } public static boolean queryForum(String username) throws Exception { boolean resultExists = false; try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { String selectQuery = "SELECT * FROM forum WHERE username = ?"; Logger.log(selectQuery, INFO); try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) { preparedStatement.setString(1, username); try (ResultSet resultSet = preparedStatement.executeQuery()) { resultExists = resultSet.next(); } } } return resultExists; } public static String queryHash(String hash) throws Exception { String jsonContent = new String(Files.readAllBytes(Path.of(CODE)), StandardCharsets.UTF_8); JSONObject codeObject = new JSONObject(jsonContent); if (codeObject.has(hash)) { String username = codeObject.getString(hash); String finalOutput = username; // codeObject.remove(hash); Files.write(Path.of(CODE), codeObject.toString().getBytes(StandardCharsets.UTF_8)); System.out.println(username); return finalOutput; } else { System.out.println("mismatched"); return null; } } public static String queryArticles(int ArticleID, int ArticleSheets) throws Exception { String ArticleSheet; switch (ArticleSheets){ case 0: ArticleSheet = "serverArticles"; break; case 1: ArticleSheet = "commandArticles"; break; case 2: ArticleSheet = "attractionsArticles"; break; case 3: ArticleSheet = "noticeArticles"; break; default: ArticleSheet = null; break; } try (Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword)) { String selectQuery = "SELECT * FROM " + ArticleSheet +" WHERE id = ?"; try (PreparedStatement preparedStatement = connection.prepareStatement(selectQuery)) { preparedStatement.setInt(1, ArticleID); try (ResultSet resultSet = preparedStatement.executeQuery()) { if (resultSet.next()) { String resultName = resultSet.getString("Name"); return resultName; } else { return null; } } } } } public static String queryReg(String name) throws Exception{ try { Connection connection = DriverManager.getConnection(jdbcUrl, sqlusername, sqlpassword); String query = "SELECT * FROM users WHERE username = ?"; PreparedStatement preparedStatement = connection.prepareStatement(query); preparedStatement.setString(1, name); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { Long uid = resultSet.getLong("uid"); Boolean frozen = resultSet.getBoolean("frozen"); int eco = resultSet.getInt("economy"); JSONObject responseJson = new JSONObject(); responseJson.put("code", 0); responseJson.put("frozen", frozen); responseJson.put("qq", uid); responseJson.put("economy", eco); return responseJson.toString(); } resultSet.close(); preparedStatement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } JSONObject responseJson = new JSONObject(); responseJson.put("code", 1); responseJson.put("qq", -1); return responseJson.toString(); } public static void regforum(String username, String password) throws Exception{ // 解析JSON数据为JSONArray Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 注意月份是从0开始计数的 int day = calendar.get(Calendar.DAY_OF_MONTH); String date = year + "-" + month + "-" + day;
String EncryptedPswd = hashSHA256(password);
2
2023-11-15 13:38:53+00:00
4k
RaniAgus/java-docker-tutorial
src/main/java/io/github/raniagus/example/Application.java
[ { "identifier": "Bootstrap", "path": "src/main/java/io/github/raniagus/example/bootstrap/Bootstrap.java", "snippet": "public class Bootstrap implements Runnable, WithSimplePersistenceUnit {\n private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);\n\n public static void main(String...
import gg.jte.ContentType; import gg.jte.TemplateEngine; import gg.jte.output.StringOutput; import gg.jte.resolve.DirectoryCodeResolver; import io.github.flbulgarelli.jpa.extras.simple.WithSimplePersistenceUnit; import io.github.raniagus.example.bootstrap.Bootstrap; import io.github.raniagus.example.constants.Routes; import io.github.raniagus.example.controller.ErrorController; import io.github.raniagus.example.controller.HomeController; import io.github.raniagus.example.controller.LoginController; import io.github.raniagus.example.exception.ShouldLoginException; import io.github.raniagus.example.exception.UserNotAuthorizedException; import io.github.raniagus.example.model.Rol; import io.javalin.Javalin; import io.javalin.http.staticfiles.Location; import java.nio.file.Path; import java.time.LocalDate;
1,670
package io.github.raniagus.example; public class Application { public static final Config config = Config.create(); public static void main(String[] args) { startDatabaseConnection(); if (config.databaseHbm2ddlAuto().equals("create-drop")) { new Bootstrap().run(); } startServer(); } public static void startDatabaseConnection() { WithSimplePersistenceUnit.configure(properties -> properties.putAll(config.getHibernateProperties())); WithSimplePersistenceUnit.dispose(); } @SuppressWarnings("java:S2095") public static void startServer() { var app = Javalin.create(config -> { var templateEngine = createTemplateEngine(); config.fileRenderer((filePath, model, ctx) -> { var output = new StringOutput(); templateEngine.render(filePath, model.get("view"), output); return output.toString(); }); config.staticFiles.add("public", Location.CLASSPATH); config.validation.register(LocalDate.class, LocalDate::parse); }); app.beforeMatched(LoginController.INSTANCE::handleSession); app.get(Routes.HOME, HomeController.INSTANCE::renderHome, Rol.USER, Rol.ADMIN); app.get(Routes.LOGIN, LoginController.INSTANCE::renderLogin); app.post(Routes.LOGIN, LoginController.INSTANCE::performLogin); app.post(Routes.LOGOUT, LoginController.INSTANCE::performLogout);
package io.github.raniagus.example; public class Application { public static final Config config = Config.create(); public static void main(String[] args) { startDatabaseConnection(); if (config.databaseHbm2ddlAuto().equals("create-drop")) { new Bootstrap().run(); } startServer(); } public static void startDatabaseConnection() { WithSimplePersistenceUnit.configure(properties -> properties.putAll(config.getHibernateProperties())); WithSimplePersistenceUnit.dispose(); } @SuppressWarnings("java:S2095") public static void startServer() { var app = Javalin.create(config -> { var templateEngine = createTemplateEngine(); config.fileRenderer((filePath, model, ctx) -> { var output = new StringOutput(); templateEngine.render(filePath, model.get("view"), output); return output.toString(); }); config.staticFiles.add("public", Location.CLASSPATH); config.validation.register(LocalDate.class, LocalDate::parse); }); app.beforeMatched(LoginController.INSTANCE::handleSession); app.get(Routes.HOME, HomeController.INSTANCE::renderHome, Rol.USER, Rol.ADMIN); app.get(Routes.LOGIN, LoginController.INSTANCE::renderLogin); app.post(Routes.LOGIN, LoginController.INSTANCE::performLogin); app.post(Routes.LOGOUT, LoginController.INSTANCE::performLogout);
app.exception(ShouldLoginException.class, (e, ctx) -> ErrorController.INSTANCE.handleShouldLogin(ctx));
2
2023-11-12 15:14:24+00:00
4k
innogames/flink-real-time-crm-ui
src/main/java/com/innogames/analytics/rtcrmui/controller/IndexController.java
[ { "identifier": "Campaign", "path": "src/main/java/com/innogames/analytics/rtcrmui/entity/Campaign.java", "snippet": "@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)\npublic class Campaign {\n\n\tprivate int campaignId;\n\tprivate boolean enabled;\n\tprivate String game;\n\tprivate String ...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.innogames.analytics.rtcrmui.entity.Campaign; import com.innogames.analytics.rtcrmui.entity.TrackingEvent; import com.innogames.analytics.rtcrmui.kafka.StringProducer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.servlet.view.RedirectView;
1,869
package com.innogames.analytics.rtcrmui.controller; @Controller public class IndexController { private static final ObjectMapper objectMapper = new ObjectMapper(); @Autowired private StringProducer stringProducer; @Autowired private SimpMessagingTemplate template; @GetMapping("/") public String home(final Model model) { model.addAttribute("module", "index"); return "index"; } @PostMapping("/event") public RedirectView sendEvent(@RequestBody final String eventJson) { try {
package com.innogames.analytics.rtcrmui.controller; @Controller public class IndexController { private static final ObjectMapper objectMapper = new ObjectMapper(); @Autowired private StringProducer stringProducer; @Autowired private SimpMessagingTemplate template; @GetMapping("/") public String home(final Model model) { model.addAttribute("module", "index"); return "index"; } @PostMapping("/event") public RedirectView sendEvent(@RequestBody final String eventJson) { try {
final TrackingEvent trackingEvent = objectMapper.readValue(eventJson, TrackingEvent.class);
1
2023-11-12 18:07:20+00:00
4k
heldermartins4/RPG_Pokemon
src/main/java/interfaces/GamePanel.java
[ { "identifier": "KeyHandler", "path": "src/main/java/controllers/controls/KeyHandler.java", "snippet": "public class KeyHandler implements KeyListener {\n\n public boolean up, down, left, right;\n\n public KeyHandler() {\n up = down = left = right = false;\n }\n\n @Override\n publi...
import javax.swing.JPanel; import controllers.controls.KeyHandler; import controllers.entity.Player; import interfaces.map.Map; import interfaces.start.Start; import java.awt.*;
3,230
package interfaces; public class GamePanel extends JPanel implements Runnable { Map map = new Map("map_1"); public KeyHandler key = new KeyHandler(); Player player;
package interfaces; public class GamePanel extends JPanel implements Runnable { Map map = new Map("map_1"); public KeyHandler key = new KeyHandler(); Player player;
Start start_panel;
3
2023-11-12 16:44:00+00:00
4k
kigangka/iotdb-server
src/main/java/com/kit/iotdb/controller/WeatherController.java
[ { "identifier": "Constant", "path": "src/main/java/com/kit/iotdb/common/utils/Constant.java", "snippet": "public class Constant {\n\n /**\n * 空气质量选项\n */\n public final static String[] QUALITY_OPTIONS = new String[]{\"优\", \"良\", \"中\", \"差\"};\n}" }, { "identifier": "Rst", "pa...
import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.StrUtil; import com.kit.iotdb.common.utils.Constant; import com.kit.iotdb.common.utils.Rst; import com.kit.iotdb.entity.WeatherEntity; import com.kit.iotdb.service.WeatherService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import java.math.RoundingMode; import java.util.Date;
1,697
package com.kit.iotdb.controller; /** * 添加说明 * * @author kit * @version 1.0 * @date 2023/11/7 16:50 */ @RestController @RequestMapping("/weather") public class WeatherController { @Resource WeatherService weatherService; /** * 新增 * * @return */ @GetMapping("add") public Rst add() { Date date = new Date(); // 模拟数据 // 此处涉及到的字符串的,必须前后加',如下面的city字段,quality字段, remark字段 WeatherEntity testEntity = WeatherEntity.builder() .samplingTime(date.getTime()) .samplingTimeStr("'" + DateUtil.format(date, "yyyy-MM-dd HH:mm:ss") + "'") .cityKey(101190101) .city("'南京'") .temperature(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(-18.2, 30.5, 1, RoundingMode.HALF_UP)))) .humidity(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(1, 100, 1, RoundingMode.HALF_UP)))) .pm10(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 0, RoundingMode.HALF_UP)))) .pm25(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 1, RoundingMode.HALF_UP))))
package com.kit.iotdb.controller; /** * 添加说明 * * @author kit * @version 1.0 * @date 2023/11/7 16:50 */ @RestController @RequestMapping("/weather") public class WeatherController { @Resource WeatherService weatherService; /** * 新增 * * @return */ @GetMapping("add") public Rst add() { Date date = new Date(); // 模拟数据 // 此处涉及到的字符串的,必须前后加',如下面的city字段,quality字段, remark字段 WeatherEntity testEntity = WeatherEntity.builder() .samplingTime(date.getTime()) .samplingTimeStr("'" + DateUtil.format(date, "yyyy-MM-dd HH:mm:ss") + "'") .cityKey(101190101) .city("'南京'") .temperature(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(-18.2, 30.5, 1, RoundingMode.HALF_UP)))) .humidity(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(1, 100, 1, RoundingMode.HALF_UP)))) .pm10(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 0, RoundingMode.HALF_UP)))) .pm25(NumberUtil.parseFloat(StrUtil.toString(RandomUtil.randomDouble(0, 300, 1, RoundingMode.HALF_UP))))
.quality("'" + Constant.QUALITY_OPTIONS[RandomUtil.randomInt(0, 3)] + "'")
0
2023-11-15 06:04:04+00:00
4k
penyoofficial/HerbMS
src/main/java/com/penyo/herbms/controller/PrescriptionController.java
[ { "identifier": "Prescription", "path": "src/main/java/com/penyo/herbms/pojo/Prescription.java", "snippet": "public class Prescription extends GenericBean {\n /**\n * 唯一识别码\n */\n private int id;\n /**\n * 中草药处方 ID(外键)\n */\n private int prescriptionId;\n /**\n * 中草药 ID(外键)\n */\n priv...
import com.penyo.herbms.pojo.Prescription; import com.penyo.herbms.pojo.PrescriptionInfo; import com.penyo.herbms.pojo.ReturnDataPack; import com.penyo.herbms.service.HerbService; import com.penyo.herbms.service.PrescriptionService; import java.util.ArrayList; import java.util.List; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
1,840
package com.penyo.herbms.controller; /** * 处方的控制器代理 * * @author Penyo * @see Prescription * @see GenericController */ @Controller public class PrescriptionController extends GenericController<Prescription> { @Override @RequestMapping("/use-prescriptions") @ResponseBody public String requestMain(HttpServletRequest request) {
package com.penyo.herbms.controller; /** * 处方的控制器代理 * * @author Penyo * @see Prescription * @see GenericController */ @Controller public class PrescriptionController extends GenericController<Prescription> { @Override @RequestMapping("/use-prescriptions") @ResponseBody public String requestMain(HttpServletRequest request) {
return requestMain(toMap(request), getService(PrescriptionService.class)).toString();
4
2023-11-13 16:40:05+00:00
4k
martin-bian/DimpleBlog
dimple-blog/src/main/java/com/dimple/service/impl/TagServiceImpl.java
[ { "identifier": "Tag", "path": "dimple-blog/src/main/java/com/dimple/domain/Tag.java", "snippet": "@Data\n@Entity\n@Table(name = \"bg_tag\")\npublic class Tag extends BaseEntity implements Serializable {\n @Id\n @Column(name = \"tag_id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n ...
import com.dimple.domain.Tag; import com.dimple.mapstruct.TagMapper; import com.dimple.repository.TagRepository; import com.dimple.service.Dto.TagCriteria; import com.dimple.service.TagService; import com.dimple.exception.BadRequestException; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Map; import java.util.Set;
2,297
package com.dimple.service.impl; /** * @className: TagServiceImpl * @description: * @author: Dimple * @date: 06/19/20 */ @Service @Slf4j @RequiredArgsConstructor public class TagServiceImpl implements TagService {
package com.dimple.service.impl; /** * @className: TagServiceImpl * @description: * @author: Dimple * @date: 06/19/20 */ @Service @Slf4j @RequiredArgsConstructor public class TagServiceImpl implements TagService {
private final TagRepository tagRepository;
2
2023-11-10 03:30:36+00:00
4k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/component/codeintput/intputscutcheon/labelscutcheon/CustomVariableLabel.java
[ { "identifier": "LabelElementName", "path": "database/src/main/java/com/lazycoder/database/common/LabelElementName.java", "snippet": "public class LabelElementName {\n\n\t/**\n\t * 内容输入 t !!\n\t */\n\tpublic static final String TEXT_INPUT = \"textInput\";\n\n\t/**\n\t * 选择 c !!\n\t */\n\tpublic static f...
import com.lazycoder.database.common.LabelElementName; import com.lazycoder.service.fileStructure.SysFileStructure; import com.lazycoder.service.vo.element.lable.BaseLableElement; import com.lazycoder.uidatasourceedit.component.codeintput.inputmeta.pane.base.PassingComponentParams; import com.lazycoder.uiutils.mycomponent.MyButton; import java.awt.Dimension; import java.io.File; import javax.swing.ImageIcon;
3,080
package com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon; public class CustomVariableLabel extends MyButton implements LabelComponentIntetface { /** * 多个变量 */ public final static ImageIcon CUSTOM_ARRAY_ICON = new ImageIcon( SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + "code_content_edit" + File.separator + "base_code_content_edit" + File.separator + "label_element" + File.separator + "custom_variable" + File.separator + "custom_array.png"); /** * */ private static final long serialVersionUID = -3492363933786387477L; private PassingComponentParams passingComponentParams = null; /** * 添加在daima面板 */ public CustomVariableLabel() { super(CUSTOM_ARRAY_ICON); Dimension dd = new Dimension(80, 30); this.setMaximumSize(dd); this.setMinimumSize(dd); this.setPreferredSize(dd); this.setFocusPainted(false); } @Override public void deleteFromPanel() { // TODO Auto-generated method stub } @Override public String getLabelType() { // TODO Auto-generated method stub return LabelElementName.CUSTOM_VARIABLE; } @Override public PassingComponentParams getPassingComponentParams() { // TODO Auto-generated method stub return passingComponentParams; } @Override public void setPassingComponentParams(PassingComponentParams passingComponentParams) { // TODO Auto-generated method stub this.passingComponentParams = passingComponentParams; LabelComponentIntetface.addCorrespondingComponentResponseListener(this); } @Override public void setNavigate(boolean flag) { } @Override
package com.lazycoder.uidatasourceedit.component.codeintput.intputscutcheon.labelscutcheon; public class CustomVariableLabel extends MyButton implements LabelComponentIntetface { /** * 多个变量 */ public final static ImageIcon CUSTOM_ARRAY_ICON = new ImageIcon( SysFileStructure.getImageFolder().getAbsolutePath() + File.separator + "code_content_edit" + File.separator + "base_code_content_edit" + File.separator + "label_element" + File.separator + "custom_variable" + File.separator + "custom_array.png"); /** * */ private static final long serialVersionUID = -3492363933786387477L; private PassingComponentParams passingComponentParams = null; /** * 添加在daima面板 */ public CustomVariableLabel() { super(CUSTOM_ARRAY_ICON); Dimension dd = new Dimension(80, 30); this.setMaximumSize(dd); this.setMinimumSize(dd); this.setPreferredSize(dd); this.setFocusPainted(false); } @Override public void deleteFromPanel() { // TODO Auto-generated method stub } @Override public String getLabelType() { // TODO Auto-generated method stub return LabelElementName.CUSTOM_VARIABLE; } @Override public PassingComponentParams getPassingComponentParams() { // TODO Auto-generated method stub return passingComponentParams; } @Override public void setPassingComponentParams(PassingComponentParams passingComponentParams) { // TODO Auto-generated method stub this.passingComponentParams = passingComponentParams; LabelComponentIntetface.addCorrespondingComponentResponseListener(this); } @Override public void setNavigate(boolean flag) { } @Override
public BaseLableElement property() {
2
2023-11-16 11:55:06+00:00
4k
hardingadonis/miu-shop
src/main/java/io/hardingadonis/miu/controller/admin/AddNewProduct.java
[ { "identifier": "Product", "path": "src/main/java/io/hardingadonis/miu/model/Product.java", "snippet": "public class Product {\n\n private int ID;\n private String brand;\n private String name;\n private int categoryID;\n private String origin;\n private String expiryDate;\n private...
import io.hardingadonis.miu.model.Product; import io.hardingadonis.miu.services.Singleton; import java.io.*; import java.time.LocalDateTime; import java.util.Collections; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*;
2,015
package io.hardingadonis.miu.controller.admin; @WebServlet(name = "AddNewProduct", urlPatterns = {"/admin/new-product"}) public class AddNewProduct extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); request.getRequestDispatcher("/view/admin/add-new-product.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String nameProduct = request.getParameter("productName"); String productBrand = request.getParameter("productBrand"); int Category_ID = Integer.parseInt(request.getParameter("productCategoryID")); String productOrigin = request.getParameter("productOrigin"); String productExpiry = request.getParameter("productExpiry"); String productWeight = request.getParameter("productWeight"); String productPreservation = request.getParameter("productPreservation"); long productPrice = Long.parseLong(request.getParameter("productPrice")); int productAmount = Integer.parseInt(request.getParameter("productAmount")); Product product = new Product(); product.setName(nameProduct); product.setBrand(productBrand); product.setCategoryID(Category_ID); product.setOrigin(productOrigin); product.setExpiryDate(productExpiry); product.setWeight(productWeight); product.setPreservation(productPreservation); product.setPrice(productPrice); product.setAmount(productAmount); product.setThumbnail(""); product.setImages(Collections.EMPTY_LIST);
package io.hardingadonis.miu.controller.admin; @WebServlet(name = "AddNewProduct", urlPatterns = {"/admin/new-product"}) public class AddNewProduct extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); request.getRequestDispatcher("/view/admin/add-new-product.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); String nameProduct = request.getParameter("productName"); String productBrand = request.getParameter("productBrand"); int Category_ID = Integer.parseInt(request.getParameter("productCategoryID")); String productOrigin = request.getParameter("productOrigin"); String productExpiry = request.getParameter("productExpiry"); String productWeight = request.getParameter("productWeight"); String productPreservation = request.getParameter("productPreservation"); long productPrice = Long.parseLong(request.getParameter("productPrice")); int productAmount = Integer.parseInt(request.getParameter("productAmount")); Product product = new Product(); product.setName(nameProduct); product.setBrand(productBrand); product.setCategoryID(Category_ID); product.setOrigin(productOrigin); product.setExpiryDate(productExpiry); product.setWeight(productWeight); product.setPreservation(productPreservation); product.setPrice(productPrice); product.setAmount(productAmount); product.setThumbnail(""); product.setImages(Collections.EMPTY_LIST);
Singleton.productDAO.insert(product);
1
2023-11-16 07:15:44+00:00
4k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/stream/StreamTxThread.java
[ { "identifier": "HomePacket", "path": "app/src/main/java/kr/or/kashi/hde/HomePacket.java", "snippet": "public interface HomePacket {\n String address();\n int command();\n byte[] data();\n\n int hashCode();\n boolean parse(ByteBuffer buffer) throws BufferUnderflowException;\n void toBu...
import android.util.Log; import java.io.IOException; import java.io.OutputStream; import java.lang.InterruptedException; import java.nio.ByteBuffer; import java.util.ArrayDeque; import kr.or.kashi.hde.HomePacket; import kr.or.kashi.hde.util.Utils;
1,637
/* * 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.stream; public class StreamTxThread extends Thread { private static final String TAG = StreamTxThread.class.getSimpleName(); private static final boolean DBG = true; private final OutputStream mOutputStream; private final StreamCallback mCallback;
/* * 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.stream; public class StreamTxThread extends Thread { private static final String TAG = StreamTxThread.class.getSimpleName(); private static final boolean DBG = true; private final OutputStream mOutputStream; private final StreamCallback mCallback;
private final ArrayDeque<HomePacket> mPacketQueue = new ArrayDeque<>();
0
2023-11-10 01:19:44+00:00
4k
Bug1312/dm_locator
src/main/java/com/bug1312/dm_locator/network/PacketRequestLocate.java
[ { "identifier": "Config", "path": "src/main/java/com/bug1312/dm_locator/Config.java", "snippet": "public class Config {\n\tpublic static final ForgeConfigSpec SERVER_SPEC;\n\tpublic static final ServerConfig SERVER_CONFIG;\n\n\tstatic {\n\t\tPair<ServerConfig, ForgeConfigSpec> serverConfigPair = new For...
import java.util.Optional; import java.util.function.Consumer; import java.util.function.Supplier; import com.bug1312.dm_locator.Config; import com.bug1312.dm_locator.Register; import com.bug1312.dm_locator.StructureHelper; import com.bug1312.dm_locator.particle.LocateParticleData; import com.swdteam.common.init.DMFlightMode; import com.swdteam.common.init.DMTardis; import com.swdteam.common.init.DMTranslationKeys; import com.swdteam.common.tardis.TardisData; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.nbt.CompoundNBT; import net.minecraft.network.PacketBuffer; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.vector.Vector3d; import net.minecraft.util.registry.Registry; import net.minecraft.util.text.Style; import net.minecraft.util.text.TextFormatting; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.biome.Biome; import net.minecraft.world.gen.feature.structure.Structure; import net.minecraftforge.fml.network.NetworkEvent; import net.minecraftforge.registries.ForgeRegistries;
3,429
// Copyright 2023 Bug1312 (bug@bug1312.com) package com.bug1312.dm_locator.network; public class PacketRequestLocate { public PacketRequestLocate() {} public static void encode(PacketRequestLocate msg, PacketBuffer buf) {} public static PacketRequestLocate decode(PacketBuffer buf) {return new PacketRequestLocate();} public static void handle(PacketRequestLocate msg, Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayerEntity player = ctx.get().getSender(); if (StructureHelper.FLYING_PLAYERS_LOCATOR.containsKey(player.getUUID())) { Consumer<TranslationTextComponent> sendError = (text) -> player.displayClientMessage(text.setStyle(Style.EMPTY.withColor(TextFormatting.RED)), true); Consumer<Vector3d> toLocation = (end) -> { Vector3d start = player.position(); Vector3d direction = end.subtract(start); if (direction.length() > 15) direction = direction.normalize().scale(15); Vector3d limitedEnd = start.add(direction); Register.TRIGGER_USE.trigger(player);
// Copyright 2023 Bug1312 (bug@bug1312.com) package com.bug1312.dm_locator.network; public class PacketRequestLocate { public PacketRequestLocate() {} public static void encode(PacketRequestLocate msg, PacketBuffer buf) {} public static PacketRequestLocate decode(PacketBuffer buf) {return new PacketRequestLocate();} public static void handle(PacketRequestLocate msg, Supplier<NetworkEvent.Context> ctx) { ctx.get().enqueueWork(() -> { ServerPlayerEntity player = ctx.get().getSender(); if (StructureHelper.FLYING_PLAYERS_LOCATOR.containsKey(player.getUUID())) { Consumer<TranslationTextComponent> sendError = (text) -> player.displayClientMessage(text.setStyle(Style.EMPTY.withColor(TextFormatting.RED)), true); Consumer<Vector3d> toLocation = (end) -> { Vector3d start = player.position(); Vector3d direction = end.subtract(start); if (direction.length() > 15) direction = direction.normalize().scale(15); Vector3d limitedEnd = start.add(direction); Register.TRIGGER_USE.trigger(player);
player.getLevel().sendParticles(new LocateParticleData((float) limitedEnd.x(), (float) limitedEnd.z(), (int) direction.length()), start.x, start.y, start.z, 1, 0, 0, 0, 0);
3
2023-11-13 03:42:37+00:00
4k
zizai-Shen/young-im
young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/bind/ConfigServerConfigurationBind.java
[ { "identifier": "YoungImException", "path": "young-im-common/src/main/java/cn/young/im/common/exception/YoungImException.java", "snippet": "public class YoungImException extends RuntimeException {\n public YoungImException(String errorMsg) {\n super(errorMsg);\n }\n\n public YoungImExcep...
import cn.young.im.common.exception.YoungImException; import cn.young.im.springboot.starter.adapter.config.callback.ConfigRefreshCallBack; import cn.young.im.springboot.starter.adapter.config.repository.ConfigServerRepository; import cn.young.im.springboot.starter.adapter.config.ConfigType; import cn.young.im.springboot.starter.adapter.config.anno.ConfigServerConfigurationProperties; import cn.young.im.springboot.starter.adapter.config.parse.ConfigParseFactory; import cn.young.im.springboot.starter.adapter.config.parse.IConfigParseHandler; import cn.young.im.springboot.starter.extension.spring.ApplicationContextHolder; import com.alibaba.nacos.api.config.listener.AbstractListener; import com.alibaba.nacos.api.exception.NacosException; import lombok.AllArgsConstructor; import lombok.NonNull; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.core.annotation.AnnotationUtils; import java.util.Objects;
1,754
package cn.young.im.springboot.starter.adapter.config.bind; @AllArgsConstructor public class ConfigServerConfigurationBind implements BeanPostProcessor { private final ConfigServerRepository configServerRepository; private final ApplicationContextHolder contextHolder; /** * 实例化前对注解进行处理 */ @Override public Object postProcessBeforeInitialization(Object bean, @NonNull String beanName) throws BeansException { // 1. 提取注解 ConfigServerConfigurationProperties annotation = AnnotationUtils.findAnnotation(bean.getClass(), ConfigServerConfigurationProperties.class); // 2. 排除非配置 Bean if (Objects.isNull(annotation)) { return bean; } // 3. 存在注解开始绑定 bind(bean, beanName, annotation); return bean; } /** * 属性与系统绑定 */ private void bind(final Object bean, final String beanName, final ConfigServerConfigurationProperties annotation) { // 1. 提取属性 final String dataId = annotation.configKey(); final String groupId = annotation.groupId(); final String type = deduceConfigType(annotation); final ConfigRefreshCallBack callBack = (ConfigRefreshCallBack) contextHolder.getContext().getBean(annotation.callbackClazz()); // 2. 解析属性 String content = configServerRepository.getConfig(dataId, groupId); // 把配置文件塞进属性 (handler) + callback IConfigParseHandler handler = ConfigParseFactory.acquireHandler(type); handler.parse(content, bean); // 3. 自动刷新监听器注册 if (annotation.autoRefreshed()) { try { configServerRepository.getConfigService().addListener(dataId, groupId, new AbstractListener() { final String _beanName = beanName; final ApplicationContextHolder _contextHolder = contextHolder; final ConfigRefreshCallBack _callBack = callBack; final String _type = type; @Override public void receiveConfigInfo(String configInfo) { // 1. 提取配置 Bean Object originBean = _contextHolder.getContext().getBean(_beanName); // 2. 提取处理器 IConfigParseHandler handler = ConfigParseFactory.acquireHandler(_type); // 3. 执行处理 handler.parse(configInfo, originBean); // 4. 触发回调 _callBack.refresh(); } }); } catch (NacosException e) { throw new YoungImException("listener init occur error, config bean is :" + beanName); } } } /** * 推断 Config Type */ private String deduceConfigType(final ConfigServerConfigurationProperties annotation) { String type;
package cn.young.im.springboot.starter.adapter.config.bind; @AllArgsConstructor public class ConfigServerConfigurationBind implements BeanPostProcessor { private final ConfigServerRepository configServerRepository; private final ApplicationContextHolder contextHolder; /** * 实例化前对注解进行处理 */ @Override public Object postProcessBeforeInitialization(Object bean, @NonNull String beanName) throws BeansException { // 1. 提取注解 ConfigServerConfigurationProperties annotation = AnnotationUtils.findAnnotation(bean.getClass(), ConfigServerConfigurationProperties.class); // 2. 排除非配置 Bean if (Objects.isNull(annotation)) { return bean; } // 3. 存在注解开始绑定 bind(bean, beanName, annotation); return bean; } /** * 属性与系统绑定 */ private void bind(final Object bean, final String beanName, final ConfigServerConfigurationProperties annotation) { // 1. 提取属性 final String dataId = annotation.configKey(); final String groupId = annotation.groupId(); final String type = deduceConfigType(annotation); final ConfigRefreshCallBack callBack = (ConfigRefreshCallBack) contextHolder.getContext().getBean(annotation.callbackClazz()); // 2. 解析属性 String content = configServerRepository.getConfig(dataId, groupId); // 把配置文件塞进属性 (handler) + callback IConfigParseHandler handler = ConfigParseFactory.acquireHandler(type); handler.parse(content, bean); // 3. 自动刷新监听器注册 if (annotation.autoRefreshed()) { try { configServerRepository.getConfigService().addListener(dataId, groupId, new AbstractListener() { final String _beanName = beanName; final ApplicationContextHolder _contextHolder = contextHolder; final ConfigRefreshCallBack _callBack = callBack; final String _type = type; @Override public void receiveConfigInfo(String configInfo) { // 1. 提取配置 Bean Object originBean = _contextHolder.getContext().getBean(_beanName); // 2. 提取处理器 IConfigParseHandler handler = ConfigParseFactory.acquireHandler(_type); // 3. 执行处理 handler.parse(configInfo, originBean); // 4. 触发回调 _callBack.refresh(); } }); } catch (NacosException e) { throw new YoungImException("listener init occur error, config bean is :" + beanName); } } } /** * 推断 Config Type */ private String deduceConfigType(final ConfigServerConfigurationProperties annotation) { String type;
ConfigType configType = annotation.type();
3
2023-11-10 06:21:17+00:00
4k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/server/core/CommandsManager.java
[ { "identifier": "AccessLevel", "path": "src/main/java/io/xlorey/FluxLoader/enums/AccessLevel.java", "snippet": "@Getter\npublic enum AccessLevel {\n /**\n * Highest access level, typically reserved for administrators.\n * This level has the highest priority.\n */\n ADMIN(\"admin\", 5),...
import io.xlorey.FluxLoader.annotations.CommandChatReturn; import io.xlorey.FluxLoader.annotations.CommandExecutionScope; import io.xlorey.FluxLoader.annotations.CommandName; import io.xlorey.FluxLoader.annotations.CommandAccessLevel; import io.xlorey.FluxLoader.enums.AccessLevel; import io.xlorey.FluxLoader.enums.CommandScope; import io.xlorey.FluxLoader.interfaces.ICommand; import io.xlorey.FluxLoader.server.api.PlayerUtils; import io.xlorey.FluxLoader.utils.Logger; import lombok.experimental.UtilityClass; import zombie.characters.IsoPlayer; import zombie.core.raknet.UdpConnection; import java.util.Arrays; import java.util.HashMap;
3,389
package io.xlorey.FluxLoader.server.core; /** * A set of tools for handling custom commands */ @UtilityClass public class CommandsManager { /** * Repository of all custom commands */
package io.xlorey.FluxLoader.server.core; /** * A set of tools for handling custom commands */ @UtilityClass public class CommandsManager { /** * Repository of all custom commands */
private static final HashMap<String, ICommand> commandsMap = new HashMap<>();
2
2023-11-16 09:05:44+00:00
4k
EmonerRobotics/2023Robot
src/main/java/frc/robot/subsystems/LiftSubsystem.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n\n public static class LimelightConstants{\n public static double goalHeightInches = 30.31496; //30.31496\n }\n\n public final class LiftMeasurements{\n public static final...
import edu.wpi.first.wpilibj.Encoder; import edu.wpi.first.wpilibj.motorcontrol.PWMVictorSPX; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.Constants.IntakeConstants;
3,483
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class LiftSubsystem extends SubsystemBase { private PWMVictorSPX liftMotor; private Encoder liftEncoder; public LiftSubsystem() { //redline motor liftMotor = new PWMVictorSPX(IntakeConstants.LiftRedline1); //lift encoder liftEncoder = new Encoder(6, 7); //true, EncodingType.k4X liftEncoder.reset(); } public void manuelLiftControl(double speed){ liftMotor.set(-speed); } public double getEncoderMeters(){ return (liftEncoder.get() * -IntakeConstants.kEncoderTick2Meter); } public boolean isAtGround(){
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems; public class LiftSubsystem extends SubsystemBase { private PWMVictorSPX liftMotor; private Encoder liftEncoder; public LiftSubsystem() { //redline motor liftMotor = new PWMVictorSPX(IntakeConstants.LiftRedline1); //lift encoder liftEncoder = new Encoder(6, 7); //true, EncodingType.k4X liftEncoder.reset(); } public void manuelLiftControl(double speed){ liftMotor.set(-speed); } public double getEncoderMeters(){ return (liftEncoder.get() * -IntakeConstants.kEncoderTick2Meter); } public boolean isAtGround(){
double error = getEncoderMeters() - Constants.LiftMeasurements.GROUNDH;
0
2023-11-18 14:02:20+00:00
4k
backend-source/ecommerce-microservice-architecture
shipping-service/src/main/java/com/hoangtien2k3/shippingservice/service/impl/OrderItemServiceImpl.java
[ { "identifier": "AppConstant", "path": "shipping-service/src/main/java/com/hoangtien2k3/shippingservice/constant/AppConstant.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic abstract class AppConstant {\n\n public static final String LOCAL_DATE_FORMAT = \"dd-MM-yyyy\";\n ...
import java.util.List; import java.util.stream.Collectors; import javax.transaction.Transactional; import com.hoangtien2k3.shippingservice.constant.AppConstant; import com.hoangtien2k3.shippingservice.domain.id.OrderItemId; import com.hoangtien2k3.shippingservice.dto.OrderDto; import com.hoangtien2k3.shippingservice.dto.OrderItemDto; import com.hoangtien2k3.shippingservice.dto.ProductDto; import com.hoangtien2k3.shippingservice.exception.wrapper.OrderItemNotFoundException; import com.hoangtien2k3.shippingservice.helper.OrderItemMappingHelper; import com.hoangtien2k3.shippingservice.repository.OrderItemRepository; import com.hoangtien2k3.shippingservice.service.OrderItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
1,851
package com.hoangtien2k3.shippingservice.service.impl; @Service @Transactional @Slf4j @RequiredArgsConstructor public class OrderItemServiceImpl implements OrderItemService { private final OrderItemRepository orderItemRepository; private final RestTemplate restTemplate; @Override
package com.hoangtien2k3.shippingservice.service.impl; @Service @Transactional @Slf4j @RequiredArgsConstructor public class OrderItemServiceImpl implements OrderItemService { private final OrderItemRepository orderItemRepository; private final RestTemplate restTemplate; @Override
public List<OrderItemDto> findAll() {
3
2023-11-13 04:24:52+00:00
4k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/mobs/regions/end/Zealot.java
[ { "identifier": "ISkyblockMob", "path": "src/main/java/com/sweattypalms/skyblock/core/mobs/builder/ISkyblockMob.java", "snippet": "public interface ISkyblockMob {\n SkyblockMob getSkyblockMob();\n EntityLiving getEntityInstance();\n}" }, { "identifier": "SkyblockMob", "path": "src/main...
import com.sweattypalms.skyblock.core.mobs.builder.ISkyblockMob; import com.sweattypalms.skyblock.core.mobs.builder.SkyblockMob; import net.minecraft.server.v1_8_R3.EntityEnderman; import net.minecraft.server.v1_8_R3.EntityLiving; import org.bukkit.Location; import org.bukkit.craftbukkit.v1_8_R3.CraftWorld;
3,392
package com.sweattypalms.skyblock.core.mobs.regions.end; public class Zealot extends EntityEnderman implements ISkyblockMob { public static final String ID = "zealot";
package com.sweattypalms.skyblock.core.mobs.regions.end; public class Zealot extends EntityEnderman implements ISkyblockMob { public static final String ID = "zealot";
private final SkyblockMob skyblockMob;
1
2023-11-15 15:05:58+00:00
4k
microsphere-projects/microsphere-i18n
microsphere-i18n-core/src/test/java/io/microsphere/i18n/spring/context/I18nInitializerTest.java
[ { "identifier": "CompositeServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/CompositeServiceMessageSource.java", "snippet": "public class CompositeServiceMessageSource extends AbstractServiceMessageSource implements SmartInitializingSingleton {\n\n private final ...
import io.microsphere.i18n.CompositeServiceMessageSource; import io.microsphere.i18n.ServiceMessageSource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import static org.junit.Assert.assertEquals;
1,678
package io.microsphere.i18n.spring.context; /** * {@link I18nInitializer} Test * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @since 1.0.0 */ @RunWith(SpringRunner.class) @ContextConfiguration(initializers = I18nInitializer.class, loader = AnnotationConfigContextLoader.class, classes = I18nInitializerTest.class) @Configuration public class I18nInitializerTest { @Before public void before() { LocaleContextHolder.resetLocaleContext(); } @Autowired private ServiceMessageSource serviceMessageSource; @Test public void test() {
package io.microsphere.i18n.spring.context; /** * {@link I18nInitializer} Test * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @since 1.0.0 */ @RunWith(SpringRunner.class) @ContextConfiguration(initializers = I18nInitializer.class, loader = AnnotationConfigContextLoader.class, classes = I18nInitializerTest.class) @Configuration public class I18nInitializerTest { @Before public void before() { LocaleContextHolder.resetLocaleContext(); } @Autowired private ServiceMessageSource serviceMessageSource; @Test public void test() {
assertEquals(CompositeServiceMessageSource.class, serviceMessageSource.getClass());
0
2023-11-17 11:35:59+00:00
4k
pyzpre/Create-Bicycles-Bitterballen
src/main/java/createbicyclesbitterballen/index/BlockEntityRegistry.java
[ { "identifier": "BlockRegistry", "path": "src/main/java/createbicyclesbitterballen/index/BlockRegistry.java", "snippet": "public class BlockRegistry {\n\tpublic static final BlockEntry<MechanicalFryer> MECHANICAL_FRYER =\n\t\t\tREGISTRATE.block(\"mechanical_fryer\", MechanicalFryer::new)\n\t\t\t.initial...
import createbicyclesbitterballen.index.BlockRegistry; import com.tterrag.registrate.util.entry.BlockEntityEntry; import createbicyclesbitterballen.block.mechanicalfryer.FryerInstance; import createbicyclesbitterballen.block.mechanicalfryer.MechanicalFryerEntity; import createbicyclesbitterballen.block.mechanicalfryer.MechanicalFryerRenderer; import static createbicyclesbitterballen.CreateBicBitMod.REGISTRATE;
3,136
package createbicyclesbitterballen.index; public class BlockEntityRegistry { public static final BlockEntityEntry<MechanicalFryerEntity> MECHANICAL_FRYER = REGISTRATE .blockEntity("mechanical_fryer", MechanicalFryerEntity::new) .instance(() -> FryerInstance::new) .validBlocks(BlockRegistry.MECHANICAL_FRYER)
package createbicyclesbitterballen.index; public class BlockEntityRegistry { public static final BlockEntityEntry<MechanicalFryerEntity> MECHANICAL_FRYER = REGISTRATE .blockEntity("mechanical_fryer", MechanicalFryerEntity::new) .instance(() -> FryerInstance::new) .validBlocks(BlockRegistry.MECHANICAL_FRYER)
.renderer(() -> MechanicalFryerRenderer::new)
3
2023-11-12 13:05:18+00:00
4k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/PDFBuilder.java
[ { "identifier": "BinaryPage", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/binary/BinaryPage.java", "snippet": "public class BinaryPage {\n int currentNumber = 1;\n\n ArrayList<Bitmap> lists = new ArrayList<>();\n\n int pageCount;\n int pageWidth, pageHeight;\n ...
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.RectF; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import com.hangyeolee.androidpdfwriter.binary.BinaryPage; import com.hangyeolee.androidpdfwriter.components.PDFLayout; import com.hangyeolee.androidpdfwriter.utils.DPI; import com.hangyeolee.androidpdfwriter.utils.Paper; import com.hangyeolee.androidpdfwriter.utils.StandardDirectory; import com.hangyeolee.androidpdfwriter.utils.Zoomable; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.Provider; import java.util.Locale;
3,538
package com.hangyeolee.androidpdfwriter; public class PDFBuilder<T extends PDFLayout> { int quality = 60;
package com.hangyeolee.androidpdfwriter; public class PDFBuilder<T extends PDFLayout> { int quality = 60;
BinaryPage page;
0
2023-11-15 08:05:28+00:00
4k
Ghost-chu/CustomClientDNS
src/main/java/com/ghostchu/mods/customclientdns/CustomClientDNS.java
[ { "identifier": "DNSConfig", "path": "src/main/java/com/ghostchu/mods/customclientdns/config/DNSConfig.java", "snippet": "public class DNSConfig {\n private boolean useLocalDnsServer = true;\n private List<String> customizedDNSResolver = new ArrayList<>(List.of(\n \"https://dns.alidns.c...
import com.ghostchu.mods.customclientdns.config.DNSConfig; import com.ghostchu.mods.customclientdns.dns.DNSLookupHelper; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.impl.FabricLoaderImpl; import org.bspfsystems.yamlconfiguration.file.YamlConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xbill.DNS.*; import java.io.File; import java.io.IOException; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List;
2,023
package com.ghostchu.mods.customclientdns; public class CustomClientDNS implements ModInitializer { public DNSConfig DNS_CONFIG; public static CustomClientDNS INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger("CustomClientDNS"); /** * Runs the mod initializer. */ @Override public void onInitialize() { INSTANCE = this; try { DNS_CONFIG = loadConfig(); } catch (IOException e) { throw new RuntimeException(e); // Crash the game if files failed to create to avoid silent failure } setupDNSResolver(DNS_CONFIG); selfTest(); } private void selfTest() { List<String> testList = List.of( "github.com", "hypixel.net", "google.com", "cloudflare.com", "minecrafr.net", "mojang.com" ); testList.parallelStream().forEach(s -> { try {
package com.ghostchu.mods.customclientdns; public class CustomClientDNS implements ModInitializer { public DNSConfig DNS_CONFIG; public static CustomClientDNS INSTANCE; private static final Logger LOGGER = LoggerFactory.getLogger("CustomClientDNS"); /** * Runs the mod initializer. */ @Override public void onInitialize() { INSTANCE = this; try { DNS_CONFIG = loadConfig(); } catch (IOException e) { throw new RuntimeException(e); // Crash the game if files failed to create to avoid silent failure } setupDNSResolver(DNS_CONFIG); selfTest(); } private void selfTest() { List<String> testList = List.of( "github.com", "hypixel.net", "google.com", "cloudflare.com", "minecrafr.net", "mojang.com" ); testList.parallelStream().forEach(s -> { try {
LOGGER.info("[Self-Test] DNS lookup for {}: {} ", s, new DNSLookupHelper(s));
1
2023-11-17 17:56:41+00:00
4k
frc-7419/SwerveBase
src/main/java/frc/robot/subsystems/drive/DriveBaseSubsystem.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n public static class SwerveConstants {\n /*\n * IMPORTANT: THIS WAS FOUND THROUGH CAD FILES BUT THERE ARE MANY SWERVE X CONFIGURATIONS\n * SO YOU NEED TO DOUBLE CHECK THIS...
import com.kauailabs.navx.frc.AHRS; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveDriveOdometry; import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.wpilibj.SerialPort; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.Constants.SwerveConstants; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
2,120
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems.drive; public class DriveBaseSubsystem extends SubsystemBase { private final SwerveDriveOdometry m_odometry; private final SwerveModule frontLeftModule; private final SwerveModule frontRightModule; private final SwerveModule backLeftModule; private final SwerveModule backRightModule; private final AHRS ahrs; public DriveBaseSubsystem() {
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot.subsystems.drive; public class DriveBaseSubsystem extends SubsystemBase { private final SwerveDriveOdometry m_odometry; private final SwerveModule frontLeftModule; private final SwerveModule frontRightModule; private final SwerveModule backLeftModule; private final SwerveModule backRightModule; private final AHRS ahrs; public DriveBaseSubsystem() {
frontLeftModule = new SwerveModule(SwerveConstants.frontLeft.turnMotorID, SwerveConstants.frontLeft.driveMotorID, SwerveConstants.frontLeft.turnEncoderID, SwerveConstants.frontLeft.offset, "FrontLeftModule");
1
2023-11-17 04:37:58+00:00
4k
SoBadFish/Report
src/main/java/org/sobadfish/report/form/DisplayCustomForm.java
[ { "identifier": "ReportMainClass", "path": "src/main/java/org/sobadfish/report/ReportMainClass.java", "snippet": "public class ReportMainClass extends PluginBase {\n\n private static IDataManager dataManager;\n\n private static ReportMainClass mainClass;\n\n private ReportConfig reportConfig;\n...
import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.form.element.ElementDropdown; import cn.nukkit.form.element.ElementInput; import cn.nukkit.form.element.ElementLabel; import cn.nukkit.form.response.FormResponseCustom; import cn.nukkit.form.window.FormWindowCustom; import cn.nukkit.utils.Config; import cn.nukkit.utils.TextFormat; import org.sobadfish.report.ReportMainClass; import org.sobadfish.report.config.PlayerInfo; import org.sobadfish.report.tools.Utils; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List;
2,363
package org.sobadfish.report.form; /** * @author Sobadfish * @date 2023/11/14 */ public class DisplayCustomForm { private final int id; public static int getRid(){
package org.sobadfish.report.form; /** * @author Sobadfish * @date 2023/11/14 */ public class DisplayCustomForm { private final int id; public static int getRid(){
return Utils.rand(11900,21000);
2
2023-11-15 03:08:23+00:00
4k
daobab-projects/orm-performance-comparator
src/main/java/io/daobab/performance/invoker/InvokerService.java
[ { "identifier": "SakilaDataBase", "path": "src/main/java/io/daobab/performance/daobab/SakilaDataBase.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class SakilaDataBase extends DataBaseTarget implements SakilaTables, SqlProducer {\n\n private final RentalGenerator rentalGenerator;\n ...
import io.daobab.performance.daobab.SakilaDataBase; import io.daobab.performance.daobab.SakilaTables; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import static java.lang.String.format;
3,446
package io.daobab.performance.invoker; @Component @Slf4j @RequiredArgsConstructor
package io.daobab.performance.invoker; @Component @Slf4j @RequiredArgsConstructor
public class InvokerService implements SakilaTables {
1
2023-11-12 21:43:51+00:00
4k
lastnightinparis/tinkoff-investement-bot
bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/handler/update/impl/TextUpdateHandler.java
[ { "identifier": "UserConverter", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/converter/UserConverter.java", "snippet": "@Component\n@RequiredArgsConstructor\npublic class UserConverter {\n\n\n public User fromTgApi(org.telegram.telegrambots.meta.api.objects.User user) {\n ...
import com.itmo.tinkoffinvestementbot.converter.UserConverter; import com.itmo.tinkoffinvestementbot.exception.chat.BotUserDeniedException; import com.itmo.tinkoffinvestementbot.exception.chat.ProcessingException; import com.itmo.tinkoffinvestementbot.exception.system.IllegalTradingBotException; import com.itmo.tinkoffinvestementbot.handler.registry.UpdateHandlersRegistry; import com.itmo.tinkoffinvestementbot.handler.update.BotUpdateHandler; import com.itmo.tinkoffinvestementbot.model.domain.User; import com.itmo.tinkoffinvestementbot.model.enums.bot.BotState; import com.itmo.tinkoffinvestementbot.model.enums.bot.Button; import com.itmo.tinkoffinvestementbot.model.enums.handler.UpdateType; import com.itmo.tinkoffinvestementbot.service.users.UserService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.telegram.telegrambots.meta.api.objects.Message; import org.telegram.telegrambots.meta.api.objects.Update; import java.util.Optional;
2,372
package com.itmo.tinkoffinvestementbot.handler.update.impl; @Service @RequiredArgsConstructor public class TextUpdateHandler implements BotUpdateHandler { private final UserService userService; private final UserConverter userConverter; private final UpdateHandlersRegistry updateHandlersRegistry; @Override public void handelUpdates(Update update) { Message message = update.getMessage(); Long userChatId = message.getFrom().getId(); User user; if (userService.isNew(userChatId)) { // Если пользователь новый if (message.getFrom().getIsBot()) { // Если пользователь является ботом throw new BotUserDeniedException(userChatId); } else { // Если новый пользователь не является ботом user = userService.save( userConverter.fromTgApi(message.getFrom()) ); try { updateHandlersRegistry .getTextHandlerFor(BotState.FIRST_START) .handleText(user, message); } catch (IllegalTradingBotException e) { throw new ProcessingException( userChatId, "There is no text handler for bot state - " + BotState.FIRST_START, e ); } } } else { // Если пользователь зарегистрирован в системе user = userService.getUserByChatId(userChatId); if (user.isBlocked()) { // Если пользователь разблокировал бота user.setBlocked(false); user = userService.save(user); }
package com.itmo.tinkoffinvestementbot.handler.update.impl; @Service @RequiredArgsConstructor public class TextUpdateHandler implements BotUpdateHandler { private final UserService userService; private final UserConverter userConverter; private final UpdateHandlersRegistry updateHandlersRegistry; @Override public void handelUpdates(Update update) { Message message = update.getMessage(); Long userChatId = message.getFrom().getId(); User user; if (userService.isNew(userChatId)) { // Если пользователь новый if (message.getFrom().getIsBot()) { // Если пользователь является ботом throw new BotUserDeniedException(userChatId); } else { // Если новый пользователь не является ботом user = userService.save( userConverter.fromTgApi(message.getFrom()) ); try { updateHandlersRegistry .getTextHandlerFor(BotState.FIRST_START) .handleText(user, message); } catch (IllegalTradingBotException e) { throw new ProcessingException( userChatId, "There is no text handler for bot state - " + BotState.FIRST_START, e ); } } } else { // Если пользователь зарегистрирован в системе user = userService.getUserByChatId(userChatId); if (user.isBlocked()) { // Если пользователь разблокировал бота user.setBlocked(false); user = userService.save(user); }
Optional<Button> buttonOpt = Button.findByMessage(message.getText());
8
2023-11-13 09:28:00+00:00
4k
toxicity188/InventoryAPI
plugin/src/main/java/kor/toxicity/inventory/manager/ResourcePackManagerImpl.java
[ { "identifier": "InventoryAPI", "path": "api/src/main/java/kor/toxicity/inventory/api/InventoryAPI.java", "snippet": "@SuppressWarnings(\"unused\")\npublic abstract class InventoryAPI extends JavaPlugin {\n private static InventoryAPI api;\n\n private ImageManager imageManager;\n private FontMa...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.stream.JsonWriter; import kor.toxicity.inventory.api.InventoryAPI; import kor.toxicity.inventory.api.gui.GuiFont; import kor.toxicity.inventory.api.gui.GuiImage; import kor.toxicity.inventory.api.gui.GuiObjectGenerator; import kor.toxicity.inventory.api.gui.GuiResource; import kor.toxicity.inventory.api.manager.ResourcePackManager; import kor.toxicity.inventory.builder.JsonArrayBuilder; import kor.toxicity.inventory.builder.JsonObjectBuilder; import kor.toxicity.inventory.generator.FontObjectGeneratorImpl; import kor.toxicity.inventory.generator.ImageObjectGeneratorImpl; import kor.toxicity.inventory.util.PluginUtil; import lombok.Getter; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List;
3,263
package kor.toxicity.inventory.manager; public class ResourcePackManagerImpl implements ResourcePackManager { private final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>(); private final List<ImageObjectGeneratorImpl> images = new ArrayList<>(); @Getter private Material emptyMaterial = Material.DIAMOND_HORSE_ARMOR; @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void reload() {
package kor.toxicity.inventory.manager; public class ResourcePackManagerImpl implements ResourcePackManager { private final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); private final List<FontObjectGeneratorImpl> fonts = new ArrayList<>(); private final List<ImageObjectGeneratorImpl> images = new ArrayList<>(); @Getter private Material emptyMaterial = Material.DIAMOND_HORSE_ARMOR; @SuppressWarnings("ResultOfMethodCallIgnored") @Override public void reload() {
var topFolder = getFile(getFile(InventoryAPI.getInstance().getDataFolder(), ".generated"), "assets");
0
2023-11-13 00:19:46+00:00
4k
Hikaito/Fox-Engine
src/system/setting/UserSetting.java
[ { "identifier": "Program", "path": "src/system/Program.java", "snippet": "public class Program {\n\n //region initialization------------------------------------------\n\n // \"global\" variables\n private static UserSetting userSetting;\n private static MainWindow window;\n private static...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import system.Program; import system.backbone.ColorAdapter; import system.layerTree.RendererTypeAdapter; import system.layerTree.data.TreeUnit; import java.awt.*; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths;
3,476
package system.setting; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== // settings container class // loads, saves, etc the settings // on change to folder paths, call generateDirectories [makes sure all referenced path directories actually exist] public class UserSetting { // region save/load functionality -------------------------------- // default control file private final static String fileName = "settings.json"; // GSON builder private static final Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag .setPrettyPrinting() // creates a pretty version of the output
package system.setting; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== // settings container class // loads, saves, etc the settings // on change to folder paths, call generateDirectories [makes sure all referenced path directories actually exist] public class UserSetting { // region save/load functionality -------------------------------- // default control file private final static String fileName = "settings.json"; // GSON builder private static final Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag .setPrettyPrinting() // creates a pretty version of the output
.registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter
1
2023-11-12 21:12:21+00:00
4k
shizotoaster/thaumon
forge/src/main/java/jdlenl/thaumon/forge/ThaumonForge.java
[ { "identifier": "Thaumon", "path": "common/src/main/java/jdlenl/thaumon/Thaumon.java", "snippet": "public class Thaumon {\n public static final String MOD_ID = \"thaumon\";\n public static Logger logger = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n ThaumonItems.ini...
import jdlenl.thaumon.Thaumon; import jdlenl.thaumon.block.forge.ThaumonBlocksImpl; import jdlenl.thaumon.color.forge.ColorRegistrationHandlers; import jdlenl.thaumon.item.forge.ThaumonItemsImpl; import jdlenl.thaumon.itemgroup.forge.ThaumonItemGroupForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
3,453
package jdlenl.thaumon.forge; @Mod(Thaumon.MOD_ID) public class ThaumonForge { public ThaumonForge() { Thaumon.init(); IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus(); ThaumonItemGroupForge.ITEM_GROUPS.register(eventBus);
package jdlenl.thaumon.forge; @Mod(Thaumon.MOD_ID) public class ThaumonForge { public ThaumonForge() { Thaumon.init(); IEventBus eventBus = FMLJavaModLoadingContext.get().getModEventBus(); ThaumonItemGroupForge.ITEM_GROUPS.register(eventBus);
ThaumonBlocksImpl.BLOCKS.register(eventBus);
1
2023-11-16 06:03:29+00:00
4k
KomnisEvangelos/GeoApp
app/src/main/java/gr/ihu/geoapp/ui/home/HomeFragment.java
[ { "identifier": "Image", "path": "app/src/main/java/gr/ihu/geoapp/models/Image.java", "snippet": "public class Image {\n private String id;\n private String path;\n private String title;\n private String description;\n private String tags_csv;\n //private String location;\n\n /**\n ...
import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.GridView; import android.widget.ListAdapter; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import java.util.List; import gr.ihu.geoapp.databinding.FragmentHomeBinding; import gr.ihu.geoapp.models.Image; import gr.ihu.geoapp.models.users.RegularUser;
2,606
package gr.ihu.geoapp.ui.home; /** * This class represents the Home Fragment in the application. * It displays a simple text view. */ public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private GridView gridView; /** * Initializes the view of the fragment. * Sets up the observer for the text view. * * @param inflater the LayoutInflater to inflate the view * @param container the container for the view * @param savedInstanceState the saved instance state * @return the view of the fragment */ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); //final TextView textView = binding.textHome; //homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText); gridView = binding.homeGridView;
package gr.ihu.geoapp.ui.home; /** * This class represents the Home Fragment in the application. * It displays a simple text view. */ public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private GridView gridView; /** * Initializes the view of the fragment. * Sets up the observer for the text view. * * @param inflater the LayoutInflater to inflate the view * @param container the container for the view * @param savedInstanceState the saved instance state * @return the view of the fragment */ public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); //final TextView textView = binding.textHome; //homeViewModel.getText().observe(getViewLifecycleOwner(), textView::setText); gridView = binding.homeGridView;
List<Image> imageList = RegularUser.getInstance().getImageList();
0
2023-11-10 17:43:18+00:00
4k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/utils/nmsutil/BoundingBoxSize.java
[ { "identifier": "PacketEntity", "path": "src/main/java/ac/grim/grimac/utils/data/packetentity/PacketEntity.java", "snippet": "public class PacketEntity {\n public Vector3d serverPos;\n public int lastTransactionHung;\n public EntityType type;\n public org.bukkit.entity.EntityType bukkitEntit...
import ac.grim.grimac.utils.data.packetentity.PacketEntity; import ac.grim.grimac.utils.data.packetentity.PacketEntityHorse; import ac.grim.grimac.utils.data.packetentity.PacketEntitySizeable; import ac.grim.grimac.utils.enums.EntityType;
3,483
case SKELETON_HORSE: case MULE: case ZOMBIE_HORSE: case HORSE: case ZOGLIN: return 1.39648; case BOAT: return 1.375; case CHICKEN: case ENDERMITE: case RABBIT: case SILVERFISH: case VEX: return 0.4; case STRIDER: case COW: case SHEEP: case MUSHROOM_COW: case PIG: case LLAMA: case DOLPHIN: case WITHER: case TRADER_LLAMA: return 0.9; case PHANTOM: if (packetEntity instanceof PacketEntitySizeable) { return 0.9 + ((PacketEntitySizeable) packetEntity).size * 0.2; } case DONKEY: return 1.5; case ELDER_GUARDIAN: return 1.9975; case ENDER_CRYSTAL: return 2.0; case ENDER_DRAGON: return 16.0; case FIREBALL: return 1; case GHAST: return 4.0; case GIANT: return 3.6; case GUARDIAN: return 0.85; case IRON_GOLEM: return 1.4; case MAGMA_CUBE: if (packetEntity instanceof PacketEntitySizeable) { return 0.51000005 * ((PacketEntitySizeable) packetEntity).size; } case MINECART: case MINECART_CHEST: case MINECART_COMMAND: case MINECART_FURNACE: case MINECART_HOPPER: case MINECART_MOB_SPAWNER: case MINECART_TNT: return 0.98; case PLAYER: return 0.6; case POLAR_BEAR: return 1.4; case RAVAGER: return 1.95; case SHULKER: return 1.0; case SLIME: if (packetEntity instanceof PacketEntitySizeable) { return 0.51000005 * ((PacketEntitySizeable) packetEntity).size; } case SMALL_FIREBALL: return 0.3125; case SPIDER: return 1.4; case SQUID: return 0.8; case TURTLE: return 1.2; default: return 0.6; } } public static double getHeight(PacketEntity packetEntity) { // Turtles are the only baby animal that don't follow the * 0.5 rule if (packetEntity.type == EntityType.TURTLE && packetEntity.isBaby) return 0.12; return getHeightMinusBaby(packetEntity) * (packetEntity.isBaby ? 0.5 : 1); } public static double getMyRidingOffset(PacketEntity packetEntity) { switch (packetEntity.type) { case PIGLIN: case ZOMBIFIED_PIGLIN: case ZOMBIE: return packetEntity.isBaby ? -0.05 : -0.45; case SKELETON: return -0.6; case ENDERMITE: case SILVERFISH: return 0.1; case EVOKER: case ILLUSIONER: case PILLAGER: case RAVAGER: case VINDICATOR: case WITCH: return -0.45; case PLAYER: return -0.35; } if (EntityType.isAnimal(packetEntity.bukkitEntityType)) { return 0.14; } return 0; } public static double getPassengerRidingOffset(PacketEntity packetEntity) {
package ac.grim.grimac.utils.nmsutil; public class BoundingBoxSize { public static double getWidth(PacketEntity packetEntity) { // Turtles are the only baby animal that don't follow the * 0.5 rule if (packetEntity.type == EntityType.TURTLE && packetEntity.isBaby) return 0.36; return getWidthMinusBaby(packetEntity) * (packetEntity.isBaby ? 0.5 : 1); } private static double getWidthMinusBaby(PacketEntity packetEntity) { switch (packetEntity.type) { case AXOLOTL: case PANDA: return 1.3; case BAT: case PARROT: case COD: case EVOKER_FANGS: case TROPICAL_FISH: return 0.5; case BEE: case PUFFERFISH: case SALMON: case SNOWMAN: case WITHER_SKELETON: case CAVE_SPIDER: return 0.7; case WITHER_SKULL: case SHULKER_BULLET: return 0.3125; case BLAZE: case OCELOT: case STRAY: case HOGLIN: case SKELETON_HORSE: case MULE: case ZOMBIE_HORSE: case HORSE: case ZOGLIN: return 1.39648; case BOAT: return 1.375; case CHICKEN: case ENDERMITE: case RABBIT: case SILVERFISH: case VEX: return 0.4; case STRIDER: case COW: case SHEEP: case MUSHROOM_COW: case PIG: case LLAMA: case DOLPHIN: case WITHER: case TRADER_LLAMA: return 0.9; case PHANTOM: if (packetEntity instanceof PacketEntitySizeable) { return 0.9 + ((PacketEntitySizeable) packetEntity).size * 0.2; } case DONKEY: return 1.5; case ELDER_GUARDIAN: return 1.9975; case ENDER_CRYSTAL: return 2.0; case ENDER_DRAGON: return 16.0; case FIREBALL: return 1; case GHAST: return 4.0; case GIANT: return 3.6; case GUARDIAN: return 0.85; case IRON_GOLEM: return 1.4; case MAGMA_CUBE: if (packetEntity instanceof PacketEntitySizeable) { return 0.51000005 * ((PacketEntitySizeable) packetEntity).size; } case MINECART: case MINECART_CHEST: case MINECART_COMMAND: case MINECART_FURNACE: case MINECART_HOPPER: case MINECART_MOB_SPAWNER: case MINECART_TNT: return 0.98; case PLAYER: return 0.6; case POLAR_BEAR: return 1.4; case RAVAGER: return 1.95; case SHULKER: return 1.0; case SLIME: if (packetEntity instanceof PacketEntitySizeable) { return 0.51000005 * ((PacketEntitySizeable) packetEntity).size; } case SMALL_FIREBALL: return 0.3125; case SPIDER: return 1.4; case SQUID: return 0.8; case TURTLE: return 1.2; default: return 0.6; } } public static double getHeight(PacketEntity packetEntity) { // Turtles are the only baby animal that don't follow the * 0.5 rule if (packetEntity.type == EntityType.TURTLE && packetEntity.isBaby) return 0.12; return getHeightMinusBaby(packetEntity) * (packetEntity.isBaby ? 0.5 : 1); } public static double getMyRidingOffset(PacketEntity packetEntity) { switch (packetEntity.type) { case PIGLIN: case ZOMBIFIED_PIGLIN: case ZOMBIE: return packetEntity.isBaby ? -0.05 : -0.45; case SKELETON: return -0.6; case ENDERMITE: case SILVERFISH: return 0.1; case EVOKER: case ILLUSIONER: case PILLAGER: case RAVAGER: case VINDICATOR: case WITCH: return -0.45; case PLAYER: return -0.35; } if (EntityType.isAnimal(packetEntity.bukkitEntityType)) { return 0.14; } return 0; } public static double getPassengerRidingOffset(PacketEntity packetEntity) {
if (packetEntity instanceof PacketEntityHorse)
1
2023-11-11 05:14:12+00:00
4k
ImShyMike/QuestCompassPlus
src/main/java/shymike/questcompassplus/QuestCompassPlus.java
[ { "identifier": "CommandRegister", "path": "src/main/java/shymike/questcompassplus/commands/CommandRegister.java", "snippet": "public class CommandRegister {\n\tstatic public void run() {\n\t\tMinecraftClient mc = MinecraftClient.getInstance();\n\t\tClientCommandRegistrationCallback.EVENT.register((disp...
import shymike.questcompassplus.commands.CommandRegister; import shymike.questcompassplus.utils.RenderUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
2,169
package shymike.questcompassplus; public class QuestCompassPlus implements ClientModInitializer { public static final Logger LOGGER = LoggerFactory.getLogger("quest-compass-plus"); @Override public void onInitializeClient() { LOGGER.info("QuestCompassPlus Loading!"); HudRenderCallback.EVENT.register(new RenderUtils());
package shymike.questcompassplus; public class QuestCompassPlus implements ClientModInitializer { public static final Logger LOGGER = LoggerFactory.getLogger("quest-compass-plus"); @Override public void onInitializeClient() { LOGGER.info("QuestCompassPlus Loading!"); HudRenderCallback.EVENT.register(new RenderUtils());
CommandRegister.run();
0
2023-11-14 15:56:39+00:00
4k
kawainime/IOT-Smart_Farming
ICEBURG_AccessControl_V.01/src/UI/Home.java
[ { "identifier": "Cache_Reader", "path": "ICEBURG_AccessControl_V.01/src/Core/Cache_Reader.java", "snippet": "public class Cache_Reader \n{\n public static String reader(String file_name)\n {\n String user_name = null;\n \n try\n {\n String db_name = file_name...
import Core.Cache_Reader; import Core.Log; import Core.Presant_Validation; import Core.User_Validation; import java.awt.Color;
2,088
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UI; /** * * @author Jayashanka Deshan */ public class Home extends javax.swing.JFrame { /** * Creates new form Home */ public Home() { initComponents(); Log.add_Log("A"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); roundPanel15 = new com.deshan.swing.RoundPanel(); jTextField8 = new javax.swing.JTextField(); time_zone = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); today = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); roundPanel15.setBackground(new java.awt.Color(255, 255, 255)); jTextField8.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N jTextField8.setForeground(new java.awt.Color(102, 102, 102)); jTextField8.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField8.setText("SCAN YOUR CARD HERE"); jTextField8.setBorder(null); jTextField8.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextField8FocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextField8FocusLost(evt); } }); jTextField8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField8ActionPerformed(evt); } }); jTextField8.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTextField8KeyReleased(evt); } }); javax.swing.GroupLayout roundPanel15Layout = new javax.swing.GroupLayout(roundPanel15); roundPanel15.setLayout(roundPanel15Layout); roundPanel15Layout.setHorizontalGroup( roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel15Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE) .addContainerGap()) ); roundPanel15Layout.setVerticalGroup( roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel15Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE) .addContainerGap()) ); jPanel1.add(roundPanel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(193, 450, 390, -1)); time_zone.setFont(new java.awt.Font("Yu Gothic", 1, 48)); // NOI18N time_zone.setForeground(new java.awt.Color(102, 102, 102)); time_zone.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); time_zone.setText("10:45 P.M"); jPanel1.add(time_zone, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 800, 50)); jLabel3.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(102, 102, 102)); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("ICEBURG ACCESS CONTROL"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 800, 40)); today.setFont(new java.awt.Font("Monospaced", 1, 20)); // NOI18N today.setForeground(new java.awt.Color(102, 102, 102)); today.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); today.setText("2010.12.22"); jPanel1.add(today, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 150, 800, 30)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/drawable/main.gif"))); // NOI18N jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(204, 204, 204))); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, -1)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jTextField8FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusGained if(jTextField8.getText().equals("SCAN YOUR CARD HERE")) { jTextField8.setText(""); jTextField8.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField8FocusGained private void jTextField8FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusLost if(jTextField8.getText().equals("")) { jTextField8.setText("SCAN YOUR CARD HERE"); jTextField8.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField8FocusLost private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField8ActionPerformed private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased if(jTextField8.getText().length() == 10) {
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package UI; /** * * @author Jayashanka Deshan */ public class Home extends javax.swing.JFrame { /** * Creates new form Home */ public Home() { initComponents(); Log.add_Log("A"); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); roundPanel15 = new com.deshan.swing.RoundPanel(); jTextField8 = new javax.swing.JTextField(); time_zone = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); today = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setUndecorated(true); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); roundPanel15.setBackground(new java.awt.Color(255, 255, 255)); jTextField8.setFont(new java.awt.Font("Yu Gothic UI", 0, 16)); // NOI18N jTextField8.setForeground(new java.awt.Color(102, 102, 102)); jTextField8.setHorizontalAlignment(javax.swing.JTextField.CENTER); jTextField8.setText("SCAN YOUR CARD HERE"); jTextField8.setBorder(null); jTextField8.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextField8FocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { jTextField8FocusLost(evt); } }); jTextField8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField8ActionPerformed(evt); } }); jTextField8.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jTextField8KeyReleased(evt); } }); javax.swing.GroupLayout roundPanel15Layout = new javax.swing.GroupLayout(roundPanel15); roundPanel15.setLayout(roundPanel15Layout); roundPanel15Layout.setHorizontalGroup( roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(roundPanel15Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE) .addContainerGap()) ); roundPanel15Layout.setVerticalGroup( roundPanel15Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, roundPanel15Layout.createSequentialGroup() .addContainerGap() .addComponent(jTextField8, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE) .addContainerGap()) ); jPanel1.add(roundPanel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(193, 450, 390, -1)); time_zone.setFont(new java.awt.Font("Yu Gothic", 1, 48)); // NOI18N time_zone.setForeground(new java.awt.Color(102, 102, 102)); time_zone.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); time_zone.setText("10:45 P.M"); jPanel1.add(time_zone, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 80, 800, 50)); jLabel3.setFont(new java.awt.Font("Monospaced", 1, 18)); // NOI18N jLabel3.setForeground(new java.awt.Color(102, 102, 102)); jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("ICEBURG ACCESS CONTROL"); jPanel1.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 20, 800, 40)); today.setFont(new java.awt.Font("Monospaced", 1, 20)); // NOI18N today.setForeground(new java.awt.Color(102, 102, 102)); today.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); today.setText("2010.12.22"); jPanel1.add(today, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 150, 800, 30)); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/drawable/main.gif"))); // NOI18N jLabel1.setBorder(javax.swing.BorderFactory.createMatteBorder(1, 1, 1, 1, new java.awt.Color(204, 204, 204))); jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 800, -1)); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jTextField8FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusGained if(jTextField8.getText().equals("SCAN YOUR CARD HERE")) { jTextField8.setText(""); jTextField8.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField8FocusGained private void jTextField8FocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField8FocusLost if(jTextField8.getText().equals("")) { jTextField8.setText("SCAN YOUR CARD HERE"); jTextField8.setForeground(new Color(102,102,102)); } }//GEN-LAST:event_jTextField8FocusLost private void jTextField8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField8ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField8ActionPerformed private void jTextField8KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField8KeyReleased if(jTextField8.getText().length() == 10) {
if(jTextField8.getText().equals(Cache_Reader.reader("Master_Card.key")))
0
2023-11-11 08:23:10+00:00
4k
Outer-Fields/item-server
src/main/java/io/mindspice/itemserver/api/Internal.java
[ { "identifier": "Settings", "path": "src/main/java/io/mindspice/itemserver/Settings.java", "snippet": "public class Settings {\n static Settings INSTANCE;\n\n /* Monitor */\n public volatile int startHeight;\n public volatile int chainScanInterval;\n public volatile int heightBuffer;\n ...
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import io.mindspice.databaseservice.client.api.OkraNFTAPI; import io.mindspice.databaseservice.client.schema.Card; import io.mindspice.itemserver.schema.ApiMint; import io.mindspice.itemserver.Settings; import io.mindspice.itemserver.schema.ApiMintReq; import io.mindspice.itemserver.services.AvatarService; import io.mindspice.itemserver.services.LeaderBoardService; import io.mindspice.jxch.rpc.schemas.wallet.nft.MetaData; import io.mindspice.jxch.transact.logging.TLogLevel; import io.mindspice.jxch.transact.logging.TLogger; import io.mindspice.jxch.transact.service.mint.MintItem; import io.mindspice.jxch.transact.service.mint.MintService; import io.mindspice.mindlib.data.tuples.Pair; import io.mindspice.mindlib.util.JsonUtils; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.net.http.HttpResponse; import java.util.*; import java.util.stream.IntStream;
3,471
package io.mindspice.itemserver.api; @CrossOrigin @RestController @RequestMapping("/internal") public class Internal { private final MintService mintService; private final AvatarService avatarService; private final LeaderBoardService leaderBoardService; private final OkraNFTAPI nftAPI; private final MetaData accountNFTMeta; private final TLogger logger; public Internal( @Qualifier("mintService") MintService mintService, @Qualifier("avatarService") AvatarService avatarService, @Qualifier("leaderBoardService") LeaderBoardService leaderBoardService, @Qualifier("okraNFTAPI") OkraNFTAPI nftAPI, @Qualifier("customLogger") TLogger customLogger, @Qualifier("accountNFTMeta") MetaData accountNFTMeta ) { this.mintService = mintService; this.avatarService = avatarService; this.leaderBoardService = leaderBoardService; this.nftAPI = nftAPI; this.accountNFTMeta = accountNFTMeta; this.logger = customLogger; } @PostMapping("/mint_card_nfts") public ResponseEntity<String> mintCardNfts(@RequestBody String jsonReq) throws IOException { try { ApiMintReq mintReq = JsonUtils.readValue(jsonReq, ApiMintReq.class); List<Card> cards = nftAPI.getCardCollection(mintReq.collection()).data().orElseThrow(); var mints = mintReq.mint_list().stream().map(m -> new MintItem( m.address(), m.card_uid().equals("DID") ? accountNFTMeta : cards.stream().filter(c -> c.uid().equals(m.card_uid())) .findFirst().orElseThrow().metaData() .cloneSetEdt(nftAPI.getAndIncEdt(mintReq.collection(), m.card_uid()).data().get()), m.job_uuid()) ).toList(); mintService.submit(mints); } catch (Exception e) { logger.log(this.getClass(), TLogLevel.ERROR, "Failed to accept api mint", e); return new ResponseEntity<>(JsonUtils.writeString(JsonUtils.errorMsg(e.getMessage() + " | " + Arrays.toString(e.getStackTrace()))), HttpStatus.OK); } return new ResponseEntity<>( JsonUtils.writeString(JsonUtils.successMsg(JsonUtils.newEmptyNode())), HttpStatus.OK ); } @PostMapping("update_avatar") public ResponseEntity<String> updateAvatar(@RequestBody String jsonRequest) throws IOException { JsonNode node = JsonUtils.readTree(jsonRequest); String nftId = node.get("nft_id").asText(); int playerId = node.get("player_id").asInt(); if (nftId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } avatarService.submit(new Pair<>(playerId, nftId)); return new ResponseEntity<>(HttpStatus.OK); } @PostMapping("/mint_did_nfts") public ResponseEntity<String> mintDidNfts(@RequestBody String jsonReq) throws JsonProcessingException { try { JsonNode node = JsonUtils.readTree(jsonReq); int amount = node.get("amount").asInt(); String uuid = "account:" + UUID.randomUUID(); List<MintItem> mints = IntStream.range(0, amount)
package io.mindspice.itemserver.api; @CrossOrigin @RestController @RequestMapping("/internal") public class Internal { private final MintService mintService; private final AvatarService avatarService; private final LeaderBoardService leaderBoardService; private final OkraNFTAPI nftAPI; private final MetaData accountNFTMeta; private final TLogger logger; public Internal( @Qualifier("mintService") MintService mintService, @Qualifier("avatarService") AvatarService avatarService, @Qualifier("leaderBoardService") LeaderBoardService leaderBoardService, @Qualifier("okraNFTAPI") OkraNFTAPI nftAPI, @Qualifier("customLogger") TLogger customLogger, @Qualifier("accountNFTMeta") MetaData accountNFTMeta ) { this.mintService = mintService; this.avatarService = avatarService; this.leaderBoardService = leaderBoardService; this.nftAPI = nftAPI; this.accountNFTMeta = accountNFTMeta; this.logger = customLogger; } @PostMapping("/mint_card_nfts") public ResponseEntity<String> mintCardNfts(@RequestBody String jsonReq) throws IOException { try { ApiMintReq mintReq = JsonUtils.readValue(jsonReq, ApiMintReq.class); List<Card> cards = nftAPI.getCardCollection(mintReq.collection()).data().orElseThrow(); var mints = mintReq.mint_list().stream().map(m -> new MintItem( m.address(), m.card_uid().equals("DID") ? accountNFTMeta : cards.stream().filter(c -> c.uid().equals(m.card_uid())) .findFirst().orElseThrow().metaData() .cloneSetEdt(nftAPI.getAndIncEdt(mintReq.collection(), m.card_uid()).data().get()), m.job_uuid()) ).toList(); mintService.submit(mints); } catch (Exception e) { logger.log(this.getClass(), TLogLevel.ERROR, "Failed to accept api mint", e); return new ResponseEntity<>(JsonUtils.writeString(JsonUtils.errorMsg(e.getMessage() + " | " + Arrays.toString(e.getStackTrace()))), HttpStatus.OK); } return new ResponseEntity<>( JsonUtils.writeString(JsonUtils.successMsg(JsonUtils.newEmptyNode())), HttpStatus.OK ); } @PostMapping("update_avatar") public ResponseEntity<String> updateAvatar(@RequestBody String jsonRequest) throws IOException { JsonNode node = JsonUtils.readTree(jsonRequest); String nftId = node.get("nft_id").asText(); int playerId = node.get("player_id").asInt(); if (nftId == null) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } avatarService.submit(new Pair<>(playerId, nftId)); return new ResponseEntity<>(HttpStatus.OK); } @PostMapping("/mint_did_nfts") public ResponseEntity<String> mintDidNfts(@RequestBody String jsonReq) throws JsonProcessingException { try { JsonNode node = JsonUtils.readTree(jsonReq); int amount = node.get("amount").asInt(); String uuid = "account:" + UUID.randomUUID(); List<MintItem> mints = IntStream.range(0, amount)
.mapToObj(i -> new MintItem(Settings.get().didMintToAddr, accountNFTMeta, uuid))
0
2023-11-14 14:56:37+00:00
4k
KvRae/Mobile-Exemple-Java-Android
Project/app/src/main/java/com/example/pharmacie2/Views/Activities/MedecinActivity.java
[ { "identifier": "PharmacyDB", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Database/PharmacyDB.java", "snippet": "@Database(entities = {User.class, Medicament.class, Medecin.class}, version = 1, exportSchema = false)\n\npublic abstract class PharmacyDB extends RoomDatabase {\n\n pri...
import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.example.pharmacie2.Data.Database.PharmacyDB; import com.example.pharmacie2.Data.Entities.Medecin; import com.example.pharmacie2.R; import com.example.pharmacie2.Utils.MedecinAdapter; import java.util.List;
1,642
package com.example.pharmacie2.Views.Activities; public class MedecinActivity extends AppCompatActivity implements MedecinAdapter.OnDeleteClickListener{ ImageView backBtn ; ImageView AddM ; PharmacyDB db; private RecyclerView recyclerViewMed; private MedecinAdapter medecinAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_medecin); db = PharmacyDB.getInstance(this); recyclerViewMed = findViewById(R.id.recyclerView3); recyclerViewMed.setLayoutManager(new LinearLayoutManager(this)); backBtn = findViewById(R.id.imageViewCalendrier); AddM = findViewById(R.id.AddMedi); new LoadMedTask(recyclerViewMed).execute(); backBtn.setOnClickListener( e ->{ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); Toast.makeText(this, "main",Toast.LENGTH_SHORT).show(); finish(); } ); AddM.setOnClickListener( e ->{ Intent intent = new Intent(this, AjouterMedecinActivity.class); startActivity(intent); Toast.makeText(this, "main",Toast.LENGTH_SHORT).show(); finish(); } ); } @Override
package com.example.pharmacie2.Views.Activities; public class MedecinActivity extends AppCompatActivity implements MedecinAdapter.OnDeleteClickListener{ ImageView backBtn ; ImageView AddM ; PharmacyDB db; private RecyclerView recyclerViewMed; private MedecinAdapter medecinAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_medecin); db = PharmacyDB.getInstance(this); recyclerViewMed = findViewById(R.id.recyclerView3); recyclerViewMed.setLayoutManager(new LinearLayoutManager(this)); backBtn = findViewById(R.id.imageViewCalendrier); AddM = findViewById(R.id.AddMedi); new LoadMedTask(recyclerViewMed).execute(); backBtn.setOnClickListener( e ->{ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); Toast.makeText(this, "main",Toast.LENGTH_SHORT).show(); finish(); } ); AddM.setOnClickListener( e ->{ Intent intent = new Intent(this, AjouterMedecinActivity.class); startActivity(intent); Toast.makeText(this, "main",Toast.LENGTH_SHORT).show(); finish(); } ); } @Override
public void onDeleteClick(Medecin medecin) {
1
2023-11-14 22:07:33+00:00
4k
CodecNomad/CodecClient
src/main/java/com/github/codecnomad/codecclient/modules/FishingMacro.java
[ { "identifier": "Client", "path": "src/main/java/com/github/codecnomad/codecclient/Client.java", "snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft...
import com.github.codecnomad.codecclient.Client; import com.github.codecnomad.codecclient.events.PacketEvent; import com.github.codecnomad.codecclient.mixins.S19PacketAccessor; import com.github.codecnomad.codecclient.ui.Config; import com.github.codecnomad.codecclient.utils.Math; import com.github.codecnomad.codecclient.utils.*; import net.minecraft.client.Minecraft; import net.minecraft.client.settings.KeyBinding; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.entity.passive.EntitySquid; import net.minecraft.entity.projectile.EntityFishHook; import net.minecraft.item.*; import net.minecraft.network.play.server.*; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.TickEvent; import java.util.List; import java.util.regex.Matcher;
2,569
package com.github.codecnomad.codecclient.modules; @SuppressWarnings("DuplicatedCode") public class FishingMacro extends Module { public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",}; public static int startTime = 0; public static int catches = 0; public static float xpGain = 0; public static FishingSteps currentStep = FishingSteps.FIND_ROD; public static Counter MainCounter = new Counter(); public static Counter AlternativeCounter = new Counter(); public static Counter FailsafeCounter = new Counter(); public static boolean failSafe = false; Entity fishingHook = null; Entity fishingMarker = null; Entity fishingMonster = null; public static float lastYaw = 0; public static float lastPitch = 0; public static AxisAlignedBB lastAABB = null; public BlockPos startPos = null; public static Pathfinding pathfinding = new Pathfinding(); @Override public void register() { MinecraftForge.EVENT_BUS.register(this); this.state = true;
package com.github.codecnomad.codecclient.modules; @SuppressWarnings("DuplicatedCode") public class FishingMacro extends Module { public static final String[] FAILSAFE_TEXT = new String[]{"?", "you good?", "HI IM HERE", "can you not bro", "can you dont", "j g growl wtf", "can i get friend request??", "hello i'm here",}; public static int startTime = 0; public static int catches = 0; public static float xpGain = 0; public static FishingSteps currentStep = FishingSteps.FIND_ROD; public static Counter MainCounter = new Counter(); public static Counter AlternativeCounter = new Counter(); public static Counter FailsafeCounter = new Counter(); public static boolean failSafe = false; Entity fishingHook = null; Entity fishingMarker = null; Entity fishingMonster = null; public static float lastYaw = 0; public static float lastPitch = 0; public static AxisAlignedBB lastAABB = null; public BlockPos startPos = null; public static Pathfinding pathfinding = new Pathfinding(); @Override public void register() { MinecraftForge.EVENT_BUS.register(this); this.state = true;
lastYaw = Client.mc.thePlayer.rotationYaw;
0
2023-11-16 10:12:20+00:00
4k
maarlakes/common
src/main/java/cn/maarlakes/common/factory/json/JsonFactories.java
[ { "identifier": "SpiServiceLoader", "path": "src/main/java/cn/maarlakes/common/spi/SpiServiceLoader.java", "snippet": "public final class SpiServiceLoader<T> implements Iterable<T> {\n\n private static final String PREFIX = \"META-INF/services/\";\n\n private static final ConcurrentMap<ClassLoader...
import cn.maarlakes.common.spi.SpiServiceLoader; import cn.maarlakes.common.utils.Lazy; import jakarta.annotation.Nonnull; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Supplier;
2,335
package cn.maarlakes.common.factory.json; /** * @author linjpxc */ public final class JsonFactories { private JsonFactories() { }
package cn.maarlakes.common.factory.json; /** * @author linjpxc */ public final class JsonFactories { private JsonFactories() { }
private static final Supplier<JsonProvider> PROVIDER = Lazy.of(() -> SpiServiceLoader.loadShared(JsonProvider.class).firstOptional().orElseThrow(() -> new IllegalStateException("No JsonProvider implementation found")));
0
2023-11-18 07:49:00+00:00
4k
Mightinity/store-management-system
src/main/java/com/systeminventory/controller/cashierController.java
[ { "identifier": "App", "path": "src/main/java/com/systeminventory/App.java", "snippet": "public class App extends Application {\n\n private static Stage primaryStage;\n\n public static void main(String[] args) {\n launch(args);\n }\n\n public void start(Stage stage) throws IOException...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.systeminventory.App; import com.systeminventory.interfaces.*; import com.systeminventory.model.Cashier; import com.systeminventory.model.Product; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.FileChooser; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List;
2,421
package com.systeminventory.controller; public class cashierController { @FXML private Pane backgroundPopup; @FXML private Button buttonCashier; @FXML private Button buttonDashboard; @FXML private Button buttonProduct; @FXML private Button logoutDropdown; @FXML private Pane profileDropdown; @FXML private Button settingsDropdown; @FXML private Pane addProfilePopup; @FXML private Label addProfileNameLabel; @FXML private TextField addProfileNameField; @FXML private Label addProfileEmailLabel; @FXML private TextField addProfileEmailField; @FXML private Label addProfileNoPhoneLabel; @FXML private TextField addProfileNoPhoneField; @FXML private Label addProfileDateOfBirthLabel; @FXML private TextField addProfileDateOfBirthField; @FXML private Label addProfileAddressLabel; @FXML private TextField addProfileAddressField; @FXML private Label addProfileProfilePictureLabel; @FXML private Label addProfileProfileImagePathLabel; @FXML private Button addProfileApplyButton; @FXML private Button addProfileCancelButton; @FXML private Label addProfileProfileImageFullPathLabel; @FXML private Button buttonAddProfile; @FXML private Pane addProfileChooseFilePane; @FXML private GridPane profileCardContainer; @FXML private Label profileDetailsVarFullName; @FXML private Label profileDetailsVarPhone; @FXML private Label profileDetailsVarDateOfBirth; @FXML private Label profileDetailsVarEmail; @FXML private Label profileDetailsVarAddress; @FXML public Pane paneSelectAProfile; private ProfileDetailsListener profileDetailsListener; private DeleteCashierListener deleteCashierListener; private EditCashierListener editCashierListener; @FXML private ImageView profileDetailsVarImage; @FXML private TextField searchTermProfile; @FXML private Pane confirmDeleteProfilePane; @FXML private Label confirmDeleteVariableProfileName; @FXML private Button confirmDeleteDeleteButtonProfile; @FXML private Button confirmDeleteCancelButtonProfile; @FXML private Label confirmDeleteKeyProfile; @FXML private Label keyProfileOnPopup; @FXML private Label addProfileLabel; private static String hashMD5(String input) { StringBuilder result = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); byte[] byteData = md.digest(); for (byte aByteData : byteData) { result.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result.toString(); } @FXML void onAddProfileChooseFilePaneMouseClick(MouseEvent event) { FileChooser filechooser = new FileChooser(); filechooser.setTitle("Select profile picture"); filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png"));
package com.systeminventory.controller; public class cashierController { @FXML private Pane backgroundPopup; @FXML private Button buttonCashier; @FXML private Button buttonDashboard; @FXML private Button buttonProduct; @FXML private Button logoutDropdown; @FXML private Pane profileDropdown; @FXML private Button settingsDropdown; @FXML private Pane addProfilePopup; @FXML private Label addProfileNameLabel; @FXML private TextField addProfileNameField; @FXML private Label addProfileEmailLabel; @FXML private TextField addProfileEmailField; @FXML private Label addProfileNoPhoneLabel; @FXML private TextField addProfileNoPhoneField; @FXML private Label addProfileDateOfBirthLabel; @FXML private TextField addProfileDateOfBirthField; @FXML private Label addProfileAddressLabel; @FXML private TextField addProfileAddressField; @FXML private Label addProfileProfilePictureLabel; @FXML private Label addProfileProfileImagePathLabel; @FXML private Button addProfileApplyButton; @FXML private Button addProfileCancelButton; @FXML private Label addProfileProfileImageFullPathLabel; @FXML private Button buttonAddProfile; @FXML private Pane addProfileChooseFilePane; @FXML private GridPane profileCardContainer; @FXML private Label profileDetailsVarFullName; @FXML private Label profileDetailsVarPhone; @FXML private Label profileDetailsVarDateOfBirth; @FXML private Label profileDetailsVarEmail; @FXML private Label profileDetailsVarAddress; @FXML public Pane paneSelectAProfile; private ProfileDetailsListener profileDetailsListener; private DeleteCashierListener deleteCashierListener; private EditCashierListener editCashierListener; @FXML private ImageView profileDetailsVarImage; @FXML private TextField searchTermProfile; @FXML private Pane confirmDeleteProfilePane; @FXML private Label confirmDeleteVariableProfileName; @FXML private Button confirmDeleteDeleteButtonProfile; @FXML private Button confirmDeleteCancelButtonProfile; @FXML private Label confirmDeleteKeyProfile; @FXML private Label keyProfileOnPopup; @FXML private Label addProfileLabel; private static String hashMD5(String input) { StringBuilder result = new StringBuilder(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input.getBytes()); byte[] byteData = md.digest(); for (byte aByteData : byteData) { result.append(Integer.toString((aByteData & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result.toString(); } @FXML void onAddProfileChooseFilePaneMouseClick(MouseEvent event) { FileChooser filechooser = new FileChooser(); filechooser.setTitle("Select profile picture"); filechooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PNG Files", "*.png"));
File selectedFile = filechooser.showOpenDialog(App.getPrimaryStage());
0
2023-11-18 02:53:02+00:00
4k
CivilisationPlot/CivilisationPlot_Papermc
src/main/java/fr/laptoff/civilisationplot/plots/Plot.java
[ { "identifier": "CivilisationPlot", "path": "src/main/java/fr/laptoff/civilisationplot/CivilisationPlot.java", "snippet": "public final class CivilisationPlot extends JavaPlugin {\n\n public static final Logger LOGGER = Logger.getLogger(\"CivilisationPlot\");\n private static CivilisationPlot inst...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fr.laptoff.civilisationplot.CivilisationPlot; import fr.laptoff.civilisationplot.Managers.DatabaseManager; import fr.laptoff.civilisationplot.Managers.FileManager; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.World; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.UUID;
2,532
package fr.laptoff.civilisationplot.plots; public class Plot { private String WorldName; private double XCoordinate; private double YCoordinates; private String PropertyType; private UUID Proprietary; private byte Level; private UUID Uuid; private File file; private final static File fileList = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/ListPlots.json"); private Connection co = CivilisationPlot.getInstance().getDatabase().getConnection(); private static List<UUID> plotsList = new ArrayList<UUID>(); public Plot(String worldName, double xCoordinates, double yCoordinates , String propertyType, UUID proprietary, byte level, UUID uuid){ this.WorldName = worldName; this.XCoordinate = xCoordinates; this.YCoordinates = yCoordinates; this.PropertyType = propertyType; this.Proprietary = proprietary; this.Level = level; this.Uuid = uuid; this.file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + this.Uuid + ".json"); plotsList.add(this.Uuid); } public Chunk getChunk(){ return new Location(Bukkit.getWorld(this.WorldName), this.XCoordinate, this.YCoordinates, 0).getChunk(); } public World getWorld(){ return Bukkit.getWorld(this.WorldName); } public String getPropertyType(){ return this.PropertyType; } public UUID getProprietary(){ return this.Proprietary; } public byte getLevel(){ return this.Level; } public UUID getUuid(){ return this.Uuid; } public void setWorld(World world){ this.WorldName = world.getName(); } public void setPropertyType(String s){ this.PropertyType = s; } public void setProprietary(UUID uuid){ this.Proprietary = uuid; } public void setLevel(byte lvl){ this.Level = lvl; } public static List<UUID> getPlotsList(){ return plotsList; } //Database public void updateObjectFromDatabase(){
package fr.laptoff.civilisationplot.plots; public class Plot { private String WorldName; private double XCoordinate; private double YCoordinates; private String PropertyType; private UUID Proprietary; private byte Level; private UUID Uuid; private File file; private final static File fileList = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/ListPlots.json"); private Connection co = CivilisationPlot.getInstance().getDatabase().getConnection(); private static List<UUID> plotsList = new ArrayList<UUID>(); public Plot(String worldName, double xCoordinates, double yCoordinates , String propertyType, UUID proprietary, byte level, UUID uuid){ this.WorldName = worldName; this.XCoordinate = xCoordinates; this.YCoordinates = yCoordinates; this.PropertyType = propertyType; this.Proprietary = proprietary; this.Level = level; this.Uuid = uuid; this.file = new File(CivilisationPlot.getInstance().getDataFolder() + "/Data/Plots/Plots/" + this.Uuid + ".json"); plotsList.add(this.Uuid); } public Chunk getChunk(){ return new Location(Bukkit.getWorld(this.WorldName), this.XCoordinate, this.YCoordinates, 0).getChunk(); } public World getWorld(){ return Bukkit.getWorld(this.WorldName); } public String getPropertyType(){ return this.PropertyType; } public UUID getProprietary(){ return this.Proprietary; } public byte getLevel(){ return this.Level; } public UUID getUuid(){ return this.Uuid; } public void setWorld(World world){ this.WorldName = world.getName(); } public void setPropertyType(String s){ this.PropertyType = s; } public void setProprietary(UUID uuid){ this.Proprietary = uuid; } public void setLevel(byte lvl){ this.Level = lvl; } public static List<UUID> getPlotsList(){ return plotsList; } //Database public void updateObjectFromDatabase(){
if (!DatabaseManager.isOnline())
1
2023-11-11 18:26:55+00:00
4k
dsntk/dsntk-java-server
src/main/java/io/dsntk/server/rest/dto/SimpleDto.java
[ { "identifier": "CastType", "path": "src/main/java/io/dsntk/server/common/CastType.java", "snippet": "public enum CastType {\n CT_BYTE,\n CT_SHORT,\n CT_INT,\n CT_LONG,\n CT_FLOAT,\n CT_DOUBLE,\n CT_CHAR,\n CT_BOOLEAN,\n CT_STRING,\n CT_OBJECT_ARRAY;\n\n public boolean isPrimitive() {\n re...
import com.fasterxml.jackson.annotation.JsonProperty; import io.dsntk.server.common.CastType; import io.dsntk.server.common.Utils; import io.dsntk.server.common.XsdType; import io.dsntk.server.rest.errors.RpcException; import lombok.Getter; import lombok.Setter; import java.lang.reflect.Array;
2,071
package io.dsntk.server.rest.dto; /** * DTO representing a simple type value. */ @Getter @Setter public class SimpleDto { /** Name of the value's type. */ @JsonProperty("type") private String typ; /** Value represented as text. */ @JsonProperty("text") private String text; /** Flag indicating if the value is `nil`. */ @JsonProperty("isNil") private boolean nil; public Object toObject(Class<?> castClass) throws RpcException { CastType castType = CastType.fromClass(castClass); XsdType xsdType = XsdType.fromString(this.typ); switch (xsdType) { case XSD_STRING -> { if (castType == CastType.CT_STRING) { return this.text; } if (castType == CastType.CT_CHAR) { if (this.text.length() == 1) { return this.text.charAt(0); } } if (castType == CastType.CT_OBJECT_ARRAY) { String[] arr = (String[]) Array.newInstance(java.lang.String.class, 1); Array.set(arr, 0, this.text); return arr; } } case XSD_INTEGER -> { if (castType == CastType.CT_BYTE) { return Byte.valueOf(this.text); } if (castType == CastType.CT_SHORT) { return Short.valueOf(this.text); } if (castType == CastType.CT_INT) { return Integer.valueOf(this.text); } if (castType == CastType.CT_LONG) { return Long.valueOf(this.text); } } case XSD_DOUBLE -> { if (castType == CastType.CT_FLOAT) { return Float.valueOf(this.text); } if (castType == CastType.CT_DOUBLE) { return Double.valueOf(this.text); } } case XSD_DECIMAL -> { if (castType == CastType.CT_BYTE) { return Byte.valueOf(this.text); } if (castType == CastType.CT_SHORT) { return Short.valueOf(this.text); } if (castType == CastType.CT_INT) { return Integer.valueOf(this.text); } if (castType == CastType.CT_LONG) { return Long.valueOf(this.text); } if (castType == CastType.CT_FLOAT) { return Float.valueOf(this.text); } if (castType == CastType.CT_DOUBLE) { return Double.valueOf(this.text); } } } throw new RpcException(String.format("simple DTO conversion to object failed, class: %s, type: %s", castClass.getName(), xsdType)); } public static SimpleDto fromObject(Object object, CastType castType) throws RpcException { switch (castType) { case CT_BYTE -> { return SimpleDto.fromByte((Byte) object); } case CT_SHORT -> { return SimpleDto.fromShort((Short) object); } case CT_INT -> { return SimpleDto.fromInteger((Integer) object); } case CT_LONG -> { return SimpleDto.fromLong((Long) object); } case CT_FLOAT -> { return SimpleDto.fromFloat((Float) object); } case CT_DOUBLE -> { return SimpleDto.fromDouble((Double) object); } case CT_CHAR -> { return SimpleDto.fromCharacter((Character) object); } case CT_STRING -> { return SimpleDto.fromString((String) object); } } throw new RpcException(String.format("simple DTO conversion from object failed, class: %s, type: %s", object.getClass().getName(), castType)); } private static SimpleDto fromByte(Byte object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromShort(Short object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromInteger(Integer object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromLong(Long object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromFloat(Float object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal";
package io.dsntk.server.rest.dto; /** * DTO representing a simple type value. */ @Getter @Setter public class SimpleDto { /** Name of the value's type. */ @JsonProperty("type") private String typ; /** Value represented as text. */ @JsonProperty("text") private String text; /** Flag indicating if the value is `nil`. */ @JsonProperty("isNil") private boolean nil; public Object toObject(Class<?> castClass) throws RpcException { CastType castType = CastType.fromClass(castClass); XsdType xsdType = XsdType.fromString(this.typ); switch (xsdType) { case XSD_STRING -> { if (castType == CastType.CT_STRING) { return this.text; } if (castType == CastType.CT_CHAR) { if (this.text.length() == 1) { return this.text.charAt(0); } } if (castType == CastType.CT_OBJECT_ARRAY) { String[] arr = (String[]) Array.newInstance(java.lang.String.class, 1); Array.set(arr, 0, this.text); return arr; } } case XSD_INTEGER -> { if (castType == CastType.CT_BYTE) { return Byte.valueOf(this.text); } if (castType == CastType.CT_SHORT) { return Short.valueOf(this.text); } if (castType == CastType.CT_INT) { return Integer.valueOf(this.text); } if (castType == CastType.CT_LONG) { return Long.valueOf(this.text); } } case XSD_DOUBLE -> { if (castType == CastType.CT_FLOAT) { return Float.valueOf(this.text); } if (castType == CastType.CT_DOUBLE) { return Double.valueOf(this.text); } } case XSD_DECIMAL -> { if (castType == CastType.CT_BYTE) { return Byte.valueOf(this.text); } if (castType == CastType.CT_SHORT) { return Short.valueOf(this.text); } if (castType == CastType.CT_INT) { return Integer.valueOf(this.text); } if (castType == CastType.CT_LONG) { return Long.valueOf(this.text); } if (castType == CastType.CT_FLOAT) { return Float.valueOf(this.text); } if (castType == CastType.CT_DOUBLE) { return Double.valueOf(this.text); } } } throw new RpcException(String.format("simple DTO conversion to object failed, class: %s, type: %s", castClass.getName(), xsdType)); } public static SimpleDto fromObject(Object object, CastType castType) throws RpcException { switch (castType) { case CT_BYTE -> { return SimpleDto.fromByte((Byte) object); } case CT_SHORT -> { return SimpleDto.fromShort((Short) object); } case CT_INT -> { return SimpleDto.fromInteger((Integer) object); } case CT_LONG -> { return SimpleDto.fromLong((Long) object); } case CT_FLOAT -> { return SimpleDto.fromFloat((Float) object); } case CT_DOUBLE -> { return SimpleDto.fromDouble((Double) object); } case CT_CHAR -> { return SimpleDto.fromCharacter((Character) object); } case CT_STRING -> { return SimpleDto.fromString((String) object); } } throw new RpcException(String.format("simple DTO conversion from object failed, class: %s, type: %s", object.getClass().getName(), castType)); } private static SimpleDto fromByte(Byte object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromShort(Short object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromInteger(Integer object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromLong(Long object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal"; value.text = String.valueOf(object); value.nil = false; return value; } private static SimpleDto fromFloat(Float object) { SimpleDto value = new SimpleDto(); value.typ = "xsd:decimal";
value.text = Utils.stripTrailingZero(String.format("%s", object));
1
2023-11-10 18:06:05+00:00
4k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/gui/servers/ServerManagerScreen.java
[ { "identifier": "MeteorRejectsAddon", "path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java", "snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(...
import anticope.rejects.MeteorRejectsAddon; import anticope.rejects.mixin.MultiplayerScreenAccessor; import anticope.rejects.mixin.ServerListAccessor; import anticope.rejects.utils.server.IPAddress; import meteordevelopment.meteorclient.gui.GuiTheme; import meteordevelopment.meteorclient.gui.WindowScreen; import meteordevelopment.meteorclient.gui.widgets.containers.WContainer; import meteordevelopment.meteorclient.gui.widgets.containers.WHorizontalList; import meteordevelopment.meteorclient.gui.widgets.pressable.WButton; import meteordevelopment.meteorclient.utils.misc.IGetter; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.multiplayer.MultiplayerScreen; import net.minecraft.client.network.ServerInfo; import net.minecraft.client.option.ServerList; import net.minecraft.client.toast.SystemToast; import net.minecraft.text.Text; import org.lwjgl.BufferUtils; import org.lwjgl.PointerBuffer; import org.lwjgl.system.MemoryUtil; import org.lwjgl.util.tinyfd.TinyFileDialogs; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.function.Consumer;
2,969
package anticope.rejects.gui.servers; public class ServerManagerScreen extends WindowScreen { private static final PointerBuffer saveFileFilters; static { saveFileFilters = BufferUtils.createPointerBuffer(1); saveFileFilters.put(MemoryUtil.memASCII("*.txt")); saveFileFilters.rewind(); } private final MultiplayerScreen multiplayerScreen; public ServerManagerScreen(GuiTheme theme, MultiplayerScreen multiplayerScreen) { super(theme, "Manage Servers"); this.parent = multiplayerScreen; this.multiplayerScreen = multiplayerScreen; } public static Runnable tryHandle(ThrowingRunnable<?> tr, Consumer<Throwable> handler) { return Objects.requireNonNull(tr).addHandler(handler); } @Override public void initWidgets() { WHorizontalList l = add(theme.horizontalList()).expandX().widget(); addButton(l, "Find Servers (new)", () -> new ServerFinderScreen(theme, multiplayerScreen, this)); addButton(l, "Find Servers (legacy)", () -> new LegacyServerFinderScreen(theme, multiplayerScreen, this)); addButton(l, "Clean Up", () -> new CleanUpScreen(theme, multiplayerScreen, this)); l = add(theme.horizontalList()).expandX().widget(); l.add(theme.button("Save IPs")).expandX().widget().action = tryHandle(() -> { String targetPath = TinyFileDialogs.tinyfd_saveFileDialog("Save IPs", null, saveFileFilters, null); if (targetPath == null) return; if (!targetPath.endsWith(".txt")) targetPath += ".txt"; Path filePath = Path.of(targetPath); int newIPs = 0; Set<IPAddress> hashedIPs = new HashSet<>(); if (Files.exists(filePath)) { try { List<String> ips = Files.readAllLines(filePath); for (String ip : ips) { IPAddress parsedIP = IPAddress.fromText(ip); if (parsedIP != null) hashedIPs.add(parsedIP); } } catch (IOException e) { e.printStackTrace(); } } ServerList servers = multiplayerScreen.getServerList(); for (int i = 0; i < servers.size(); i++) { ServerInfo info = servers.get(i); IPAddress addr = IPAddress.fromText(info.address); if (addr != null && hashedIPs.add(addr)) newIPs++; } StringBuilder fileOutput = new StringBuilder(); for (IPAddress ip : hashedIPs) { String stringIP = ip.toString(); if (stringIP != null) fileOutput.append(stringIP).append("\n"); } try { Files.writeString(filePath, fileOutput.toString()); } catch (IOException e) { e.printStackTrace(); } toast("Success!", newIPs == 1 ? "Saved %s new IP" : "Saved %s new IPs", newIPs); }, e -> { MeteorRejectsAddon.LOG.error("Could not save IPs"); toast("Something went wrong", "The IPs could not be saved, look at the log for details"); }); l.add(theme.button("Load IPs")).expandX().widget().action = tryHandle(() -> { String targetPath = TinyFileDialogs.tinyfd_openFileDialog("Load IPs", null, saveFileFilters, "", false); if (targetPath == null) return; Path filePath = Path.of(targetPath); if (!Files.exists(filePath)) return;
package anticope.rejects.gui.servers; public class ServerManagerScreen extends WindowScreen { private static final PointerBuffer saveFileFilters; static { saveFileFilters = BufferUtils.createPointerBuffer(1); saveFileFilters.put(MemoryUtil.memASCII("*.txt")); saveFileFilters.rewind(); } private final MultiplayerScreen multiplayerScreen; public ServerManagerScreen(GuiTheme theme, MultiplayerScreen multiplayerScreen) { super(theme, "Manage Servers"); this.parent = multiplayerScreen; this.multiplayerScreen = multiplayerScreen; } public static Runnable tryHandle(ThrowingRunnable<?> tr, Consumer<Throwable> handler) { return Objects.requireNonNull(tr).addHandler(handler); } @Override public void initWidgets() { WHorizontalList l = add(theme.horizontalList()).expandX().widget(); addButton(l, "Find Servers (new)", () -> new ServerFinderScreen(theme, multiplayerScreen, this)); addButton(l, "Find Servers (legacy)", () -> new LegacyServerFinderScreen(theme, multiplayerScreen, this)); addButton(l, "Clean Up", () -> new CleanUpScreen(theme, multiplayerScreen, this)); l = add(theme.horizontalList()).expandX().widget(); l.add(theme.button("Save IPs")).expandX().widget().action = tryHandle(() -> { String targetPath = TinyFileDialogs.tinyfd_saveFileDialog("Save IPs", null, saveFileFilters, null); if (targetPath == null) return; if (!targetPath.endsWith(".txt")) targetPath += ".txt"; Path filePath = Path.of(targetPath); int newIPs = 0; Set<IPAddress> hashedIPs = new HashSet<>(); if (Files.exists(filePath)) { try { List<String> ips = Files.readAllLines(filePath); for (String ip : ips) { IPAddress parsedIP = IPAddress.fromText(ip); if (parsedIP != null) hashedIPs.add(parsedIP); } } catch (IOException e) { e.printStackTrace(); } } ServerList servers = multiplayerScreen.getServerList(); for (int i = 0; i < servers.size(); i++) { ServerInfo info = servers.get(i); IPAddress addr = IPAddress.fromText(info.address); if (addr != null && hashedIPs.add(addr)) newIPs++; } StringBuilder fileOutput = new StringBuilder(); for (IPAddress ip : hashedIPs) { String stringIP = ip.toString(); if (stringIP != null) fileOutput.append(stringIP).append("\n"); } try { Files.writeString(filePath, fileOutput.toString()); } catch (IOException e) { e.printStackTrace(); } toast("Success!", newIPs == 1 ? "Saved %s new IP" : "Saved %s new IPs", newIPs); }, e -> { MeteorRejectsAddon.LOG.error("Could not save IPs"); toast("Something went wrong", "The IPs could not be saved, look at the log for details"); }); l.add(theme.button("Load IPs")).expandX().widget().action = tryHandle(() -> { String targetPath = TinyFileDialogs.tinyfd_openFileDialog("Load IPs", null, saveFileFilters, "", false); if (targetPath == null) return; Path filePath = Path.of(targetPath); if (!Files.exists(filePath)) return;
List<ServerInfo> servers = ((ServerListAccessor) multiplayerScreen.getServerList()).getServers();
2
2023-11-13 08:11:28+00:00
4k
stiemannkj1/java-utilities
src/test/java/dev/stiemannkj1/collection/fixmapping/FixMappingsTests.java
[ { "identifier": "binarySearchArrayPrefixMapping", "path": "src/main/java/dev/stiemannkj1/collection/fixmapping/FixMappings.java", "snippet": "public static <T> ImmutablePrefixMapping<T> binarySearchArrayPrefixMapping(\n final Map<String, T> prefixes) {\n return new BinarySearchArrayPrefixMapping<>(p...
import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArrayPrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.binarySearchArraySuffixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTriePrefixMapping; import static dev.stiemannkj1.collection.fixmapping.FixMappings.limitedCharArrayTrieSuffixMapping; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutablePrefixMapping; import dev.stiemannkj1.collection.fixmapping.FixMappings.ImmutableSuffixMapping; import dev.stiemannkj1.util.Pair; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource;
3,175
final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get()); // Test odd number of prefixes. prefixes.put("aaa", 4); prefixMap = newPrefixMap(prefixes); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get()); } @Test default void allows_prefixes_with_matching_suffixes() { // Test odd number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map; assertDoesNotThrow(() -> newPrefixMap(suffixes)); } static Stream<Map<String, Integer>> invalidPrefixes() { return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidPrefixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> prefixes) { final Class<? extends Exception> expectedExceptionType = prefixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes)); } ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes); } interface SuffixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "1abc,true,0", "abe,true,1", "abed,false,null", "abd,false,null", "aba,false,null", "at,false,null", "ate,true,2", "cate,true,2", "icate,true,2", "dicate,true,2", "bdicate,true,2", "abdicate,true,3", "i abdicate,true,3", "abdicated,false,null", "z,false,null", "yz,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_suffixes( final String string, final boolean expectSuffixed, final Integer expectedValue) { // Test even number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
/* Copyright 2023 Kyle J. Stiemann Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package dev.stiemannkj1.collection.fixmapping; final class FixMappingsTests { // TODO test unicode interface PrefixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "abe,true,1", "abd,true,2", "aba,false,null", "abd,true,2", "abdi,true,2", "abdic,true,2", "abdica,true,2", "abdicat,true,2", "abdicat,true,2", "abdicate,true,3", "abdicated,true,3", "x,false,null", "xy,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_prefixes( final String string, final boolean expectPrefixed, final Integer expectedValue) { // Test odd number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); // Test odd number of prefixes. prefixes.put("xyz", 4); prefixMap = newPrefixMap(prefixes); assertEquals(expectPrefixed, prefixMap.matchesAnyPrefix(string)); assertEquals(expectedValue, prefixMap.valueForPrefix(string)); assertEquals( getKeyAndValueByValue(prefixes, expectedValue), prefixMap.keyAndValueForPrefix(string)); assertFirstMatchSearchTakesLessSteps( string, expectedValue, (FixMappings.FixMapping<Integer>) prefixMap); } @SuppressWarnings("unchecked") default void detects_prefixes_with_minimal_steps( final String string, final String firstMatchEvenKeys, final String firstMatchOddKeys, final int firstMatchStepsEvenKeys, final int longestMatchStepsEvenKeys, final int firstMatchStepsOddKeys, final int longestMatchStepsOddKeys) { // Test even number of prefixes. final Map<String, Integer> prefixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("abd", 2).add("abdicate", 3).map; ImmutablePrefixMapping<Integer> prefixMap = newPrefixMap(prefixes); final AtomicLong firstSearchSteps = new AtomicLong(); final AtomicLong longestSearchSteps = new AtomicLong(); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchEvenKeys, prefixes.get(firstMatchEvenKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsEvenKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsEvenKeys, longestSearchSteps.get()); // Test odd number of prefixes. prefixes.put("aaa", 4); prefixMap = newPrefixMap(prefixes); firstSearchSteps.set(0); longestSearchSteps.set(0); assertEquals( Pair.of(firstMatchOddKeys, prefixes.get(firstMatchOddKeys)), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(false, string, firstSearchSteps)); assertEquals( Pair.of("abdicate", 3), ((FixMappings.FixMapping<Integer>) prefixMap) .getKeyAndValue(true, string, longestSearchSteps)); assertEquals(firstMatchStepsOddKeys, firstSearchSteps.get()); assertEquals(longestMatchStepsOddKeys, longestSearchSteps.get()); } @Test default void allows_prefixes_with_matching_suffixes() { // Test odd number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("bdicate", 0).add("abdicate", 2).map; assertDoesNotThrow(() -> newPrefixMap(suffixes)); } static Stream<Map<String, Integer>> invalidPrefixes() { return Stream.of( Collections.emptyMap(), newTestMapBuilder().add(null, 1).map, newTestMapBuilder().add(null, 1).add("asdf", 1).map, newTestMapBuilder().add("", 1).map, newTestMapBuilder().add("", 1).add("asdf", 1).map, // Invalid map with duplicate keys: toMap(Arrays.asList(Pair.of("asdf", 1), Pair.of("asdf", 1))), // Invalid map with null entry: toMap(Arrays.asList(null, Pair.of("asdf", 1)))); } @MethodSource("invalidPrefixes") @ParameterizedTest default void throws_illegal_arg_when_provided_invalid_values( final Map<String, Integer> prefixes) { final Class<? extends Exception> expectedExceptionType = prefixes != null ? IllegalArgumentException.class : NullPointerException.class; assertThrows(expectedExceptionType, () -> newPrefixMap(prefixes)); } ImmutablePrefixMapping<Integer> newPrefixMap(final Map<String, Integer> prefixes); } interface SuffixMappersTests { @CsvSource( value = { "null,false,null", ",false,null", "123456,false,null", "~~~~~~,false,null", "a,false,null", "ab,false,null", "abc,true,0", "1abc,true,0", "abe,true,1", "abed,false,null", "abd,false,null", "aba,false,null", "at,false,null", "ate,true,2", "cate,true,2", "icate,true,2", "dicate,true,2", "bdicate,true,2", "abdicate,true,3", "i abdicate,true,3", "abdicated,false,null", "z,false,null", "yz,false,null" }, nullValues = "null") @ParameterizedTest @SuppressWarnings("unchecked") default void detects_suffixes( final String string, final boolean expectSuffixed, final Integer expectedValue) { // Test even number of suffixes. final Map<String, Integer> suffixes = newTestMapBuilder().add("abc", 0).add("abe", 1).add("ate", 2).add("abdicate", 3).map;
ImmutableSuffixMapping<Integer> suffixMap = newSuffixMap(suffixes);
5
2023-11-12 05:05:22+00:00
4k
slow3586/HypersomniaMapGen
src/main/java/com/slow3586/Main.java
[ { "identifier": "RoomStyle", "path": "src/main/java/com/slow3586/Main.java", "snippet": "@Value\npublic static class RoomStyle {\n int height;\n Color floorColor;\n Color wallColor;\n int patternIdFloor;\n int patternIdWall;\n Color patternColorFloor;\n Color patternColorWall;\n}" ...
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JacksonException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.slow3586.Main.Room.RoomStyle; import com.slow3586.Main.Settings.Node.ExternalResource; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.ToString; import lombok.Value; import org.jooq.lambda.Sneaky; import org.jooq.lambda.function.Consumer1; import org.jooq.lambda.function.Consumer2; import org.jooq.lambda.function.Consumer4; import org.jooq.lambda.function.Function1; import org.jooq.lambda.function.Function3; import java.awt.*; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Random; import java.util.StringJoiner; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.stream.IntStream; import java.util.stream.Stream; import static com.slow3586.Main.Color.WHITE; import static com.slow3586.Main.MapTile.TileType.DOOR; import static com.slow3586.Main.MapTile.TileType.WALL; import static com.slow3586.Main.Settings.Layer; import static com.slow3586.Main.Settings.Node; import static com.slow3586.Main.Settings.Node.AsNonPhysical.AS_NON_PHYSICAL_DEFAULT; import static com.slow3586.Main.Settings.Node.AsPhysical.AS_PHYSICAL_DEFAULT; import static com.slow3586.Main.Settings.Node.ExternalResource.BASE_PNG_TEXTURE_FILENAME; import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_BLOCKING; import static com.slow3586.Main.Settings.Node.ExternalResource.CRATE_NON_BLOCKING; import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_FOREGROUND; import static com.slow3586.Main.Settings.Node.ExternalResource.DOMAIN_PHYSICAL; import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_FLOOR; import static com.slow3586.Main.Settings.Node.ExternalResource.LINE_WALL; import static com.slow3586.Main.Settings.Node.ExternalResource.MAP_GFX_PATH; import static com.slow3586.Main.Settings.Node.ExternalResource.PNG_EXT; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_FLOOR_ID; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_ID_PREFIX; import static com.slow3586.Main.Settings.Node.ExternalResource.RESOURCE_WALL_ID; import static com.slow3586.Main.Settings.Node.ExternalResource.ROOM_NOISE_CIRCLE; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_CORNER; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_FLOOR_LINE; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_CORNER; import static com.slow3586.Main.Settings.Node.ExternalResource.SHADOW_WALL_LINE; import static com.slow3586.Main.Settings.Playtesting; import static com.slow3586.Main.Size.CRATE_SIZE; import static com.slow3586.Main.Size.TILE_SIZE;
3,441
package com.slow3586; public class Main { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static Random baseRandom; static Configuration config; static { OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); } public static void main(String[] args) throws IOException { //region CONFIGURATION final String configStr = Files.readString(Path.of("config.json")); config = OBJECT_MAPPER.readValue(configStr, Configuration.class); baseRandom = new Random(config.randomSeed); final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName); //endregion //region GENERATION: ROOMS //region RANDOMIZE DIAGONAL ROOM SIZES final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize()) .limit(Math.max(config.roomsCount.x, config.roomsCount.y)) .toArray(Size[]::new); //endregion //region RANDOMIZE ROOM STYLES
package com.slow3586; public class Main { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static Random baseRandom; static Configuration config; static { OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL); } public static void main(String[] args) throws IOException { //region CONFIGURATION final String configStr = Files.readString(Path.of("config.json")); config = OBJECT_MAPPER.readValue(configStr, Configuration.class); baseRandom = new Random(config.randomSeed); final Path mapDirectory = Path.of(config.gameDirectoryPath, "user", "projects", config.mapName); //endregion //region GENERATION: ROOMS //region RANDOMIZE DIAGONAL ROOM SIZES final Size[] diagonalRoomSizes = Stream.generate(() -> config.roomMinMaxSize.randomize()) .limit(Math.max(config.roomsCount.x, config.roomsCount.y)) .toArray(Size[]::new); //endregion //region RANDOMIZE ROOM STYLES
final RoomStyle[] styles = IntStream.range(0, config.styleCount)
0
2023-11-18 14:36:04+00:00
4k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/CameraActivity.java
[ { "identifier": "BaseActivity", "path": "library/base/src/main/java/com/hjq/base/BaseActivity.java", "snippet": "public abstract class BaseActivity extends AppCompatActivity\n implements ActivityAction, ClickAction,\n HandlerAction, BundleAction, KeyboardAction {\n\n /** 错误结果码 */\n p...
import android.content.Intent; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import androidx.core.content.FileProvider; import com.hjq.base.BaseActivity; import com.buaa.food.R; import com.buaa.food.aop.Log; import com.buaa.food.aop.Permissions; import com.buaa.food.app.AppActivity; import com.buaa.food.other.AppConfig; import com.hjq.permissions.Permission; import com.hjq.permissions.XXPermissions; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
3,168
package com.buaa.food.ui.activity; public final class CameraActivity extends AppActivity { public static final String INTENT_KEY_IN_FILE = "file"; public static final String INTENT_KEY_IN_VIDEO = "video"; public static final String INTENT_KEY_OUT_ERROR = "error";
package com.buaa.food.ui.activity; public final class CameraActivity extends AppActivity { public static final String INTENT_KEY_IN_FILE = "file"; public static final String INTENT_KEY_IN_VIDEO = "video"; public static final String INTENT_KEY_OUT_ERROR = "error";
public static void start(BaseActivity activity, OnCameraListener listener) {
0
2023-11-14 10:04:26+00:00
4k
WallasAR/GUITest
src/main/java/com/session/employee/medOrderController.java
[ { "identifier": "Main", "path": "src/main/java/com/example/guitest/Main.java", "snippet": "public class Main extends Application {\n\n private static Stage stage; // Variavel estaticas para fazer a mudança de tela\n\n private static Scene mainScene, homeScene, funcScene, medScene, clientScene, rec...
import com.example.guitest.Main; import com.table.view.EncomendasTable; import com.warning.alert.AlertMsg; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.input.MouseEvent; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import static com.db.bank.Banco.connection; import javafx.scene.control.cell.PropertyValueFactory; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle;
2,118
package com.session.employee; public class medOrderController implements Initializable { @FXML protected void MainAction(MouseEvent e) { if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) { Main.changedScene("main"); } } @FXML protected void SaleAction(MouseEvent e) { Main.changedScene("sale"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("ClientAdmFunc"); } @FXML private TableColumn tcDateOrder; @FXML private TableColumn tcIdOrder; @FXML private TableColumn tcMedOrder; @FXML private TableColumn tcPhoneOrder; @FXML private TableColumn tcPriceOrder; @FXML private TableColumn tcQuantOrder; @FXML private TableColumn tcStatusOrder; @FXML private TableColumn tcUserOrder; @FXML private TableView tvOrder; @FXML private TextField tfSearch; @FXML private TextField tfUpdateStatus; @FXML private TextField tfIdStatus; public void tableOrder()throws SQLException{ List<EncomendasTable> order = new ArrayList<>(); String consultaSQLcliente = "SELECT * FROM encomendas";
package com.session.employee; public class medOrderController implements Initializable { @FXML protected void MainAction(MouseEvent e) { if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) { Main.changedScene("main"); } } @FXML protected void SaleAction(MouseEvent e) { Main.changedScene("sale"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("ClientAdmFunc"); } @FXML private TableColumn tcDateOrder; @FXML private TableColumn tcIdOrder; @FXML private TableColumn tcMedOrder; @FXML private TableColumn tcPhoneOrder; @FXML private TableColumn tcPriceOrder; @FXML private TableColumn tcQuantOrder; @FXML private TableColumn tcStatusOrder; @FXML private TableColumn tcUserOrder; @FXML private TableView tvOrder; @FXML private TextField tfSearch; @FXML private TextField tfUpdateStatus; @FXML private TextField tfIdStatus; public void tableOrder()throws SQLException{ List<EncomendasTable> order = new ArrayList<>(); String consultaSQLcliente = "SELECT * FROM encomendas";
Statement statement = connection.createStatement();
3
2023-11-16 14:55:08+00:00
4k
wzh933/Buffer-Manager
src/test/java/cs/adb/wzh/bufferManager/BMgrTest.java
[ { "identifier": "Buffer", "path": "src/main/java/cs/adb/wzh/Storage/Buffer.java", "snippet": "public class Buffer {\n private final int bufSize;\n private final Frame[] buf;\n\n public int getBufSize() {\n return bufSize;\n }\n\n public Frame[] getBuf() {\n return buf;\n ...
import cs.adb.wzh.Storage.Buffer; import cs.adb.wzh.Storage.Disk; import cs.adb.wzh.bufferControlBlocks.BCB; import cs.adb.wzh.utils.PageRequestReader; import cs.adb.wzh.utils.SwapMethod; import org.junit.jupiter.api.Test;
1,930
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ class BMgrTest { @Test void bMgrTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) { System.out.println(p.getFrameId()); } System.out.println(); for (BCB p = bMgr.getTail().getPre(); p.getFrameId() != -1; p = p.getPre()) { System.out.println(p.getFrameId()); } // System.out.println(bMgr.getTail().getFrameId()); } @Test void bcbTableTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); BCB[] bcbTable = bMgr.getBcbTable(); for (BCB bcb : bcbTable) { System.out.println(bcb.getFrameId()); } System.out.println(); for (BCB bcb : bcbTable) { System.out.println(bcb.getNext().getFrameId()); } } @Test void bcbMove2HeadTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); BCB[] bcbTable = bMgr.getBcbTable(); bMgr.move2Head(bMgr.getTail().getPre()); for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) { System.out.println(p.getFrameId()); } } @Test void fixPageTest() throws Exception { Buffer bf = new Buffer(); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); bMgr.setSwapMethod(SwapMethod.CLOCK); // bMgr.setSwapMethod(SwapMethod.LRU); /* //这样就会有”当前磁盘已满,无法分配新页面!“的警告 for (int i = 0; i < 65537; i++) { System.out.println(bMgr.fixNewPage()); } bMgr.fixNewPage(); bMgr.fixPage(10); */ int fileLength = 50000; int[] pageIds = new int[fileLength]; for (int i = 0; i < fileLength; i++) { pageIds[i] = bMgr.fixNewPage(); } // PageRequestReader prr = new PageRequestReader("src/main/resources/testTxt1.txt");
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ class BMgrTest { @Test void bMgrTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) { System.out.println(p.getFrameId()); } System.out.println(); for (BCB p = bMgr.getTail().getPre(); p.getFrameId() != -1; p = p.getPre()) { System.out.println(p.getFrameId()); } // System.out.println(bMgr.getTail().getFrameId()); } @Test void bcbTableTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); BCB[] bcbTable = bMgr.getBcbTable(); for (BCB bcb : bcbTable) { System.out.println(bcb.getFrameId()); } System.out.println(); for (BCB bcb : bcbTable) { System.out.println(bcb.getNext().getFrameId()); } } @Test void bcbMove2HeadTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); BCB[] bcbTable = bMgr.getBcbTable(); bMgr.move2Head(bMgr.getTail().getPre()); for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) { System.out.println(p.getFrameId()); } } @Test void fixPageTest() throws Exception { Buffer bf = new Buffer(); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk); bMgr.setSwapMethod(SwapMethod.CLOCK); // bMgr.setSwapMethod(SwapMethod.LRU); /* //这样就会有”当前磁盘已满,无法分配新页面!“的警告 for (int i = 0; i < 65537; i++) { System.out.println(bMgr.fixNewPage()); } bMgr.fixNewPage(); bMgr.fixPage(10); */ int fileLength = 50000; int[] pageIds = new int[fileLength]; for (int i = 0; i < fileLength; i++) { pageIds[i] = bMgr.fixNewPage(); } // PageRequestReader prr = new PageRequestReader("src/main/resources/testTxt1.txt");
PageRequestReader prr = new PageRequestReader("src/main/resources/data-5w-50w-zipf.txt");
3
2023-11-15 16:30:06+00:00
4k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/utilities/Utilities.java
[ { "identifier": "DragonFly", "path": "src/main/java/useless/dragonfly/DragonFly.java", "snippet": "public class DragonFly implements GameStartEntrypoint {\n public static final String MOD_ID = \"dragonfly\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static fi...
import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.Minecraft; import net.minecraft.core.Global; import net.minecraft.core.data.DataLoader; import useless.dragonfly.DragonFly; import useless.dragonfly.utilities.vector.Vector3f; import java.io.InputStream; import java.lang.reflect.Field;
3,502
package useless.dragonfly.utilities; public class Utilities { public static final float COMPARE_CONST = 0.001f; public static String writeFields(Class<?> clazz){ Field[] fields = clazz.getFields(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; builder.append(field.getName()).append(": ").append(field.getClass().cast(field)); if (i < fields.length-1){ builder.append("\n"); } } return builder.toString(); } public static String tabBlock(String string, int tabAmount){ StringBuilder builder = new StringBuilder(); for (String line: string.split("\n")) { builder.append(tabString(tabAmount)).append(line).append("\n"); } return builder.toString(); } public static String tabString(int tabAmount){ StringBuilder builder = new StringBuilder(); for (int i = 0; i < tabAmount; i++) { builder.append("\t"); } return builder.toString(); } public static boolean equalFloats(float a, float b){ return Math.abs(Float.compare(a, b)) < COMPARE_CONST; }
package useless.dragonfly.utilities; public class Utilities { public static final float COMPARE_CONST = 0.001f; public static String writeFields(Class<?> clazz){ Field[] fields = clazz.getFields(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; builder.append(field.getName()).append(": ").append(field.getClass().cast(field)); if (i < fields.length-1){ builder.append("\n"); } } return builder.toString(); } public static String tabBlock(String string, int tabAmount){ StringBuilder builder = new StringBuilder(); for (String line: string.split("\n")) { builder.append(tabString(tabAmount)).append(line).append("\n"); } return builder.toString(); } public static String tabString(int tabAmount){ StringBuilder builder = new StringBuilder(); for (int i = 0; i < tabAmount; i++) { builder.append("\t"); } return builder.toString(); } public static boolean equalFloats(float a, float b){ return Math.abs(Float.compare(a, b)) < COMPARE_CONST; }
public static Vector3f rotatePoint(Vector3f point, Vector3f origin, String axis, float angle){
1
2023-11-16 01:10:52+00:00
4k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/config/oss/minio/MinioConfiguration.java
[ { "identifier": "Constants", "path": "src/main/java/top/sharehome/springbootinittemplate/common/base/Constants.java", "snippet": "public interface Constants {\n\n /**\n * UTF-8 字符集\n */\n String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n String GBK = \"GBK\";\n\n /**\n ...
import io.minio.MinioClient; import io.minio.PutObjectArgs; import io.minio.RemoveObjectArgs; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.ObjectUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.web.multipart.MultipartFile; import top.sharehome.springbootinittemplate.common.base.Constants; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.oss.minio.condition.OssMinioCondition; import top.sharehome.springbootinittemplate.config.oss.minio.properties.MinioProperties; import top.sharehome.springbootinittemplate.exception.customize.CustomizeFileException; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import javax.annotation.PostConstruct; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.UUID;
3,559
package top.sharehome.springbootinittemplate.config.oss.minio; /** * MinIO配置 * * @author AntonyCheng */ @Configuration @EnableConfigurationProperties(MinioProperties.class) @AllArgsConstructor @Slf4j @Conditional(OssMinioCondition.class) public class MinioConfiguration { private final MinioProperties minioProperties; /** * 上传文件到MinIO * * @param file 待上传的文件 * @param rootPath 上传的路径 * @return 文件所在路径 */ public String uploadToMinio(MultipartFile file, String rootPath) { MinioClient minioClient = getMinioClient(); String key; try { if (file == null) {
package top.sharehome.springbootinittemplate.config.oss.minio; /** * MinIO配置 * * @author AntonyCheng */ @Configuration @EnableConfigurationProperties(MinioProperties.class) @AllArgsConstructor @Slf4j @Conditional(OssMinioCondition.class) public class MinioConfiguration { private final MinioProperties minioProperties; /** * 上传文件到MinIO * * @param file 待上传的文件 * @param rootPath 上传的路径 * @return 文件所在路径 */ public String uploadToMinio(MultipartFile file, String rootPath) { MinioClient minioClient = getMinioClient(); String key; try { if (file == null) {
throw new CustomizeFileException(ReturnCode.USER_DO_NOT_UPLOAD_FILE);
4
2023-11-12 07:49:59+00:00
4k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/render/Window.java
[ { "identifier": "EventBus", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/event/EventBus.java", "snippet": "public final class EventBus {\n private static final class HandlerFn implements Comparable<HandlerFn> {\n private final Listener listener;\n private final Method me...
import com.github.rmheuer.azalea.event.EventBus; import com.github.rmheuer.azalea.input.keyboard.Keyboard; import com.github.rmheuer.azalea.input.mouse.Mouse; import com.github.rmheuer.azalea.render.opengl.OpenGLWindow; import com.github.rmheuer.azalea.utils.SafeCloseable; import org.joml.Vector2i;
1,701
package com.github.rmheuer.azalea.render; /** * Represents the platform window graphics are rendered into. There can * currently only be one window at a time. */ public interface Window extends SafeCloseable { /** * Gets the renderer used to render into this window. * * @return renderer */ Renderer getRenderer(); /** * Gets whether the window should currently close. This will be true after * something has requested the window to close, such as pressing its close * button. * * @return whether the window should close */ boolean shouldClose(); /** * Updates the contents of the window. This will show the result of * rendering done using {@link #getRenderer()}. This may temporarily block * if VSync is enabled, in order to limit the frame rate. */ void update(); /** * Sets the window title. This is typically shown in the window's title * bar. * * @param title new window title */ void setTitle(String title); /** * Gets the size of the window's framebuffer. This is not necessarily the * same as the window's size, since the framebuffer may be larger on high * DPI displays. * * @return size of the framebuffer */ Vector2i getFramebufferSize(); /** * Gets the size of the window. * * @return window size */ Vector2i getSize(); /** * Gets the window's keyboard input. * * @return keyboard input */
package com.github.rmheuer.azalea.render; /** * Represents the platform window graphics are rendered into. There can * currently only be one window at a time. */ public interface Window extends SafeCloseable { /** * Gets the renderer used to render into this window. * * @return renderer */ Renderer getRenderer(); /** * Gets whether the window should currently close. This will be true after * something has requested the window to close, such as pressing its close * button. * * @return whether the window should close */ boolean shouldClose(); /** * Updates the contents of the window. This will show the result of * rendering done using {@link #getRenderer()}. This may temporarily block * if VSync is enabled, in order to limit the frame rate. */ void update(); /** * Sets the window title. This is typically shown in the window's title * bar. * * @param title new window title */ void setTitle(String title); /** * Gets the size of the window's framebuffer. This is not necessarily the * same as the window's size, since the framebuffer may be larger on high * DPI displays. * * @return size of the framebuffer */ Vector2i getFramebufferSize(); /** * Gets the size of the window. * * @return window size */ Vector2i getSize(); /** * Gets the window's keyboard input. * * @return keyboard input */
Keyboard getKeyboard();
1
2023-11-16 04:46:53+00:00
4k
orijer/IvritInterpreter
src/Evaluation/EvaluationController.java
[ { "identifier": "BooleanVariable", "path": "src/Variables/BooleanVariable.java", "snippet": "public class BooleanVariable extends AbstractVariable<Boolean> {\r\n //An array of all the operators boolean values support:\r\n public static String[] BOOLEAN_OPERATORS = { \"שווה\", \"לא-שווה\", \"וגם\",...
import Variables.BooleanVariable; import Variables.StringVariable; import Variables.VariablesController;
2,232
package Evaluation; /** * Handles evaluating a string based on its expected value type. */ public class EvaluationController { //Contains the variables of the program: private VariablesController variablesController; /** * Constructor. * @param variablesController - Contains the variables of the program. */ public EvaluationController(VariablesController variablesController) { this.variablesController = variablesController; } /** * Evaluates a given data string. * @param data - The data to evaluate. * @return the evaluated value of the given string (still represented as a string). */ public String evaluate(String data) { //We first switch all variables with their values, so now we only deal with the values themselves: VariableValueSwapper swapper = new VariableValueSwapper(this.variablesController); data = swapper.swap(data); Evaluator evaluator; //Find the correct evaluator type: if (BooleanVariable.containsBooleanExpression(data)) { //Boolean evaluator: evaluator = new BooleanEvaluator();
package Evaluation; /** * Handles evaluating a string based on its expected value type. */ public class EvaluationController { //Contains the variables of the program: private VariablesController variablesController; /** * Constructor. * @param variablesController - Contains the variables of the program. */ public EvaluationController(VariablesController variablesController) { this.variablesController = variablesController; } /** * Evaluates a given data string. * @param data - The data to evaluate. * @return the evaluated value of the given string (still represented as a string). */ public String evaluate(String data) { //We first switch all variables with their values, so now we only deal with the values themselves: VariableValueSwapper swapper = new VariableValueSwapper(this.variablesController); data = swapper.swap(data); Evaluator evaluator; //Find the correct evaluator type: if (BooleanVariable.containsBooleanExpression(data)) { //Boolean evaluator: evaluator = new BooleanEvaluator();
} else if (StringVariable.containsLiteralStrings(data)) {
1
2023-11-17 09:15:07+00:00
4k
WuKongOpenSource/Wukong_HRM
common/common-web/src/main/java/com/kakarote/core/config/WebConfig.java
[ { "identifier": "Const", "path": "common/common-web/src/main/java/com/kakarote/core/common/Const.java", "snippet": "public class Const implements Serializable {\n\n /**\n * 项目版本\n */\n public static final String PROJECT_VERSION = \"12.3.6\";\n\n /**\n * 默认分隔符\n */\n public st...
import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer; import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator; import com.baomidou.mybatisplus.extension.MybatisMapWrapperFactory; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.json.JsonMapper; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.kakarote.core.common.Const; import com.kakarote.core.utils.BaseUtil; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.io.IOException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Date; import java.util.List; import java.util.TimeZone;
2,782
package com.kakarote.core.config; /** * web配置类 以及分页配置 * @author zhangzhiwei */ @Configuration public class WebConfig { @Value("${spring.jackson.timeZone:GMT+8}") private String timeZone; /** * long类型数据统一处理转换为string */ @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return jacksonObjectMapperBuilder -> { jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance); jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance); jacksonObjectMapperBuilder.deserializerByType(Date.class, new DateDeSerializer()); //localDate类型的序列化 jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER)); //localDate类型的反序列化 jacksonObjectMapperBuilder.deserializers(new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER)); }; } /** * 对objectMapper增加一些时间类型的处理 * * @return objectMapper */ @Bean public ObjectMapper buildObjectMapper() { ObjectMapper objectMapper = new JsonMapper(); objectMapper.registerModule(new Jdk8Module()); objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN)); objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone)); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER)); javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER)); javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER)); javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER)); javaTimeModule.addDeserializer(Date.class, new DateDeSerializer()); javaTimeModule.addSerializer(Long.class, ToStringSerializer.instance); javaTimeModule.addSerializer(Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule(javaTimeModule); return objectMapper; } @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(List<InnerInterceptor> interceptors) { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); for (InnerInterceptor innerInterceptor : interceptors) { interceptor.addInnerInterceptor(innerInterceptor); } return interceptor; } @Bean public PaginationInnerInterceptor paginationInterceptor() { PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
package com.kakarote.core.config; /** * web配置类 以及分页配置 * @author zhangzhiwei */ @Configuration public class WebConfig { @Value("${spring.jackson.timeZone:GMT+8}") private String timeZone; /** * long类型数据统一处理转换为string */ @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return jacksonObjectMapperBuilder -> { jacksonObjectMapperBuilder.serializerByType(Long.TYPE, ToStringSerializer.instance); jacksonObjectMapperBuilder.serializerByType(Long.class, ToStringSerializer.instance); jacksonObjectMapperBuilder.deserializerByType(Date.class, new DateDeSerializer()); //localDate类型的序列化 jacksonObjectMapperBuilder.serializers(new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER)); //localDate类型的反序列化 jacksonObjectMapperBuilder.deserializers(new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER), new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER)); }; } /** * 对objectMapper增加一些时间类型的处理 * * @return objectMapper */ @Bean public ObjectMapper buildObjectMapper() { ObjectMapper objectMapper = new JsonMapper(); objectMapper.registerModule(new Jdk8Module()); objectMapper.setDateFormat(new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN)); objectMapper.setTimeZone(TimeZone.getTimeZone(timeZone)); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JavaTimeModule javaTimeModule = new JavaTimeModule(); javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DatePattern.NORM_DATETIME_FORMATTER)); javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DatePattern.NORM_DATE_FORMATTER)); javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DatePattern.NORM_DATETIME_FORMATTER)); javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DatePattern.NORM_DATE_FORMATTER)); javaTimeModule.addDeserializer(Date.class, new DateDeSerializer()); javaTimeModule.addSerializer(Long.class, ToStringSerializer.instance); javaTimeModule.addSerializer(Long.TYPE, ToStringSerializer.instance); objectMapper.registerModule(javaTimeModule); return objectMapper; } @Bean public MybatisPlusInterceptor mybatisPlusInterceptor(List<InnerInterceptor> interceptors) { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); for (InnerInterceptor innerInterceptor : interceptors) { interceptor.addInnerInterceptor(innerInterceptor); } return interceptor; } @Bean public PaginationInnerInterceptor paginationInterceptor() { PaginationInnerInterceptor paginationInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
paginationInterceptor.setMaxLimit(Const.QUERY_MAX_SIZE * 100);
0
2023-10-17 05:49:52+00:00
4k
WisdomShell/codeshell-intellij
src/main/java/com/codeshell/intellij/actions/assistants/StyleCheck.java
[ { "identifier": "PrefixString", "path": "src/main/java/com/codeshell/intellij/constant/PrefixString.java", "snippet": "public interface PrefixString {\n\n String EXPLAIN_CODE = \"请解释以下%s代码: %s\";\n\n String OPTIMIZE_CODE = \"请优化以下%s代码: %s\";\n\n String CLEAN_CODE = \"请清理以下%s代码: %s\";\n\n Str...
import com.codeshell.intellij.constant.PrefixString; import com.codeshell.intellij.services.CodeShellSideWindowService; import com.codeshell.intellij.utils.EditorUtils; import com.google.gson.JsonObject; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.util.IntentionFamilyName; import com.intellij.codeInspection.util.IntentionName; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.psi.PsiFile; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import java.util.Objects;
2,074
package com.codeshell.intellij.actions.assistants; public class StyleCheck extends DumbAwareAction implements IntentionAction { @SafeFieldForPreview private Logger logger = Logger.getInstance(this.getClass()); @Override @IntentionName @NotNull public String getText() { return "Style Check"; } @Override @NotNull @IntentionFamilyName public String getFamilyName() { return "CodeShell"; } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return false; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { } @Override public boolean startInWriteAction() { return true; } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getData(LangDataKeys.PROJECT); if (Objects.isNull(project)) { return; } ApplicationManager.getApplication().invokeLater(() -> { VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE); Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
package com.codeshell.intellij.actions.assistants; public class StyleCheck extends DumbAwareAction implements IntentionAction { @SafeFieldForPreview private Logger logger = Logger.getInstance(this.getClass()); @Override @IntentionName @NotNull public String getText() { return "Style Check"; } @Override @NotNull @IntentionFamilyName public String getFamilyName() { return "CodeShell"; } @Override public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { return false; } @Override public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { } @Override public boolean startInWriteAction() { return true; } @Override public void actionPerformed(@NotNull AnActionEvent e) { Project project = e.getData(LangDataKeys.PROJECT); if (Objects.isNull(project)) { return; } ApplicationManager.getApplication().invokeLater(() -> { VirtualFile vf = e.getRequiredData(CommonDataKeys.VIRTUAL_FILE); Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
if (EditorUtils.isNoneTextSelected(editor)) {
2
2023-10-18 06:29:13+00:00
4k
djkcyl/Shamrock
qqinterface/src/main/java/tencent/im/oidb/cmd0x8fc/Oidb_0x8fc.java
[ { "identifier": "ByteStringMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/ByteStringMicro.java", "snippet": "public class ByteStringMicro {\n public static final ByteStringMicro EMPTY = null;\n\n public static ByteStringMicro copyFrom(String str, String str2) {\n return ...
import com.tencent.mobileqq.pb.ByteStringMicro; import com.tencent.mobileqq.pb.MessageMicro; import com.tencent.mobileqq.pb.PBBytesField; import com.tencent.mobileqq.pb.PBEnumField; import com.tencent.mobileqq.pb.PBField; import com.tencent.mobileqq.pb.PBRepeatMessageField; import com.tencent.mobileqq.pb.PBStringField; import com.tencent.mobileqq.pb.PBUInt32Field; import com.tencent.mobileqq.pb.PBUInt64Field;
1,752
package tencent.im.oidb.cmd0x8fc; public class Oidb_0x8fc { public static final class ReqBody extends MessageMicro<ReqBody> { public final PBUInt64Field uint64_group_code = PBField.initUInt64(0); public final PBUInt32Field uint32_show_flag = PBField.initUInt32(0); public final PBRepeatMessageField<MemberInfo> rpt_mem_level_info = PBField.initRepeatMessage(MemberInfo.class); public final PBRepeatMessageField<LevelName> rpt_level_name = PBField.initRepeatMessage(LevelName.class); public final PBUInt32Field uint32_update_time = PBField.initUInt32(0); public final PBUInt32Field uint32_office_mode = PBField.initUInt32(0); public final PBUInt32Field uint32_group_open_appid = PBField.initUInt32(0); public ClientInfo msg_client_info = new ClientInfo();
package tencent.im.oidb.cmd0x8fc; public class Oidb_0x8fc { public static final class ReqBody extends MessageMicro<ReqBody> { public final PBUInt64Field uint64_group_code = PBField.initUInt64(0); public final PBUInt32Field uint32_show_flag = PBField.initUInt32(0); public final PBRepeatMessageField<MemberInfo> rpt_mem_level_info = PBField.initRepeatMessage(MemberInfo.class); public final PBRepeatMessageField<LevelName> rpt_level_name = PBField.initRepeatMessage(LevelName.class); public final PBUInt32Field uint32_update_time = PBField.initUInt32(0); public final PBUInt32Field uint32_office_mode = PBField.initUInt32(0); public final PBUInt32Field uint32_group_open_appid = PBField.initUInt32(0); public ClientInfo msg_client_info = new ClientInfo();
public final PBBytesField bytes_auth_key = PBField.initBytes(ByteStringMicro.EMPTY);
0
2023-10-20 10:43:47+00:00
4k
ballerina-platform/module-ballerinax-copybook
native/src/main/java/io/ballerina/lib/copybook/runtime/convertor/Utils.java
[ { "identifier": "Copybook", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/Copybook.java", "snippet": "public class Copybook {\n\n private Copybook() {\n }\n\n public static Schema parse(String schemaPath) throws IOException {\n CopybookLexer lexer = new Copybook...
import io.ballerina.lib.copybook.commons.schema.Copybook; import io.ballerina.lib.copybook.commons.schema.CopybookNode; import io.ballerina.lib.copybook.commons.schema.DataItem; import io.ballerina.lib.copybook.commons.schema.GroupItem; import io.ballerina.lib.copybook.commons.schema.Schema; import io.ballerina.runtime.api.Environment; import io.ballerina.runtime.api.Future; import io.ballerina.runtime.api.PredefinedTypes; import io.ballerina.runtime.api.creators.ErrorCreator; import io.ballerina.runtime.api.creators.TypeCreator; import io.ballerina.runtime.api.creators.ValueCreator; import io.ballerina.runtime.api.types.ArrayType; import io.ballerina.runtime.api.types.MapType; import io.ballerina.runtime.api.types.ObjectType; import io.ballerina.runtime.api.utils.StringUtils; import io.ballerina.runtime.api.values.BArray; import io.ballerina.runtime.api.values.BError; import io.ballerina.runtime.api.values.BMap; import io.ballerina.runtime.api.values.BObject; import io.ballerina.runtime.api.values.BString; import io.ballerina.runtime.api.values.BTypedesc; import java.io.IOException; import java.util.ArrayList; import java.util.List; import static io.ballerina.lib.copybook.runtime.converter.ModuleUtils.getModule;
2,651
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. 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 io.ballerina.lib.copybook.runtime.converter; public final class Utils { private static final String NATIVE_VALUE = "native-value"; private static final String TO_RECORD_METHOD_NAME = "toRecord"; private static final String NODE_TYPE_NAME = "Node"; private static final String SCHEMA_TYPE_NAME = "Schema"; private static final String GROUP_ITEM_TYPE_NAME = "GroupItem"; private static final String DATA_ITEM_TYPE_NAME = "DataItem"; private static final String ERROR_TYPE_NAME = "Error"; private Utils() { } public static Object parseSchemaFile(BString schemaPath) { BObject schema = ValueCreator.createObjectValue(getModule(), SCHEMA_TYPE_NAME); try { Schema nativeSchema = Copybook.parse(schemaPath.getValue()); if (!nativeSchema.getErrors().isEmpty()) { return handleParsingError(nativeSchema); } schema.addNativeData(NATIVE_VALUE, nativeSchema); return schema; } catch (IOException e) { return createError(e.getMessage()); } } private static BError handleParsingError(Schema nativeSchema) { BString[] bStrings = nativeSchema.getErrors().stream().map(StringUtils::fromString).toArray(BString[]::new); BArray errors = ValueCreator.createArrayValue(bStrings); BMap<BString, Object> errorDetail = ValueCreator.createMapValue(); errorDetail.put(StringUtils.fromString("parser-errors"), errors); return createError("Error while parsing the Copybook schema.", errorDetail); } private static BError createError(String message, BMap<BString, Object> errorDetail) { return ErrorCreator.createError(getModule(), ERROR_TYPE_NAME, StringUtils.fromString(message), null, errorDetail); } private static BError createError(String message) { return createError(message, null); } public static int getLevel(BObject bObject) {
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. 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 io.ballerina.lib.copybook.runtime.converter; public final class Utils { private static final String NATIVE_VALUE = "native-value"; private static final String TO_RECORD_METHOD_NAME = "toRecord"; private static final String NODE_TYPE_NAME = "Node"; private static final String SCHEMA_TYPE_NAME = "Schema"; private static final String GROUP_ITEM_TYPE_NAME = "GroupItem"; private static final String DATA_ITEM_TYPE_NAME = "DataItem"; private static final String ERROR_TYPE_NAME = "Error"; private Utils() { } public static Object parseSchemaFile(BString schemaPath) { BObject schema = ValueCreator.createObjectValue(getModule(), SCHEMA_TYPE_NAME); try { Schema nativeSchema = Copybook.parse(schemaPath.getValue()); if (!nativeSchema.getErrors().isEmpty()) { return handleParsingError(nativeSchema); } schema.addNativeData(NATIVE_VALUE, nativeSchema); return schema; } catch (IOException e) { return createError(e.getMessage()); } } private static BError handleParsingError(Schema nativeSchema) { BString[] bStrings = nativeSchema.getErrors().stream().map(StringUtils::fromString).toArray(BString[]::new); BArray errors = ValueCreator.createArrayValue(bStrings); BMap<BString, Object> errorDetail = ValueCreator.createMapValue(); errorDetail.put(StringUtils.fromString("parser-errors"), errors); return createError("Error while parsing the Copybook schema.", errorDetail); } private static BError createError(String message, BMap<BString, Object> errorDetail) { return ErrorCreator.createError(getModule(), ERROR_TYPE_NAME, StringUtils.fromString(message), null, errorDetail); } private static BError createError(String message) { return createError(message, null); } public static int getLevel(BObject bObject) {
CopybookNode copybookNode = (CopybookNode) bObject.getNativeData(NATIVE_VALUE);
1
2023-10-24 04:51:53+00:00
4k
ballerina-platform/copybook-tools
copybook-cli/src/main/java/io/ballerina/tools/copybook/cmd/CopybookCmd.java
[ { "identifier": "Constants", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/diagnostic/Constants.java", "snippet": "public class Constants {\n\n public static final String MESSAGE_FOR_INVALID_FILE_EXTENSION = \"File \\\"%s\\\" is invalid. Copybook tool support\" +\n \" onl...
import io.ballerina.cli.BLauncherCmd; import io.ballerina.tools.copybook.diagnostic.Constants; import io.ballerina.tools.copybook.diagnostic.DiagnosticMessages; import io.ballerina.tools.copybook.exception.CmdException; import io.ballerina.tools.copybook.exception.CopybookTypeGenerationException; import io.ballerina.tools.copybook.generator.CodeGenerator; import org.ballerinalang.formatter.core.FormatterException; import picocli.CommandLine; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import static io.ballerina.tools.copybook.generator.GeneratorConstants.COBOL_EXTENSION; import static io.ballerina.tools.copybook.generator.GeneratorConstants.COPYBOOK_EXTENSION;
2,581
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. 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 io.ballerina.tools.copybook.cmd; @CommandLine.Command( name = "copybook", description = "Generates Ballerina record types for copybooks definition" ) public class CopybookCmd implements BLauncherCmd { private static final String CMD_NAME = "copybook"; private final PrintStream outStream; private final boolean exitWhenFinish; private Path executionPath = Paths.get(System.getProperty("user.dir")); @CommandLine.Option(names = {"-h", "--help"}, hidden = true) private boolean helpFlag; @CommandLine.Option(names = {"-i", "--input"}, description = "File path to the Copybook definition file") private boolean inputPathFlag; @CommandLine.Option(names = {"-o", "--output"}, description = "Directory to store the generated Ballerina record types") private String outputPath; @CommandLine.Parameters private List<String> argList; public CopybookCmd() { this(System.err, Paths.get(System.getProperty("user.dir")), true); } public CopybookCmd(PrintStream outStream, Path executionDir, boolean exitWhenFinish) { this.outStream = outStream; this.executionPath = executionDir; this.exitWhenFinish = exitWhenFinish; } private static void exitError(boolean exit) { if (exit) { Runtime.getRuntime().exit(1); } } @Override public void execute() { try { if (helpFlag) { printLongDesc(new StringBuilder()); outStream.flush(); exitError(this.exitWhenFinish); return; } validateInputFlags(); executeOperation(); } catch (CmdException | CopybookTypeGenerationException | FormatterException | IOException e) { outStream.println(e.getMessage()); exitError(this.exitWhenFinish); } } private void validateInputFlags() throws CmdException, IOException { if (inputPathFlag) { if (argList == null) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_100, null); } } else { getCommandUsageInfo(); exitError(this.exitWhenFinish); return; } String filePath = argList.get(0); if (!validInputFileExtension(filePath)) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, String.format(Constants.MESSAGE_FOR_INVALID_FILE_EXTENSION, filePath)); } } private void executeOperation() throws CopybookTypeGenerationException, CmdException, FormatterException, IOException { String filePath = argList.get(0); generateType(filePath); } private void generateType(String filePath) throws CmdException, CopybookTypeGenerationException, FormatterException, IOException { final File copybookFile = new File(filePath); if (!copybookFile.exists()) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, String.format(Constants.MESSAGE_FOR_INVALID_COPYBOOK_PATH, filePath)); } if (!copybookFile.canRead()) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, String.format(Constants.MESSAGE_CAN_NOT_READ_COPYBOOK_FILE, filePath)); } Path copybookFilePath = null; try { copybookFilePath = Paths.get(copybookFile.getCanonicalPath()); } catch (IOException e) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.toString()); } CodeGenerator.generate(copybookFilePath, getTargetOutputPath(), outStream); } private Path getTargetOutputPath() { Path targetOutputPath = executionPath; if (this.outputPath != null) { if (Paths.get(outputPath).isAbsolute()) { targetOutputPath = Paths.get(outputPath); } else { targetOutputPath = Paths.get(targetOutputPath.toString(), outputPath); } } return targetOutputPath; } private boolean validInputFileExtension(String filePath) {
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. 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 io.ballerina.tools.copybook.cmd; @CommandLine.Command( name = "copybook", description = "Generates Ballerina record types for copybooks definition" ) public class CopybookCmd implements BLauncherCmd { private static final String CMD_NAME = "copybook"; private final PrintStream outStream; private final boolean exitWhenFinish; private Path executionPath = Paths.get(System.getProperty("user.dir")); @CommandLine.Option(names = {"-h", "--help"}, hidden = true) private boolean helpFlag; @CommandLine.Option(names = {"-i", "--input"}, description = "File path to the Copybook definition file") private boolean inputPathFlag; @CommandLine.Option(names = {"-o", "--output"}, description = "Directory to store the generated Ballerina record types") private String outputPath; @CommandLine.Parameters private List<String> argList; public CopybookCmd() { this(System.err, Paths.get(System.getProperty("user.dir")), true); } public CopybookCmd(PrintStream outStream, Path executionDir, boolean exitWhenFinish) { this.outStream = outStream; this.executionPath = executionDir; this.exitWhenFinish = exitWhenFinish; } private static void exitError(boolean exit) { if (exit) { Runtime.getRuntime().exit(1); } } @Override public void execute() { try { if (helpFlag) { printLongDesc(new StringBuilder()); outStream.flush(); exitError(this.exitWhenFinish); return; } validateInputFlags(); executeOperation(); } catch (CmdException | CopybookTypeGenerationException | FormatterException | IOException e) { outStream.println(e.getMessage()); exitError(this.exitWhenFinish); } } private void validateInputFlags() throws CmdException, IOException { if (inputPathFlag) { if (argList == null) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_100, null); } } else { getCommandUsageInfo(); exitError(this.exitWhenFinish); return; } String filePath = argList.get(0); if (!validInputFileExtension(filePath)) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, String.format(Constants.MESSAGE_FOR_INVALID_FILE_EXTENSION, filePath)); } } private void executeOperation() throws CopybookTypeGenerationException, CmdException, FormatterException, IOException { String filePath = argList.get(0); generateType(filePath); } private void generateType(String filePath) throws CmdException, CopybookTypeGenerationException, FormatterException, IOException { final File copybookFile = new File(filePath); if (!copybookFile.exists()) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, String.format(Constants.MESSAGE_FOR_INVALID_COPYBOOK_PATH, filePath)); } if (!copybookFile.canRead()) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, String.format(Constants.MESSAGE_CAN_NOT_READ_COPYBOOK_FILE, filePath)); } Path copybookFilePath = null; try { copybookFilePath = Paths.get(copybookFile.getCanonicalPath()); } catch (IOException e) { throw new CmdException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.toString()); } CodeGenerator.generate(copybookFilePath, getTargetOutputPath(), outStream); } private Path getTargetOutputPath() { Path targetOutputPath = executionPath; if (this.outputPath != null) { if (Paths.get(outputPath).isAbsolute()) { targetOutputPath = Paths.get(outputPath); } else { targetOutputPath = Paths.get(targetOutputPath.toString(), outputPath); } } return targetOutputPath; } private boolean validInputFileExtension(String filePath) {
return filePath.endsWith(COPYBOOK_EXTENSION) || filePath.endsWith(COBOL_EXTENSION);
6
2023-10-24 05:00:08+00:00
4k
zhaoeryu/eu-backend
eu-quartz/src/main/java/cn/eu/quartz/job/AbstractQuartzJob.java
[ { "identifier": "SpringContextHolder", "path": "eu-common-core/src/main/java/cn/eu/common/utils/SpringContextHolder.java", "snippet": "public class SpringContextHolder implements ApplicationContextAware {\n private static ApplicationContext applicationContext;\n\n @Override\n public void setApp...
import cn.eu.common.utils.SpringContextHolder; import cn.eu.message.enums.MailSendType; import cn.eu.message.handler.dispatcher.MessageDispatcher; import cn.eu.message.model.Mail; import cn.eu.quartz.QuartzConstants; import cn.eu.quartz.domain.QuartzJob; import cn.eu.quartz.domain.QuartzJobLog; import cn.eu.quartz.enums.QuartzJobStatus; import cn.eu.quartz.service.IQuartzJobLogService; import cn.eu.quartz.service.IQuartzJobService; import cn.hutool.core.exceptions.ExceptionUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import lombok.extern.slf4j.Slf4j; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.scheduling.quartz.QuartzJobBean; import org.springframework.util.Assert; import java.time.Duration; import java.time.LocalDateTime;
2,943
package cn.eu.quartz.job; /** * @author zhaoeryu * @since 2023/6/13 */ @Slf4j public abstract class AbstractQuartzJob extends QuartzJobBean { private static final ThreadLocal<LocalDateTime> THREAD_LOCAL = new ThreadLocal<>(); @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { // public void execute(JobExecutionContext context) throws JobExecutionException { QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzConstants.JOB_DATA_KEY); log.info("--------------------------------------"); log.info("[{}]任务开始执行", quartzJob.getJobName()); try { before(context, quartzJob); doExecute(context, quartzJob); after(context, quartzJob, null); } catch (Exception e) { log.error("任务执行异常: " + e.getMessage(), e); after(context, quartzJob, e); } log.info("[{}]任务执行结束", quartzJob.getJobName()); } protected void before(JobExecutionContext context, QuartzJob quartzJob) { THREAD_LOCAL.set(LocalDateTime.now()); } protected void after(JobExecutionContext context, QuartzJob quartzJob, Exception e) { LocalDateTime startTime = THREAD_LOCAL.get(); THREAD_LOCAL.remove(); LocalDateTime endTime = LocalDateTime.now(); long execMs = Duration.between(startTime, endTime).toMillis(); log.info("任务名称 = [{}],任务组名 = [{}],执行耗时 = [{}]毫秒", quartzJob.getJobName(), quartzJob.getJobGroup(), execMs); IQuartzJobService quartzJobService = SpringContextHolder.getBean(IQuartzJobService.class); QuartzJobLog quartzJobLog = new QuartzJobLog(); quartzJobLog.setJobId(quartzJob.getId()); quartzJobLog.setJobName(quartzJob.getJobName()); quartzJobLog.setSpringBeanName(quartzJob.getSpringBeanName()); quartzJobLog.setMethodName(quartzJob.getMethodName()); quartzJobLog.setMethodParams(quartzJob.getMethodParams()); quartzJobLog.setSuccess(e == null); if (e != null) { quartzJobLog.setExceptionMessage(e.getMessage()); quartzJobLog.setExceptionDetail(ExceptionUtil.stacktraceToString(e)); // 如果失败了需要暂停 if (quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()) { quartzJob.setStatus(QuartzJobStatus.PAUSE.getValue()); quartzJobService.pauseOrResume(quartzJob); } // 如果配置了邮箱,任务失败发送邮件 if (StrUtil.isNotBlank(quartzJob.getAlarmEmail())) { try { // send email MessageDispatcher dispatcher = SpringContextHolder.getBean(MessageDispatcher.class); Mail mail = new Mail(); mail.setTo(quartzJob.getAlarmEmail()); mail.setSubject("任务执行失败 - [" + quartzJob.getJobName() + "]"); mail.setContent(quartzJobLog.getExceptionDetail()); mail.setSendType(MailSendType.TEXT); dispatcher.dispatch(mail); } catch (Exception emailEx) { log.error("发送邮件失败:" + emailEx.getMessage(), emailEx); } } } quartzJobLog.setStartTime(startTime); quartzJobLog.setEndTime(endTime); quartzJobLog.setExecTime(execMs); // save log to database
package cn.eu.quartz.job; /** * @author zhaoeryu * @since 2023/6/13 */ @Slf4j public abstract class AbstractQuartzJob extends QuartzJobBean { private static final ThreadLocal<LocalDateTime> THREAD_LOCAL = new ThreadLocal<>(); @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { // public void execute(JobExecutionContext context) throws JobExecutionException { QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzConstants.JOB_DATA_KEY); log.info("--------------------------------------"); log.info("[{}]任务开始执行", quartzJob.getJobName()); try { before(context, quartzJob); doExecute(context, quartzJob); after(context, quartzJob, null); } catch (Exception e) { log.error("任务执行异常: " + e.getMessage(), e); after(context, quartzJob, e); } log.info("[{}]任务执行结束", quartzJob.getJobName()); } protected void before(JobExecutionContext context, QuartzJob quartzJob) { THREAD_LOCAL.set(LocalDateTime.now()); } protected void after(JobExecutionContext context, QuartzJob quartzJob, Exception e) { LocalDateTime startTime = THREAD_LOCAL.get(); THREAD_LOCAL.remove(); LocalDateTime endTime = LocalDateTime.now(); long execMs = Duration.between(startTime, endTime).toMillis(); log.info("任务名称 = [{}],任务组名 = [{}],执行耗时 = [{}]毫秒", quartzJob.getJobName(), quartzJob.getJobGroup(), execMs); IQuartzJobService quartzJobService = SpringContextHolder.getBean(IQuartzJobService.class); QuartzJobLog quartzJobLog = new QuartzJobLog(); quartzJobLog.setJobId(quartzJob.getId()); quartzJobLog.setJobName(quartzJob.getJobName()); quartzJobLog.setSpringBeanName(quartzJob.getSpringBeanName()); quartzJobLog.setMethodName(quartzJob.getMethodName()); quartzJobLog.setMethodParams(quartzJob.getMethodParams()); quartzJobLog.setSuccess(e == null); if (e != null) { quartzJobLog.setExceptionMessage(e.getMessage()); quartzJobLog.setExceptionDetail(ExceptionUtil.stacktraceToString(e)); // 如果失败了需要暂停 if (quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()) { quartzJob.setStatus(QuartzJobStatus.PAUSE.getValue()); quartzJobService.pauseOrResume(quartzJob); } // 如果配置了邮箱,任务失败发送邮件 if (StrUtil.isNotBlank(quartzJob.getAlarmEmail())) { try { // send email MessageDispatcher dispatcher = SpringContextHolder.getBean(MessageDispatcher.class); Mail mail = new Mail(); mail.setTo(quartzJob.getAlarmEmail()); mail.setSubject("任务执行失败 - [" + quartzJob.getJobName() + "]"); mail.setContent(quartzJobLog.getExceptionDetail()); mail.setSendType(MailSendType.TEXT); dispatcher.dispatch(mail); } catch (Exception emailEx) { log.error("发送邮件失败:" + emailEx.getMessage(), emailEx); } } } quartzJobLog.setStartTime(startTime); quartzJobLog.setEndTime(endTime); quartzJobLog.setExecTime(execMs); // save log to database
IQuartzJobLogService quartzJobLogService = SpringContextHolder.getBean(IQuartzJobLogService.class);
8
2023-10-20 07:08:37+00:00
4k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/common/block/blockClass/Casings/BlockNuclearReactor.java
[ { "identifier": "NuclearReactorBlock", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/block/BasicBlocks.java", "snippet": "public static Block NuclearReactorBlock = new BlockNuclearReactor(\"nuclear\", \"Mega Nuclear Reactor\");" }, { "identifier": "initMetaItemStack", "path": "...
import static com.Nxer.TwistSpaceTechnology.common.block.BasicBlocks.NuclearReactorBlock; import static com.Nxer.TwistSpaceTechnology.util.MetaItemStackUtils.initMetaItemStack; import static com.Nxer.TwistSpaceTechnology.util.TextHandler.texter; import java.util.HashSet; import java.util.List; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import com.Nxer.TwistSpaceTechnology.client.GTCMCreativeTabs; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockBase01; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.BlockStaticDataClientOnly; import com.Nxer.TwistSpaceTechnology.common.block.blockClass.ItemBlockBase01; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
2,974
package com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings; public class BlockNuclearReactor extends BlockBase01 { public BlockNuclearReactor(String unlocalizedName, String localName) { this.setUnlocalizedName(unlocalizedName); texter(localName, unlocalizedName + ".name"); this.setHardness(9.0F); this.setResistance(5.0F); this.setHarvestLevel("wrench", 1); this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab); NuclearReactorBlockSet.add(0); } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return meta < BlockStaticDataClientOnly.iconsNuclearReactor.size() ? BlockStaticDataClientOnly.iconsNuclearReactor.get(meta) : BlockStaticDataClientOnly.iconsNuclearReactor.get(0); } public static class innerItemBlock extends ItemBlockBase01 { public innerItemBlock(Block aBlock) { super(aBlock); } } public static final Set<Integer> NuclearReactorBlockSet = new HashSet<>(); public static ItemStack NuclearReactorBlockMeta(String i18nName, int meta) {
package com.Nxer.TwistSpaceTechnology.common.block.blockClass.Casings; public class BlockNuclearReactor extends BlockBase01 { public BlockNuclearReactor(String unlocalizedName, String localName) { this.setUnlocalizedName(unlocalizedName); texter(localName, unlocalizedName + ".name"); this.setHardness(9.0F); this.setResistance(5.0F); this.setHarvestLevel("wrench", 1); this.setCreativeTab(GTCMCreativeTabs.tabGTCMGeneralTab); NuclearReactorBlockSet.add(0); } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int meta) { return meta < BlockStaticDataClientOnly.iconsNuclearReactor.size() ? BlockStaticDataClientOnly.iconsNuclearReactor.get(meta) : BlockStaticDataClientOnly.iconsNuclearReactor.get(0); } public static class innerItemBlock extends ItemBlockBase01 { public innerItemBlock(Block aBlock) { super(aBlock); } } public static final Set<Integer> NuclearReactorBlockSet = new HashSet<>(); public static ItemStack NuclearReactorBlockMeta(String i18nName, int meta) {
return initMetaItemStack(i18nName, meta, NuclearReactorBlock, NuclearReactorBlockSet);
1
2023-10-16 09:57:15+00:00
4k
wyjsonGo/GoRouter
module_common/src/main/java/com/wyjson/module_common/route/service/PretreatmentServiceImpl.java
[ { "identifier": "UserSignInActivityGoRouter", "path": "module_common/src/main/java/com/wyjson/router/helper/module_user/group_user/UserSignInActivityGoRouter.java", "snippet": "public class UserSignInActivityGoRouter {\n public static String getPath() {\n return \"/user/sign_in/activity\";\n ...
import android.content.Context; import android.content.Intent; import com.wyjson.router.annotation.Service; import com.wyjson.router.helper.module_user.group_user.UserSignInActivityGoRouter; import com.wyjson.router.interfaces.IPretreatmentService; import com.wyjson.router.model.Card;
3,233
package com.wyjson.module_common.route.service; @Service(remark = "预处理服务") public class PretreatmentServiceImpl implements IPretreatmentService { @Override public void init() { } @Override
package com.wyjson.module_common.route.service; @Service(remark = "预处理服务") public class PretreatmentServiceImpl implements IPretreatmentService { @Override public void init() { } @Override
public boolean onPretreatment(Context context, Card card) {
2
2023-10-18 13:52:07+00:00
4k
trpc-group/trpc-java
trpc-proto/trpc-proto-standard/src/test/java/com/tencent/trpc/proto/standard/clustertest/ClientFilterTest.java
[ { "identifier": "Filter", "path": "trpc-core/src/main/java/com/tencent/trpc/core/filter/spi/Filter.java", "snippet": "@Extensible\npublic interface Filter extends Ordered {\n\n /**\n * <pre> Note: For ClientFilter, the framework has copied the contents of RpcContext into Request#attachments.\n ...
import static org.junit.Assert.assertEquals; import com.tencent.trpc.core.filter.spi.Filter; import com.tencent.trpc.core.rpc.CallInfo; import com.tencent.trpc.core.rpc.Invoker; import com.tencent.trpc.core.rpc.Request; import com.tencent.trpc.core.rpc.Response; import java.util.concurrent.CompletionStage; import org.junit.Assert;
3,061
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.proto.standard.clustertest; public class ClientFilterTest implements Filter { @Override
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.proto.standard.clustertest; public class ClientFilterTest implements Filter { @Override
public CompletionStage<Response> filter(Invoker<?> filterChain, Request req) {
3
2023-10-19 10:54:11+00:00
4k
freedom-introvert/YouTubeSendCommentAntiFraud
YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/ToBeCheckedCommentsAdapter.java
[ { "identifier": "ToBeCheckedComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/ToBeCheckedComment.java", "snippet": "public class ToBeCheckedComment extends Comment{\r\n public static final int COMMENT_SECTION_TYPE_VIDEO = 1;\r\n\r\n public St...
import android.app.Activity; import android.app.AlertDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.DocumentsContract; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.documentfile.provider.DocumentFile; import androidx.recyclerview.widget.RecyclerView; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.List; import java.util.Objects; import icu.freedomintrovert.YTSendCommAntiFraud.comment.ToBeCheckedComment; import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB; import icu.freedomintrovert.YTSendCommAntiFraud.view.VoidDialogInterfaceOnClickListener;
2,021
package icu.freedomintrovert.YTSendCommAntiFraud; public class ToBeCheckedCommentsAdapter extends RecyclerView.Adapter<ToBeCheckedCommentsAdapter.ViewHolder> { StatisticsDB statisticsDB; Activity context;
package icu.freedomintrovert.YTSendCommAntiFraud; public class ToBeCheckedCommentsAdapter extends RecyclerView.Adapter<ToBeCheckedCommentsAdapter.ViewHolder> { StatisticsDB statisticsDB; Activity context;
List<ToBeCheckedComment> commentList;
0
2023-10-15 01:18:28+00:00
4k
New-Barams/This-Year-Ajaja-BE
src/test/java/com/newbarams/ajaja/module/feedback/application/LoadFeedbackInfoServiceTest.java
[ { "identifier": "MockTestSupport", "path": "src/test/java/com/newbarams/ajaja/common/support/MockTestSupport.java", "snippet": "@ExtendWith(MockitoExtension.class)\npublic abstract class MockTestSupport extends MonkeySupport {\n}" }, { "identifier": "AjajaException", "path": "src/main/java/c...
import static org.mockito.BDDMockito.*; import java.util.List; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import com.newbarams.ajaja.common.support.MockTestSupport; import com.newbarams.ajaja.global.exception.AjajaException; import com.newbarams.ajaja.module.feedback.application.model.FeedbackPeriod; import com.newbarams.ajaja.module.feedback.application.model.PlanFeedbackInfo; import com.newbarams.ajaja.module.feedback.domain.FeedbackQueryRepository; import com.newbarams.ajaja.module.feedback.dto.FeedbackResponse; import com.newbarams.ajaja.module.feedback.infra.model.FeedbackInfo; import com.newbarams.ajaja.module.feedback.mapper.FeedbackMapper; import com.newbarams.ajaja.module.plan.application.LoadPlanService;
1,840
package com.newbarams.ajaja.module.feedback.application; class LoadFeedbackInfoServiceTest extends MockTestSupport { @InjectMocks private LoadFeedbackInfoService loadFeedbackInfoService; @Mock private LoadPlanService loadPlanService; @Mock private FeedbackQueryRepository feedbackQueryRepository; @Mock private FeedbackMapper mapper; private List<FeedbackInfo> feedbacks; private PlanFeedbackInfo planFeedbackInfo;
package com.newbarams.ajaja.module.feedback.application; class LoadFeedbackInfoServiceTest extends MockTestSupport { @InjectMocks private LoadFeedbackInfoService loadFeedbackInfoService; @Mock private LoadPlanService loadPlanService; @Mock private FeedbackQueryRepository feedbackQueryRepository; @Mock private FeedbackMapper mapper; private List<FeedbackInfo> feedbacks; private PlanFeedbackInfo planFeedbackInfo;
private FeedbackResponse.FeedbackInfo feedbackInfo;
3
2023-10-23 07:24:17+00:00
4k
eclipse-jgit/jgit
org.eclipse.jgit.junit/src/org/eclipse/jgit/junit/time/MonotonicFakeClock.java
[ { "identifier": "MonotonicClock", "path": "org.eclipse.jgit/src/org/eclipse/jgit/util/time/MonotonicClock.java", "snippet": "public interface MonotonicClock {\n\t/**\n\t * Obtain a timestamp close to \"now\".\n\t * <p>\n\t * Proposed times are close to \"now\", but may not yet be certainly in the\n\t * ...
import org.eclipse.jgit.util.time.ProposedTimestamp; import java.time.Duration; import java.util.concurrent.TimeUnit; import org.eclipse.jgit.util.time.MonotonicClock;
1,676
/* * Copyright (C) 2016, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.junit.time; /** * Fake {@link org.eclipse.jgit.util.time.MonotonicClock} for testing code that * uses Clock. * * @since 4.6 */ public class MonotonicFakeClock implements MonotonicClock { private long now = TimeUnit.SECONDS.toMicros(42); /** * Advance the time returned by future calls to {@link #propose()}. * * @param add * amount of time to add; must be {@code > 0}. * @param unit * unit of {@code add}. */ public void tick(long add, TimeUnit unit) { if (add <= 0) { throw new IllegalArgumentException(); } now += unit.toMillis(add); } @Override
/* * Copyright (C) 2016, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.junit.time; /** * Fake {@link org.eclipse.jgit.util.time.MonotonicClock} for testing code that * uses Clock. * * @since 4.6 */ public class MonotonicFakeClock implements MonotonicClock { private long now = TimeUnit.SECONDS.toMicros(42); /** * Advance the time returned by future calls to {@link #propose()}. * * @param add * amount of time to add; must be {@code > 0}. * @param unit * unit of {@code add}. */ public void tick(long add, TimeUnit unit) { if (add <= 0) { throw new IllegalArgumentException(); } now += unit.toMillis(add); } @Override
public ProposedTimestamp propose() {
1
2023-10-20 15:09:17+00:00
4k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/client/model/CatfishModel.java
[ { "identifier": "Naturalist", "path": "common/src/main/java/com/starfish_studios/naturalist/Naturalist.java", "snippet": "public class Naturalist {\n public static final String MOD_ID = \"naturalist\";\n public static final CreativeModeTab TAB = CommonPlatformHelper.registerCreativeModeTab(new Res...
import com.starfish_studios.naturalist.Naturalist; import com.starfish_studios.naturalist.common.entity.Catfish; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.resources.ResourceLocation; import software.bernie.geckolib3.model.AnimatedGeoModel;
2,567
package com.starfish_studios.naturalist.client.model; @Environment(EnvType.CLIENT) public class CatfishModel extends AnimatedGeoModel<Catfish> { @Override public ResourceLocation getModelResource(Catfish catfish) {
package com.starfish_studios.naturalist.client.model; @Environment(EnvType.CLIENT) public class CatfishModel extends AnimatedGeoModel<Catfish> { @Override public ResourceLocation getModelResource(Catfish catfish) {
return new ResourceLocation(Naturalist.MOD_ID, "geo/catfish.geo.json");
0
2023-10-16 21:54:32+00:00
4k
instana/otel-dc
host/src/main/java/com/instana/dc/host/impl/SimpHostUtil.java
[ { "identifier": "SimpleQueryResult", "path": "internal/otel-dc/src/main/java/com/instana/dc/SimpleQueryResult.java", "snippet": "public class SimpleQueryResult {\n private final Number value;\n private String key;\n private final Map<String, Object> attributes = new HashMap<>();\n\n public S...
import com.instana.dc.SimpleQueryResult; import com.instana.dc.host.HostDcUtil; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern;
2,492
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class SimpHostUtil { private static final Logger logger = Logger.getLogger(SimpHostUtil.class.getName()); public static class CpuTime { private long user, nice, system, idle, iowait, irq, softirq; public long getUser() { return user; } public void setUser(long user) { this.user = user; } public long getNice() { return nice; } public void setNice(long nice) { this.nice = nice; } public long getSystem() { return system; } public void setSystem(long system) { this.system = system; } public long getIdle() { return idle; } public void setIdle(long idle) { this.idle = idle; } public long getIowait() { return iowait; } public void setIowait(long iowait) { this.iowait = iowait; } public long getIrq() { return irq; } public void setIrq(long irq) { this.irq = irq; } public long getSoftirq() { return softirq; } public void setSoftirq(long softirq) { this.softirq = softirq; } @Override public String toString() { return "CpuTime{" + "user=" + user + ", nice=" + nice + ", system=" + system + ", idle=" + idle + ", iowait=" + iowait + ", irq=" + irq + ", softirq=" + softirq + '}'; } } public static CpuTime getCpuTime() throws IOException {
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class SimpHostUtil { private static final Logger logger = Logger.getLogger(SimpHostUtil.class.getName()); public static class CpuTime { private long user, nice, system, idle, iowait, irq, softirq; public long getUser() { return user; } public void setUser(long user) { this.user = user; } public long getNice() { return nice; } public void setNice(long nice) { this.nice = nice; } public long getSystem() { return system; } public void setSystem(long system) { this.system = system; } public long getIdle() { return idle; } public void setIdle(long idle) { this.idle = idle; } public long getIowait() { return iowait; } public void setIowait(long iowait) { this.iowait = iowait; } public long getIrq() { return irq; } public void setIrq(long irq) { this.irq = irq; } public long getSoftirq() { return softirq; } public void setSoftirq(long softirq) { this.softirq = softirq; } @Override public String toString() { return "CpuTime{" + "user=" + user + ", nice=" + nice + ", system=" + system + ", idle=" + idle + ", iowait=" + iowait + ", irq=" + irq + ", softirq=" + softirq + '}'; } } public static CpuTime getCpuTime() throws IOException {
String line = HostDcUtil.readFileTextLine("/proc/stat");
1
2023-10-23 01:16:38+00:00
4k
quarkiverse/quarkus-antivirus
deployment/src/main/java/io/quarkiverse/antivirus/deployment/AntivirusProcessor.java
[ { "identifier": "Antivirus", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/Antivirus.java", "snippet": "@ApplicationScoped\n@JBossLog\npublic class Antivirus {\n\n @Inject\n private Instance<AntivirusEngine> engineInstances;\n\n /**\n * Perform virus scan and throw excepti...
import io.quarkiverse.antivirus.runtime.Antivirus; import io.quarkiverse.antivirus.runtime.ClamAVEngine; import io.quarkiverse.antivirus.runtime.ClamAVHealthCheck; import io.quarkiverse.antivirus.runtime.VirusTotalEngine; import io.quarkus.arc.deployment.AdditionalBeanBuildItem; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.FeatureBuildItem;
2,687
package io.quarkiverse.antivirus.deployment; /** * Main processor for the Antivirus extension. */ class AntivirusProcessor { private static final String FEATURE = "antivirus"; @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem(FEATURE); } @BuildStep void registerBeans(BuildProducer<AdditionalBeanBuildItem> beans, ClamAVBuildConfig buildConfig) { beans.produce(AdditionalBeanBuildItem.builder().setUnremovable() .addBeanClasses(ClamAVEngine.class)
package io.quarkiverse.antivirus.deployment; /** * Main processor for the Antivirus extension. */ class AntivirusProcessor { private static final String FEATURE = "antivirus"; @BuildStep FeatureBuildItem feature() { return new FeatureBuildItem(FEATURE); } @BuildStep void registerBeans(BuildProducer<AdditionalBeanBuildItem> beans, ClamAVBuildConfig buildConfig) { beans.produce(AdditionalBeanBuildItem.builder().setUnremovable() .addBeanClasses(ClamAVEngine.class)
.addBeanClasses(VirusTotalEngine.class)
3
2023-10-22 22:33:05+00:00
4k
A1anSong/jd_unidbg
unidbg-ios/src/main/java/com/github/unidbg/ios/FixupChains.java
[ { "identifier": "Emulator", "path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java", "snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageA...
import com.github.unidbg.Emulator; import com.github.unidbg.Symbol; import com.github.unidbg.hook.HookListener; import com.sun.jna.Pointer; import io.kaitai.struct.ByteBufferKaitaiStream; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.nio.charset.StandardCharsets; import java.util.List;
1,747
package com.github.unidbg.ios; final class FixupChains { private static final Log log = LogFactory.getLog(FixupChains.class); // values for dyld_chained_fixups_header.imports_format static final int DYLD_CHAINED_IMPORT = 1; static final int DYLD_CHAINED_IMPORT_ADDEND = 2; static final int DYLD_CHAINED_IMPORT_ADDEND64 = 3; static final int DYLD_CHAINED_PTR_START_NONE = 0xffff; // used in page_start[] to denote a page with no fixups static final int DYLD_CHAINED_PTR_START_MULTI = 0x8000; // used in page_start[] to denote a page which has multiple starts static final int DYLD_CHAINED_PTR_START_LAST = 0x8000; // used in chain_starts[] to denote last start in list for page // values for dyld_chained_starts_in_segment.pointer_format static final int DYLD_CHAINED_PTR_ARM64E = 1; // stride 8, unauth target is vmaddr static final int DYLD_CHAINED_PTR_64 = 2; // target is vmaddr static final int DYLD_CHAINED_PTR_32 = 3; static final int DYLD_CHAINED_PTR_32_CACHE = 4; static final int DYLD_CHAINED_PTR_32_FIRMWARE = 5; static final int DYLD_CHAINED_PTR_64_OFFSET = 6; // target is vm offset static final int DYLD_CHAINED_PTR_ARM64E_OFFSET = 7; // stride 4, unauth target is vm offset static final int DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8; static final int DYLD_CHAINED_PTR_ARM64E_USERLAND = 9; // stride 8, unauth target is vm offset static final int DYLD_CHAINED_PTR_ARM64E_FIRMWARE = 10; // stride 4, unauth target is vmaddr static final int DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE = 11; // stride 1, x86_64 kernel caches static final int DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12; // stride 8, unauth target is vm offset, 24-bit bind static boolean greaterThanAddOrOverflow(long addLHS, long addRHS, long b) { return (addLHS > b) || (addRHS > (b-addLHS)); } private static long signExtendedAddend(long addend) { long top8Bits = addend & 0x00007f80000L; long bottom19Bits = addend & 0x0000007ffffL; return (top8Bits << 13) | (((bottom19Bits << 37) >>> 37) & 0x00ffffffffffffffL); }
package com.github.unidbg.ios; final class FixupChains { private static final Log log = LogFactory.getLog(FixupChains.class); // values for dyld_chained_fixups_header.imports_format static final int DYLD_CHAINED_IMPORT = 1; static final int DYLD_CHAINED_IMPORT_ADDEND = 2; static final int DYLD_CHAINED_IMPORT_ADDEND64 = 3; static final int DYLD_CHAINED_PTR_START_NONE = 0xffff; // used in page_start[] to denote a page with no fixups static final int DYLD_CHAINED_PTR_START_MULTI = 0x8000; // used in page_start[] to denote a page which has multiple starts static final int DYLD_CHAINED_PTR_START_LAST = 0x8000; // used in chain_starts[] to denote last start in list for page // values for dyld_chained_starts_in_segment.pointer_format static final int DYLD_CHAINED_PTR_ARM64E = 1; // stride 8, unauth target is vmaddr static final int DYLD_CHAINED_PTR_64 = 2; // target is vmaddr static final int DYLD_CHAINED_PTR_32 = 3; static final int DYLD_CHAINED_PTR_32_CACHE = 4; static final int DYLD_CHAINED_PTR_32_FIRMWARE = 5; static final int DYLD_CHAINED_PTR_64_OFFSET = 6; // target is vm offset static final int DYLD_CHAINED_PTR_ARM64E_OFFSET = 7; // stride 4, unauth target is vm offset static final int DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8; static final int DYLD_CHAINED_PTR_ARM64E_USERLAND = 9; // stride 8, unauth target is vm offset static final int DYLD_CHAINED_PTR_ARM64E_FIRMWARE = 10; // stride 4, unauth target is vmaddr static final int DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE = 11; // stride 1, x86_64 kernel caches static final int DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12; // stride 8, unauth target is vm offset, 24-bit bind static boolean greaterThanAddOrOverflow(long addLHS, long addRHS, long b) { return (addLHS > b) || (addRHS > (b-addLHS)); } private static long signExtendedAddend(long addend) { long top8Bits = addend & 0x00007f80000L; long bottom19Bits = addend & 0x0000007ffffL; return (top8Bits << 13) | (((bottom19Bits << 37) >>> 37) & 0x00ffffffffffffffL); }
static void handleChain(Emulator<?> emulator, MachOModule mm, List<HookListener> hookListeners, int pointer_format, Pointer chain, long raw64, List<BindTarget> bindTargets, ByteBufferKaitaiStream symbolsPool) {
0
2023-10-17 06:13:28+00:00
4k
robaho/httpserver
src/test/java/robaho/net/httpserver/websockets/WebSocketResponseHandlerTest.java
[ { "identifier": "Code", "path": "src/main/java/robaho/net/httpserver/Code.java", "snippet": "public class Code {\n\n public static final int HTTP_CONTINUE = 100;\n public static final int HTTP_OK = 200;\n public static final int HTTP_CREATED = 201;\n public static final int HTTP_ACCEPTED = 202;\n p...
import static org.testng.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import robaho.net.httpserver.Code; import robaho.net.httpserver.StubHttpExchange;
2,217
package robaho.net.httpserver.websockets; /* * #%L * NanoHttpd-Websocket * %% * Copyright (C) 2012 - 2015 nanohttpd * %% * 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. Neither the name of the nanohttpd nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 HOLDER 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. * #L% */ public class WebSocketResponseHandlerTest { Headers headers; WebSocketHandler handler; HttpExchange exchange; @BeforeMethod public void setUp() { this.headers = new Headers(); this.headers.add("upgrade", "websocket"); this.headers.add("connection", "Upgrade"); this.headers.add("sec-websocket-key", "x3JJHMbDL1EzLkh9GBhXDw=="); this.headers.add("sec-websocket-protocol", "chat, superchat"); this.headers.add("sec-websocket-version", "13"); handler = new TestWebsocketHandler(); exchange = new TestHttpExchange(headers, new Headers()); } private static class TestWebsocketHandler extends WebSocketHandler { @Override protected WebSocket openWebSocket(HttpExchange exchange) { return new TestWebSocket(exchange); } private static class TestWebSocket extends WebSocket { TestWebSocket(HttpExchange exchange) { super(exchange); } protected void onClose(CloseCode code, String reason, boolean initiatedByRemote) { } @Override protected void onMessage(WebSocketFrame message) throws WebSocketException { } @Override protected void onPong(WebSocketFrame pong) throws WebSocketException { } } }
package robaho.net.httpserver.websockets; /* * #%L * NanoHttpd-Websocket * %% * Copyright (C) 2012 - 2015 nanohttpd * %% * 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. Neither the name of the nanohttpd nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * 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 HOLDER 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. * #L% */ public class WebSocketResponseHandlerTest { Headers headers; WebSocketHandler handler; HttpExchange exchange; @BeforeMethod public void setUp() { this.headers = new Headers(); this.headers.add("upgrade", "websocket"); this.headers.add("connection", "Upgrade"); this.headers.add("sec-websocket-key", "x3JJHMbDL1EzLkh9GBhXDw=="); this.headers.add("sec-websocket-protocol", "chat, superchat"); this.headers.add("sec-websocket-version", "13"); handler = new TestWebsocketHandler(); exchange = new TestHttpExchange(headers, new Headers()); } private static class TestWebsocketHandler extends WebSocketHandler { @Override protected WebSocket openWebSocket(HttpExchange exchange) { return new TestWebSocket(exchange); } private static class TestWebSocket extends WebSocket { TestWebSocket(HttpExchange exchange) { super(exchange); } protected void onClose(CloseCode code, String reason, boolean initiatedByRemote) { } @Override protected void onMessage(WebSocketFrame message) throws WebSocketException { } @Override protected void onPong(WebSocketFrame pong) throws WebSocketException { } } }
private static class TestHttpExchange extends StubHttpExchange {
1
2023-10-15 15:56:58+00:00
4k
ImCodist/funny-bfdi
src/main/java/xyz/imcodist/funnybfdi/features/BFDIHeadFeature.java
[ { "identifier": "FunnyBFDI", "path": "src/main/java/xyz/imcodist/funnybfdi/FunnyBFDI.java", "snippet": "public class FunnyBFDI implements ModInitializer {\n public static final String MOD_ID = \"funnybfdi\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n @Override\n ...
import net.minecraft.client.model.*; import net.minecraft.client.render.OverlayTexture; import net.minecraft.client.render.RenderLayer; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.feature.FeatureRenderer; import net.minecraft.client.render.entity.feature.FeatureRendererContext; import net.minecraft.client.render.entity.model.EntityModel; import net.minecraft.client.render.entity.model.ModelWithHead; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.util.Identifier; import net.minecraft.util.math.RotationAxis; import xyz.imcodist.funnybfdi.FunnyBFDI; import xyz.imcodist.funnybfdi.other.Config; import xyz.imcodist.funnybfdi.other.MouthManager;
2,304
package xyz.imcodist.funnybfdi.features; public class BFDIHeadFeature<T extends LivingEntity, M extends EntityModel<T> & ModelWithHead> extends FeatureRenderer<T, M> { private final ModelPart base; public BFDIHeadFeature(FeatureRendererContext<T, M> context) { super(context); ModelData modelData = new ModelData(); ModelPartData modelPartData = modelData.getRoot(); modelPartData.addChild("mouth", ModelPartBuilder.create().uv(0, 0).cuboid(-4.0F, -8.0F, 4.51F, 8.0F, 16.0F, 0.0F), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); TexturedModelData texturedModelData = TexturedModelData.of(modelData, 16, 16); this.base = texturedModelData.createModel().getChild("mouth"); } @Override public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { if (!Config.enabled) return; if (Config.mouthSize <= 0.0f) return; ModelPart head = getContextModel().getHead(); if (entity.isInvisible()) return; if (!head.visible) return; MouthManager.MouthState mouthState = MouthManager.getPlayerMouthState(entity.getUuid()); String mouthExpression = "normal"; if (entity.getHealth() <= 10) { // when less then half health mouthExpression = "sad"; } String mouth = "idle"; // status effects boolean hasAbsorb = false; boolean hasPoison = false; for (StatusEffectInstance effectInstance : entity.getStatusEffects()) { if (effectInstance.getEffectType().equals(StatusEffects.ABSORPTION)) { hasAbsorb = true; continue; } if (effectInstance.getEffectType().equals(StatusEffects.POISON)) { hasPoison = true; } } // absorption if (mouthExpression.equals("normal") && hasAbsorb) { mouthExpression = "normal"; mouth = "absorption"; } // is at critical hearts (shaky health bar oooo) if (entity.getHealth() <= 4) { mouthExpression = "sad"; mouth = "critical"; } if (entity.isSubmergedInWater()) { mouth = "water"; } // is talking if (mouthState != null && mouthState.talking) { String shape = mouthState.transitionMouthShape; if (!shape.equals("0")) { if (!mouth.equals("absorption") && !mouth.equals("critical") && !mouth.equals("water")) { mouth = "talk" + shape; } else { mouth = mouth + "talk"; } } else { if (mouth.equals("water")) mouth = mouth + "talkclosed"; } } else { if (hasPoison) { mouthExpression = "special"; mouth = "poison"; } } // is hurt if (entity.hurtTime > 0) { mouthExpression = "special"; mouth = "hurt"; }
package xyz.imcodist.funnybfdi.features; public class BFDIHeadFeature<T extends LivingEntity, M extends EntityModel<T> & ModelWithHead> extends FeatureRenderer<T, M> { private final ModelPart base; public BFDIHeadFeature(FeatureRendererContext<T, M> context) { super(context); ModelData modelData = new ModelData(); ModelPartData modelPartData = modelData.getRoot(); modelPartData.addChild("mouth", ModelPartBuilder.create().uv(0, 0).cuboid(-4.0F, -8.0F, 4.51F, 8.0F, 16.0F, 0.0F), ModelTransform.pivot(0.0F, 0.0F, 0.0F)); TexturedModelData texturedModelData = TexturedModelData.of(modelData, 16, 16); this.base = texturedModelData.createModel().getChild("mouth"); } @Override public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { if (!Config.enabled) return; if (Config.mouthSize <= 0.0f) return; ModelPart head = getContextModel().getHead(); if (entity.isInvisible()) return; if (!head.visible) return; MouthManager.MouthState mouthState = MouthManager.getPlayerMouthState(entity.getUuid()); String mouthExpression = "normal"; if (entity.getHealth() <= 10) { // when less then half health mouthExpression = "sad"; } String mouth = "idle"; // status effects boolean hasAbsorb = false; boolean hasPoison = false; for (StatusEffectInstance effectInstance : entity.getStatusEffects()) { if (effectInstance.getEffectType().equals(StatusEffects.ABSORPTION)) { hasAbsorb = true; continue; } if (effectInstance.getEffectType().equals(StatusEffects.POISON)) { hasPoison = true; } } // absorption if (mouthExpression.equals("normal") && hasAbsorb) { mouthExpression = "normal"; mouth = "absorption"; } // is at critical hearts (shaky health bar oooo) if (entity.getHealth() <= 4) { mouthExpression = "sad"; mouth = "critical"; } if (entity.isSubmergedInWater()) { mouth = "water"; } // is talking if (mouthState != null && mouthState.talking) { String shape = mouthState.transitionMouthShape; if (!shape.equals("0")) { if (!mouth.equals("absorption") && !mouth.equals("critical") && !mouth.equals("water")) { mouth = "talk" + shape; } else { mouth = mouth + "talk"; } } else { if (mouth.equals("water")) mouth = mouth + "talkclosed"; } } else { if (hasPoison) { mouthExpression = "special"; mouth = "poison"; } } // is hurt if (entity.hurtTime > 0) { mouthExpression = "special"; mouth = "hurt"; }
RenderLayer renderLayer = RenderLayer.getEntityTranslucent(new Identifier(FunnyBFDI.MOD_ID, "textures/mouths/" + mouthExpression + "/" + mouth + ".png"));
0
2023-10-18 00:31:52+00:00
4k
ItzGreenCat/SkyImprover
src/main/java/me/greencat/skyimprover/feature/damageSplash/DamageSplash.java
[ { "identifier": "Config", "path": "src/main/java/me/greencat/skyimprover/config/Config.java", "snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashE...
import me.greencat.skyimprover.config.Config; import me.greencat.skyimprover.event.RenderLivingEntityPreEvent; import me.greencat.skyimprover.feature.Module; import me.greencat.skyimprover.utils.TextRenderUtils; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderContext; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.entity.Entity; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.decoration.ArmorStandEntity; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.util.math.Vec3d; import java.awt.*; import java.text.DecimalFormat; import java.util.List; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
1,815
package me.greencat.skyimprover.feature.damageSplash; public class DamageSplash implements Module { private static final Pattern pattern = Pattern.compile("[✧✯]?(\\d{1,3}(?:,\\d{3})*[⚔+✧❤♞☄✷ﬗ✯]*)"); private static final Deque<RenderInformation> damages = new LinkedList<>(); private static final DecimalFormat decimalFormat = new DecimalFormat("0.00"); private static final Random random = new Random(); @Override public void registerEvent() {
package me.greencat.skyimprover.feature.damageSplash; public class DamageSplash implements Module { private static final Pattern pattern = Pattern.compile("[✧✯]?(\\d{1,3}(?:,\\d{3})*[⚔+✧❤♞☄✷ﬗ✯]*)"); private static final Deque<RenderInformation> damages = new LinkedList<>(); private static final DecimalFormat decimalFormat = new DecimalFormat("0.00"); private static final Random random = new Random(); @Override public void registerEvent() {
RenderLivingEntityPreEvent.EVENT.register(DamageSplash::onRenderEntity);
1
2023-10-19 09:19:09+00:00
4k
zilliztech/kafka-connect-milvus
src/main/java/com/milvus/io/kafka/MilvusSinkTask.java
[ { "identifier": "MilvusClientHelper", "path": "src/main/java/com/milvus/io/kafka/helper/MilvusClientHelper.java", "snippet": "public class MilvusClientHelper {\n public MilvusServiceClient createMilvusClient(MilvusSinkConnectorConfig config) {\n ConnectParam connectParam = ConnectParam.newBuil...
import com.milvus.io.kafka.helper.MilvusClientHelper; import com.milvus.io.kafka.utils.DataConverter; import com.milvus.io.kafka.utils.Utils; import com.milvus.io.kafka.utils.VersionUtil; import io.milvus.client.MilvusServiceClient; import io.milvus.grpc.CollectionSchema; import io.milvus.grpc.DescribeCollectionResponse; import io.milvus.grpc.GetLoadStateResponse; import io.milvus.grpc.LoadState; import io.milvus.param.R; import io.milvus.param.collection.DescribeCollectionParam; import io.milvus.param.collection.GetLoadStateParam; import io.milvus.param.dml.InsertParam; import org.apache.kafka.connect.sink.SinkRecord; import org.apache.kafka.connect.sink.SinkTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; import java.util.Map; import static com.milvus.io.kafka.MilvusSinkConnectorConfig.TOKEN;
2,341
package com.milvus.io.kafka; public class MilvusSinkTask extends SinkTask { private static final Logger log = LoggerFactory.getLogger(MilvusSinkTask.class); private MilvusSinkConnectorConfig config; private MilvusServiceClient myMilvusClient; private DataConverter converter; private CollectionSchema collectionSchema; @Override public String version() {
package com.milvus.io.kafka; public class MilvusSinkTask extends SinkTask { private static final Logger log = LoggerFactory.getLogger(MilvusSinkTask.class); private MilvusSinkConnectorConfig config; private MilvusServiceClient myMilvusClient; private DataConverter converter; private CollectionSchema collectionSchema; @Override public String version() {
return VersionUtil.getVersion();
3
2023-10-18 02:11:08+00:00
4k
histevehu/12306
generator/src/main/java/com/steve/train/generator/gen/EnumGenerator.java
[ { "identifier": "ConfirmOrderStatusEnum", "path": "business/src/main/java/com/steve/train/business/enums/ConfirmOrderStatusEnum.java", "snippet": "public enum ConfirmOrderStatusEnum {\n // 订单刚进系统\n INIT(\"I\", \"初始\"),\n // 订单选票中\n PENDING(\"P\", \"处理中\"),\n SUCCESS(\"S\", \"成功\"),\n F...
import cn.hutool.core.util.StrUtil; import com.steve.train.business.enums.ConfirmOrderStatusEnum; import com.steve.train.common.enums.SeatColEnum; import com.steve.train.common.enums.SeatTypeEnum; import com.steve.train.common.enums.TrainTypeEnum; import com.steve.train.member.enums.PassengerTypeEnum; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List;
2,328
package com.steve.train.generator.gen; public class EnumGenerator { static String path = "admin/src/assets/js/enums.js"; public static void main(String[] args) { // 生成的JSON枚举对象 StringBuffer bufferObject = new StringBuffer(); // 生成的JSON枚举数组 StringBuffer bufferArray = new StringBuffer(); long begin = System.currentTimeMillis(); try { toJson(PassengerTypeEnum.class, bufferObject, bufferArray); toJson(TrainTypeEnum.class, bufferObject, bufferArray); toJson(SeatTypeEnum.class, bufferObject, bufferArray); toJson(SeatColEnum.class, bufferObject, bufferArray);
package com.steve.train.generator.gen; public class EnumGenerator { static String path = "admin/src/assets/js/enums.js"; public static void main(String[] args) { // 生成的JSON枚举对象 StringBuffer bufferObject = new StringBuffer(); // 生成的JSON枚举数组 StringBuffer bufferArray = new StringBuffer(); long begin = System.currentTimeMillis(); try { toJson(PassengerTypeEnum.class, bufferObject, bufferArray); toJson(TrainTypeEnum.class, bufferObject, bufferArray); toJson(SeatTypeEnum.class, bufferObject, bufferArray); toJson(SeatColEnum.class, bufferObject, bufferArray);
toJson(ConfirmOrderStatusEnum.class, bufferObject, bufferArray);
0
2023-10-23 01:20:56+00:00
4k
aws-samples/trading-latency-benchmark
src/main/java/com/aws/trading/ExchangeClientLatencyTestHandler.java
[ { "identifier": "COIN_PAIRS", "path": "src/main/java/com/aws/trading/Config.java", "snippet": "public static final List<String> COIN_PAIRS;" }, { "identifier": "printResults", "path": "src/main/java/com/aws/trading/RoundTripLatencyTester.java", "snippet": "public static synchronized void...
import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.websocketx.*; import io.netty.util.CharsetUtil; import org.HdrHistogram.SingleWriterRecorder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.net.URI; import java.nio.charset.StandardCharsets; import java.util.Random; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import static com.aws.trading.Config.COIN_PAIRS; import static com.aws.trading.RoundTripLatencyTester.printResults;
2,330
throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } final WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { this.onTextWebSocketFrame(ctx, (TextWebSocketFrame) frame); } else if (frame instanceof PongWebSocketFrame) { } else if (frame instanceof CloseWebSocketFrame) { LOGGER.info("received CloseWebSocketFrame, closing the channel"); ch.close(); } else if (frame instanceof BinaryWebSocketFrame) { LOGGER.info(frame.content().toString()); } } private TextWebSocketFrame subscribeMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer(ExchangeProtocolImpl.SUBSCRIBE_MSG)); } private TextWebSocketFrame authMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer( ExchangeProtocolImpl.AUTH_MSG_HEADER, Integer.toString(this.apiToken).getBytes(StandardCharsets.UTF_8), ExchangeProtocolImpl.MSG_END) ); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { LOGGER.error(cause); if (!handshakeFuture.isDone()) { handshakeFuture.setFailure(cause); } ctx.close(); } public ChannelPromise getHandshakeFuture() { return handshakeFuture; } private void onTextWebSocketFrame(ChannelHandlerContext ctx, TextWebSocketFrame textFrame) throws InterruptedException { long eventReceiveTime = System.nanoTime(); ByteBuf buf = textFrame.content(); final byte[] bytes; int offset = 0; final int length = buf.readableBytes(); if (buf.hasArray()) { bytes = buf.array(); offset = buf.arrayOffset(); } else { bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); } buf.clear(); buf.release(); JSONObject parsedObject = JSON.parseObject(bytes, offset, bytes.length - offset, StandardCharsets.UTF_8); Object type = parsedObject.getString("type"); if ("BOOKED".equals(type) || type.equals("DONE")) { //LOGGER.info("eventTime: {}, received ACK: {}",eventReceiveTime, parsedObject); String clientId = parsedObject.getString("client_id"); if (type.equals("BOOKED")) { if (calculateRoundTrip(eventReceiveTime, clientId, orderSentTimeMap)) return; var pair = parsedObject.getString("instrument_code"); sendCancelOrder(ctx, clientId, pair); } else { if (calculateRoundTrip(eventReceiveTime, clientId, cancelSentTimeMap)) return; sendOrder(ctx); } if (orderResponseCount % test_size == 0) { printResults(hdrRecorderForAggregation, test_size); } } else if ("AUTHENTICATED".equals(type)) { LOGGER.info("{}", parsedObject); ctx.channel().writeAndFlush(subscribeMessage()); } else if ("SUBSCRIPTIONS".equals(type)) { LOGGER.info("{}", parsedObject); this.testStartTime = System.nanoTime(); sendOrder(ctx); } else { LOGGER.error("Unhandled object {}", parsedObject); } } private void sendCancelOrder(ChannelHandlerContext ctx, String clientId, String pair) { TextWebSocketFrame cancelOrder = protocol.createCancelOrder(pair, clientId); //LOGGER.info("Sending cancel order seq: {}, order: {}", sequence, cancelOrder.toString(StandardCharsets.UTF_8)); try { ctx.channel().write(cancelOrder, ctx.channel().voidPromise()).await(); } catch (InterruptedException e) { LOGGER.error(e); } var cancelSentTime = System.nanoTime(); //LOGGER.info("cancel sent time for clientId: {} - {}",clientId, cancelSentTime); this.cancelSentTimeMap.put(clientId, cancelSentTime); ctx.channel().flush(); orderResponseCount += 1; } private boolean calculateRoundTrip(long eventReceiveTime, String clientId, ConcurrentHashMap<String, Long> cancelSentTimeMap) { long roundTripTime; Long cancelSentTime = cancelSentTimeMap.remove(clientId); if (null == cancelSentTime || eventReceiveTime < cancelSentTime) { LOGGER.error("no order sent time found for order {}", clientId); return true; } roundTripTime = eventReceiveTime - cancelSentTime; //LOGGER.info("round trip time for client id {}: {} = {} - {}", clientId, roundTripTime, eventReceiveTime, cancelSentTime); if (roundTripTime > 0) { //LOGGER.info("recording round trip time"); hdrRecorderForAggregation.recordValue(roundTripTime); } return false; } void sendOrder(ChannelHandlerContext ch) throws InterruptedException {
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 * * 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. * * 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 com.aws.trading; public class ExchangeClientLatencyTestHandler extends ChannelInboundHandlerAdapter { private static final Logger LOGGER = LogManager.getLogger(ExchangeClientLatencyTestHandler.class); private final WebSocketClientHandshaker handshaker; private final int apiToken; private final int test_size; public final URI uri; private final ExchangeProtocol protocol; private ChannelPromise handshakeFuture; private final ConcurrentHashMap<String, Long> orderSentTimeMap; private final ConcurrentHashMap<String, Long> cancelSentTimeMap; private long orderResponseCount = 0; private final SingleWriterRecorder hdrRecorderForAggregation; private long testStartTime = 0; private final Random random = new Random(); public ExchangeClientLatencyTestHandler(ExchangeProtocol protocol, URI uri, int apiToken, int test_size) { this.uri = uri; this.protocol = protocol; var header = HttpHeaders.EMPTY_HEADERS; this.handshaker = WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, false, header, 1280000); this.apiToken = apiToken; this.orderSentTimeMap = new ConcurrentHashMap<>(test_size); this.cancelSentTimeMap = new ConcurrentHashMap<>(test_size); this.test_size = test_size; this.hdrRecorderForAggregation = new SingleWriterRecorder(Long.MAX_VALUE, 2); } @Override public void handlerAdded(final ChannelHandlerContext ctx) throws Exception { this.handshakeFuture = ctx.newPromise(); } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { LOGGER.info("channel is active, starting websocket handshaking..."); handshaker.handshake(ctx.channel()); } @Override public void channelInactive(final ChannelHandlerContext ctx) throws Exception { LOGGER.info("Websocket client disconnected"); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { final Channel ch = ctx.channel(); if (!handshaker.isHandshakeComplete()) { LOGGER.info("Websocket client is connected"); var m = (FullHttpResponse) msg; handshaker.finishHandshake(ch, m); LOGGER.info("Websocket client is authenticating for {}", this.apiToken); //success, authenticate var channel = ctx.channel(); channel.write(authMessage()); channel.flush(); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { final FullHttpResponse response = (FullHttpResponse) msg; throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } final WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { this.onTextWebSocketFrame(ctx, (TextWebSocketFrame) frame); } else if (frame instanceof PongWebSocketFrame) { } else if (frame instanceof CloseWebSocketFrame) { LOGGER.info("received CloseWebSocketFrame, closing the channel"); ch.close(); } else if (frame instanceof BinaryWebSocketFrame) { LOGGER.info(frame.content().toString()); } } private TextWebSocketFrame subscribeMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer(ExchangeProtocolImpl.SUBSCRIBE_MSG)); } private TextWebSocketFrame authMessage() { return new TextWebSocketFrame(Unpooled.wrappedBuffer( ExchangeProtocolImpl.AUTH_MSG_HEADER, Integer.toString(this.apiToken).getBytes(StandardCharsets.UTF_8), ExchangeProtocolImpl.MSG_END) ); } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception { LOGGER.error(cause); if (!handshakeFuture.isDone()) { handshakeFuture.setFailure(cause); } ctx.close(); } public ChannelPromise getHandshakeFuture() { return handshakeFuture; } private void onTextWebSocketFrame(ChannelHandlerContext ctx, TextWebSocketFrame textFrame) throws InterruptedException { long eventReceiveTime = System.nanoTime(); ByteBuf buf = textFrame.content(); final byte[] bytes; int offset = 0; final int length = buf.readableBytes(); if (buf.hasArray()) { bytes = buf.array(); offset = buf.arrayOffset(); } else { bytes = new byte[length]; buf.getBytes(buf.readerIndex(), bytes); } buf.clear(); buf.release(); JSONObject parsedObject = JSON.parseObject(bytes, offset, bytes.length - offset, StandardCharsets.UTF_8); Object type = parsedObject.getString("type"); if ("BOOKED".equals(type) || type.equals("DONE")) { //LOGGER.info("eventTime: {}, received ACK: {}",eventReceiveTime, parsedObject); String clientId = parsedObject.getString("client_id"); if (type.equals("BOOKED")) { if (calculateRoundTrip(eventReceiveTime, clientId, orderSentTimeMap)) return; var pair = parsedObject.getString("instrument_code"); sendCancelOrder(ctx, clientId, pair); } else { if (calculateRoundTrip(eventReceiveTime, clientId, cancelSentTimeMap)) return; sendOrder(ctx); } if (orderResponseCount % test_size == 0) { printResults(hdrRecorderForAggregation, test_size); } } else if ("AUTHENTICATED".equals(type)) { LOGGER.info("{}", parsedObject); ctx.channel().writeAndFlush(subscribeMessage()); } else if ("SUBSCRIPTIONS".equals(type)) { LOGGER.info("{}", parsedObject); this.testStartTime = System.nanoTime(); sendOrder(ctx); } else { LOGGER.error("Unhandled object {}", parsedObject); } } private void sendCancelOrder(ChannelHandlerContext ctx, String clientId, String pair) { TextWebSocketFrame cancelOrder = protocol.createCancelOrder(pair, clientId); //LOGGER.info("Sending cancel order seq: {}, order: {}", sequence, cancelOrder.toString(StandardCharsets.UTF_8)); try { ctx.channel().write(cancelOrder, ctx.channel().voidPromise()).await(); } catch (InterruptedException e) { LOGGER.error(e); } var cancelSentTime = System.nanoTime(); //LOGGER.info("cancel sent time for clientId: {} - {}",clientId, cancelSentTime); this.cancelSentTimeMap.put(clientId, cancelSentTime); ctx.channel().flush(); orderResponseCount += 1; } private boolean calculateRoundTrip(long eventReceiveTime, String clientId, ConcurrentHashMap<String, Long> cancelSentTimeMap) { long roundTripTime; Long cancelSentTime = cancelSentTimeMap.remove(clientId); if (null == cancelSentTime || eventReceiveTime < cancelSentTime) { LOGGER.error("no order sent time found for order {}", clientId); return true; } roundTripTime = eventReceiveTime - cancelSentTime; //LOGGER.info("round trip time for client id {}: {} = {} - {}", clientId, roundTripTime, eventReceiveTime, cancelSentTime); if (roundTripTime > 0) { //LOGGER.info("recording round trip time"); hdrRecorderForAggregation.recordValue(roundTripTime); } return false; } void sendOrder(ChannelHandlerContext ch) throws InterruptedException {
var pair = COIN_PAIRS.get(random.nextInt(COIN_PAIRS.size()));
0
2023-10-22 19:04:39+00:00
4k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/bug/BugMapper.java
[ { "identifier": "PaymentMapper", "path": "src/main/java/com/moabam/api/application/payment/PaymentMapper.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class PaymentMapper {\n\n\tpublic static Payment toPayment(Long memberId, Product product) {\n\t\tOrder order = Order...
import java.util.List; import com.moabam.api.application.payment.PaymentMapper; import com.moabam.api.domain.bug.Bug; import com.moabam.api.domain.bug.BugActionType; import com.moabam.api.domain.bug.BugHistory; import com.moabam.api.domain.bug.BugType; import com.moabam.api.dto.bug.BugHistoryItemResponse; import com.moabam.api.dto.bug.BugHistoryResponse; import com.moabam.api.dto.bug.BugHistoryWithPayment; import com.moabam.api.dto.bug.BugResponse; import com.moabam.global.common.util.DateUtils; import com.moabam.global.common.util.StreamUtils; import lombok.AccessLevel; import lombok.NoArgsConstructor;
1,937
package com.moabam.api.application.bug; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class BugMapper { public static BugResponse toBugResponse(Bug bug) { return BugResponse.builder() .morningBug(bug.getMorningBug()) .nightBug(bug.getNightBug()) .goldenBug(bug.getGoldenBug()) .build(); } public static BugHistoryItemResponse toBugHistoryItemResponse(BugHistoryWithPayment dto) { return BugHistoryItemResponse.builder() .id(dto.id()) .bugType(dto.bugType()) .actionType(dto.actionType()) .quantity(dto.quantity()) .date(DateUtils.format(dto.createdAt())) .payment(PaymentMapper.toPaymentResponse(dto.payment())) .build(); } public static BugHistoryResponse toBugHistoryResponse(List<BugHistoryWithPayment> dtoList) { return BugHistoryResponse.builder() .history(StreamUtils.map(dtoList, BugMapper::toBugHistoryItemResponse)) .build(); }
package com.moabam.api.application.bug; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class BugMapper { public static BugResponse toBugResponse(Bug bug) { return BugResponse.builder() .morningBug(bug.getMorningBug()) .nightBug(bug.getNightBug()) .goldenBug(bug.getGoldenBug()) .build(); } public static BugHistoryItemResponse toBugHistoryItemResponse(BugHistoryWithPayment dto) { return BugHistoryItemResponse.builder() .id(dto.id()) .bugType(dto.bugType()) .actionType(dto.actionType()) .quantity(dto.quantity()) .date(DateUtils.format(dto.createdAt())) .payment(PaymentMapper.toPaymentResponse(dto.payment())) .build(); } public static BugHistoryResponse toBugHistoryResponse(List<BugHistoryWithPayment> dtoList) { return BugHistoryResponse.builder() .history(StreamUtils.map(dtoList, BugMapper::toBugHistoryItemResponse)) .build(); }
public static BugHistory toUseBugHistory(Long memberId, BugType bugType, int quantity) {
4
2023-10-20 06:15:43+00:00
4k
Chocochip101/aws-kendra-demo
src/main/java/com/chocochip/awskendrademo/application/DemoController.java
[ { "identifier": "IndexRequestDTO", "path": "src/main/java/com/chocochip/awskendrademo/dto/IndexRequestDTO.java", "snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class IndexRequestDTO {\n private String name;\n private String clientToken;\n private String roleArn;\n private String de...
import com.chocochip.awskendrademo.dto.IndexRequestDTO; import com.chocochip.awskendrademo.dto.S3DataSourceRequestDTO; import com.chocochip.awskendrademo.dto.SearchResultDTO; import com.chocochip.awskendrademo.service.KendraService; import com.chocochip.awskendrademo.service.IndexService; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;
1,732
package com.chocochip.awskendrademo.application; @RestController @RequiredArgsConstructor public class DemoController { private final IndexService indexService; private final KendraService kendraService; @GetMapping("/search") public ResponseEntity<List<SearchResultDTO>> search( @RequestParam("keyword") String keyword, @RequestParam("index-id") String indexId) { return ResponseEntity.ok(indexService.searchForDocuments(keyword, indexId)); } @PostMapping("/datasource/s3") public ResponseEntity<String> addDataSource( @RequestBody S3DataSourceRequestDTO s3DataSourceRequestDTO, @RequestParam("index-id") String indexId) { return ResponseEntity.ok(indexService.addS3DataSource(s3DataSourceRequestDTO, indexId)); } @GetMapping("/sync") public ResponseEntity<Boolean> sync( @RequestParam("index-id") String indexId, @RequestParam("datasource-id") String dataSourceId) { indexService.syncDataSource(indexId, dataSourceId); return ResponseEntity.ok(true); } @PostMapping("/kendra/index")
package com.chocochip.awskendrademo.application; @RestController @RequiredArgsConstructor public class DemoController { private final IndexService indexService; private final KendraService kendraService; @GetMapping("/search") public ResponseEntity<List<SearchResultDTO>> search( @RequestParam("keyword") String keyword, @RequestParam("index-id") String indexId) { return ResponseEntity.ok(indexService.searchForDocuments(keyword, indexId)); } @PostMapping("/datasource/s3") public ResponseEntity<String> addDataSource( @RequestBody S3DataSourceRequestDTO s3DataSourceRequestDTO, @RequestParam("index-id") String indexId) { return ResponseEntity.ok(indexService.addS3DataSource(s3DataSourceRequestDTO, indexId)); } @GetMapping("/sync") public ResponseEntity<Boolean> sync( @RequestParam("index-id") String indexId, @RequestParam("datasource-id") String dataSourceId) { indexService.syncDataSource(indexId, dataSourceId); return ResponseEntity.ok(true); } @PostMapping("/kendra/index")
public ResponseEntity<String> createIndex(@RequestBody IndexRequestDTO indexRequestDTO) {
0
2023-10-23 15:47:15+00:00
4k
FlinkFood/FlinkFood
flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/flinkjobs/CustomerViewJob.java
[ { "identifier": "Address", "path": "flinkfood-demo/flinkfood-v-DataStream/src/main/java/org/flinkfood/schemas/Address.java", "snippet": "public class Address {\n\n public int id;\n public int customer_id;\n public String street;\n public int street_number;\n public String zipcode;\n pu...
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction; import org.apache.flink.streaming.api.windowing.time.Time; import static org.apache.flink.table.api.Expressions.jsonArray; import org.apache.flink.api.common.eventtime.WatermarkStrategy; import org.apache.flink.connector.mongodb.sink.MongoSink; import org.apache.flink.mongodb.shaded.org.bson.Document; import org.apache.flink.connector.base.DeliveryGuarantee; import org.apache.flink.connector.kafka.source.KafkaSource; import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer; import org.apache.flink.streaming.api.datastream.DataStream; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ArrayNode; import com.mongodb.client.model.InsertOneModel; import org.bson.BsonDocument; import org.flinkfood.schemas.Address; import org.flinkfood.schemas.Customer; import org.flinkfood.schemas.KafkaAddressSchema; import org.flinkfood.schemas.KafkaCustomerSchema; import org.flinkfood.schemas.KafkaOrderSchema; import org.flinkfood.schemas.Order; import org.apache.flink.util.Collector; import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
2,163
// Package declaration for the Flink job package org.flinkfood.flinkjobs; // Importing necessary Flink libraries and external dependencies // Class declaration for the Flink job public class CustomerViewJob { // Kafka and MongoDB connection details obtained from environment variables private static final String KAFKA_URI = "localhost:9092"; private static final String SOURCE_CUSTOMER_TABLE = "postgres.public.customer"; private static final String SOURCE_ADDRESS_TABLE = "postgres.public.address"; private static final String SOURCE_ORDER_TABLE = "postgres.public.orders"; private static final String MONGODB_URI = "mongodb://localhost:27017"; private static final String SINK_DB = "flinkfood"; private static final String SINK_DB_TABLE = "users_sink"; // Main method where the Flink job is defined public static void main(String[] args) throws Exception { // Setting up Kafka source with relevant configurations
// Package declaration for the Flink job package org.flinkfood.flinkjobs; // Importing necessary Flink libraries and external dependencies // Class declaration for the Flink job public class CustomerViewJob { // Kafka and MongoDB connection details obtained from environment variables private static final String KAFKA_URI = "localhost:9092"; private static final String SOURCE_CUSTOMER_TABLE = "postgres.public.customer"; private static final String SOURCE_ADDRESS_TABLE = "postgres.public.address"; private static final String SOURCE_ORDER_TABLE = "postgres.public.orders"; private static final String MONGODB_URI = "mongodb://localhost:27017"; private static final String SINK_DB = "flinkfood"; private static final String SINK_DB_TABLE = "users_sink"; // Main method where the Flink job is defined public static void main(String[] args) throws Exception { // Setting up Kafka source with relevant configurations
KafkaSource<Customer> sourceCustomer = KafkaSource.<Customer>builder()
1
2023-10-17 08:37:30+00:00
4k
liukanshan1/PrivateTrace-Core
src/main/java/Priloc/protocol/CCircleTree.java
[ { "identifier": "EncTmLocData", "path": "src/main/java/Priloc/data/EncTmLocData.java", "snippet": "public class EncTmLocData implements Serializable {\n private EncryptedCircle eCircle;\n private Date date;\n private EncTmLocData nETLD = null;\n private EncTmLocData pETLD = null;\n privat...
import Priloc.data.EncTmLocData; import Priloc.data.EncTrajectory; import Priloc.utils.Constant; import Priloc.utils.Utils; import sg.smu.securecom.protocol.Paillier; import sg.smu.securecom.protocol.PaillierThdDec; import java.io.Serializable; import java.util.*; import java.util.concurrent.*;
2,292
package Priloc.protocol; public class CCircleTree implements Serializable { private HashMap<Date, ConcentricCircles> ccTree; private transient ThreadLocal<Map<ConcentricCircles, boolean[]>> localPrune = new ThreadLocal<>(); private static final List<EncTrajectory> workLoad = new LinkedList<>(); public CCircleTree() { this.ccTree = new HashMap<>(); } public void add(EncTrajectory eTrajectory) { List<EncTmLocData> eTLDs = eTrajectory.geteTLDs(); for (int i = 0; i < eTLDs.size(); i++) { EncTmLocData eTLD = eTLDs.get(i); Date startDate = eTLD.getDate(); ConcentricCircles ccs = ccTree.get(startDate); if (ccs == null) { ccs = new ConcentricCircles(eTLD, this); //ccs.setDates(startDate, new Date(startDate.getTime() + INTERVAL * 60 * 1000)); ccTree.put(startDate, ccs); } else { ccs.add(eTLD); } } } public void init() throws InterruptedException {
package Priloc.protocol; public class CCircleTree implements Serializable { private HashMap<Date, ConcentricCircles> ccTree; private transient ThreadLocal<Map<ConcentricCircles, boolean[]>> localPrune = new ThreadLocal<>(); private static final List<EncTrajectory> workLoad = new LinkedList<>(); public CCircleTree() { this.ccTree = new HashMap<>(); } public void add(EncTrajectory eTrajectory) { List<EncTmLocData> eTLDs = eTrajectory.geteTLDs(); for (int i = 0; i < eTLDs.size(); i++) { EncTmLocData eTLD = eTLDs.get(i); Date startDate = eTLD.getDate(); ConcentricCircles ccs = ccTree.get(startDate); if (ccs == null) { ccs = new ConcentricCircles(eTLD, this); //ccs.setDates(startDate, new Date(startDate.getTime() + INTERVAL * 60 * 1000)); ccTree.put(startDate, ccs); } else { ccs.add(eTLD); } } } public void init() throws InterruptedException {
ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD);
2
2023-10-22 06:28:51+00:00
4k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/ui/FxWindow.java
[ { "identifier": "BorderlessPane", "path": "BaseUI/src/main/java/com/xm2013/jfx/borderless/BorderlessPane.java", "snippet": "public class BorderlessPane extends AnchorPane {\n\tpublic BorderlessPane (BorderlessController controller) throws IOException {\n\n\t\t// ------------------------------------FXMLL...
import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.value.ObservableValue; import javafx.scene.Node; import javafx.scene.image.Image; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.StageStyle; import java.io.IOException; import com.xm2013.jfx.borderless.BorderlessPane; import com.xm2013.jfx.borderless.BorderlessScene; import com.xm2013.jfx.borderless.CustomStage; import com.xm2013.jfx.component.eventbus.FXEventBus; import com.xm2013.jfx.component.eventbus.XmEvent; import javafx.beans.property.DoubleProperty;
3,285
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * 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 com.xm2013.jfx.ui; public class FxWindow { private CustomStage stage; private BorderlessScene scene = null; private DoubleProperty heightProperty = new SimpleDoubleProperty(); private DoubleProperty widthProperty = new SimpleDoubleProperty(); public FxWindow(double width, double height, Pane rootPane) throws IOException { heightProperty.set(height); widthProperty.set(width); stage = new CustomStage(StageStyle.TRANSPARENT); stage.setWidth(width+40); stage.setHeight(height+40); scene = stage.craftBorderlessScene(rootPane); scene.setFill(Color.TRANSPARENT); scene.maximizedProperty().addListener((ob, ov, nv)->{ if(nv){ heightProperty.set(stage.getHeight()); widthProperty.set(stage.getWidth()); }else{ heightProperty.set(stage.getHeight()-40); widthProperty.set(stage.getWidth()-40); } }); stage.heightProperty().addListener((ob, ov, nv)->{ if(scene.isMaximized()){ heightProperty.set(stage.getHeight()); }else{ heightProperty.set(stage.getHeight()-40); } }); stage.widthProperty().addListener((ob, ov, nv)->{ if(scene.isMaximized()){ widthProperty.set(stage.getWidth()); }else{ widthProperty.set(stage.getWidth()-40); } }); stage.setScene(scene); scene.removeDefaultCSS(); rootPane.setStyle("-fx-background-color: white;"); final BorderlessPane root = (BorderlessPane) scene.getRoot(); root.setStyle("-fx-background-color: transparent; " + "-fx-padding:20px; " + "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);"); scene.maximizedProperty().addListener((ob, ov, nv)->{ if(nv) { root.setStyle(""); }else { root.setStyle("-fx-background-color: transparent; " + "-fx-padding:20px; " + "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);"); } });
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * 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 com.xm2013.jfx.ui; public class FxWindow { private CustomStage stage; private BorderlessScene scene = null; private DoubleProperty heightProperty = new SimpleDoubleProperty(); private DoubleProperty widthProperty = new SimpleDoubleProperty(); public FxWindow(double width, double height, Pane rootPane) throws IOException { heightProperty.set(height); widthProperty.set(width); stage = new CustomStage(StageStyle.TRANSPARENT); stage.setWidth(width+40); stage.setHeight(height+40); scene = stage.craftBorderlessScene(rootPane); scene.setFill(Color.TRANSPARENT); scene.maximizedProperty().addListener((ob, ov, nv)->{ if(nv){ heightProperty.set(stage.getHeight()); widthProperty.set(stage.getWidth()); }else{ heightProperty.set(stage.getHeight()-40); widthProperty.set(stage.getWidth()-40); } }); stage.heightProperty().addListener((ob, ov, nv)->{ if(scene.isMaximized()){ heightProperty.set(stage.getHeight()); }else{ heightProperty.set(stage.getHeight()-40); } }); stage.widthProperty().addListener((ob, ov, nv)->{ if(scene.isMaximized()){ widthProperty.set(stage.getWidth()); }else{ widthProperty.set(stage.getWidth()-40); } }); stage.setScene(scene); scene.removeDefaultCSS(); rootPane.setStyle("-fx-background-color: white;"); final BorderlessPane root = (BorderlessPane) scene.getRoot(); root.setStyle("-fx-background-color: transparent; " + "-fx-padding:20px; " + "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);"); scene.maximizedProperty().addListener((ob, ov, nv)->{ if(nv) { root.setStyle(""); }else { root.setStyle("-fx-background-color: transparent; " + "-fx-padding:20px; " + "-fx-effect: dropshadow(gaussian, rgba(10,10,10,0.2), 20, 0.1,0px, 0px);"); } });
FXEventBus.getDefault().addEventHandler(XmEvent.MAX_WINDOW, e -> {
3
2023-10-17 08:57:08+00:00
4k
ErickMonteiroMDK/Advocacia_Beckhauser
src/main/java/com/advocacia/Advocacia_Beckhauser/resources/AgendaController.java
[ { "identifier": "ValidationException", "path": "src/main/java/com/advocacia/Advocacia_Beckhauser/enterprise/ValidationException.java", "snippet": "public class ValidationException extends RuntimeException {\n public ValidationException(String message) {\n super(message);\n }\n}" }, { ...
import java.net.URI; import java.time.temporal.ChronoUnit; import java.util.List; import com.advocacia.Advocacia_Beckhauser.enterprise.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.advocacia.Advocacia_Beckhauser.models.Agenda; import com.advocacia.Advocacia_Beckhauser.services.AgendaService;
1,700
package com.advocacia.Advocacia_Beckhauser.resources; @RestController @RequestMapping("/api/agenda") public class AgendaController extends AbstractController { @Autowired AgendaService service; // ResponseEntity recebe <?> para obter qualquer tipo de retorno(String ou Agenda). Deus nos proteja de qualquer erro com 500 linhas /* * Autor: Lucas Ronchi * * Mensagem à Raphael: * Então tá jóia... * */ @PostMapping public ResponseEntity salvarAgenda(@RequestBody Agenda agenda) { if (agenda.getDataInicial().isAfter(agenda.getDataFatal())) {
package com.advocacia.Advocacia_Beckhauser.resources; @RestController @RequestMapping("/api/agenda") public class AgendaController extends AbstractController { @Autowired AgendaService service; // ResponseEntity recebe <?> para obter qualquer tipo de retorno(String ou Agenda). Deus nos proteja de qualquer erro com 500 linhas /* * Autor: Lucas Ronchi * * Mensagem à Raphael: * Então tá jóia... * */ @PostMapping public ResponseEntity salvarAgenda(@RequestBody Agenda agenda) { if (agenda.getDataInicial().isAfter(agenda.getDataFatal())) {
throw new ValidationException("data inicial deve ser anterior ou igual a data fatal");
0
2023-10-24 21:35:12+00:00
4k
Space125/tasklist
src/main/java/org/kurilov/tasklist/web/controller/UserController.java
[ { "identifier": "Task", "path": "src/main/java/org/kurilov/tasklist/domain/task/Task.java", "snippet": "@Data\npublic class Task {\n\n private Long id;\n private String title;\n private String description;\n private Status status;\n private LocalDateTime expirationDate;\n}" }, { "...
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; import org.kurilov.tasklist.domain.task.Task; import org.kurilov.tasklist.domain.user.User; import org.kurilov.tasklist.service.TaskService; import org.kurilov.tasklist.service.UserService; import org.kurilov.tasklist.web.dto.task.TaskDto; import org.kurilov.tasklist.web.dto.user.UserDto; import org.kurilov.tasklist.web.dto.validation.OnCreate; import org.kurilov.tasklist.web.dto.validation.OnUpdate; import org.kurilov.tasklist.web.mappers.TaskMapper; import org.kurilov.tasklist.web.mappers.UserMapper; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.List;
1,678
package org.kurilov.tasklist.web.controller; /** * @author Ivan Kurilov on 20.10.2023 */ @RestController @RequestMapping("/api/v1/users") @Validated @RequiredArgsConstructor @Tag(name = "User Controller", description = "User API") public class UserController { private final UserService userService; private final TaskService taskService; private final UserMapper userMapper; private final TaskMapper taskMapper; @PutMapping @Operation(summary = "Update User") @PreAuthorize("@userSecurityExpression.canAccessUser(#dto.id)") public UserDto update(@Validated(OnUpdate.class) @RequestBody final UserDto dto) { User user = userMapper.toEntity(dto); User updatedUser = userService.update(user); return userMapper.toDto(updatedUser); } @GetMapping("/{id}") @Operation(summary = "Get UserDto by Id") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)") public UserDto getById(@PathVariable final Long id) { User user = userService.getById(id); return userMapper.toDto(user); } @DeleteMapping("/{id}") @Operation(summary = "Delete User") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)") public void delete(@PathVariable final Long id) { userService.delete(id); } @GetMapping("/{id}/tasks") @Operation(summary = "Get all User Tasks") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)") public List<TaskDto> getTaskByUserId(@PathVariable final Long id) { List<Task> tasks = taskService.getAllByUserId(id); return taskMapper.toDto(tasks); } @PostMapping("/{id}/tasks") @Operation(summary = "Add task to User") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
package org.kurilov.tasklist.web.controller; /** * @author Ivan Kurilov on 20.10.2023 */ @RestController @RequestMapping("/api/v1/users") @Validated @RequiredArgsConstructor @Tag(name = "User Controller", description = "User API") public class UserController { private final UserService userService; private final TaskService taskService; private final UserMapper userMapper; private final TaskMapper taskMapper; @PutMapping @Operation(summary = "Update User") @PreAuthorize("@userSecurityExpression.canAccessUser(#dto.id)") public UserDto update(@Validated(OnUpdate.class) @RequestBody final UserDto dto) { User user = userMapper.toEntity(dto); User updatedUser = userService.update(user); return userMapper.toDto(updatedUser); } @GetMapping("/{id}") @Operation(summary = "Get UserDto by Id") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)") public UserDto getById(@PathVariable final Long id) { User user = userService.getById(id); return userMapper.toDto(user); } @DeleteMapping("/{id}") @Operation(summary = "Delete User") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)") public void delete(@PathVariable final Long id) { userService.delete(id); } @GetMapping("/{id}/tasks") @Operation(summary = "Get all User Tasks") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)") public List<TaskDto> getTaskByUserId(@PathVariable final Long id) { List<Task> tasks = taskService.getAllByUserId(id); return taskMapper.toDto(tasks); } @PostMapping("/{id}/tasks") @Operation(summary = "Add task to User") @PreAuthorize("@userSecurityExpression.canAccessUser(#id)")
public TaskDto createTask(@Validated(OnCreate.class)
6
2023-10-19 05:50:28+00:00
4k
rfresh2/2b2t.vc-rusherhack
src/main/java/vc/VcPlugin.java
[ { "identifier": "VcApi", "path": "src/main/java/vc/api/VcApi.java", "snippet": "public class VcApi {\n private final HttpClient httpClient;\n private final ILogger logger;\n private final Gson gson;\n\n public VcApi(final ILogger logger) {\n this.logger = logger;\n this.httpCli...
import org.rusherhack.client.api.RusherHackAPI; import org.rusherhack.client.api.plugin.Plugin; import vc.api.VcApi; import vc.command.PlaytimeCommand; import vc.command.QueueCommand; import vc.command.SeenCommand; import vc.command.StatsCommand; import vc.hud.Queue2b2tHudElement;
2,329
package vc; public class VcPlugin extends Plugin { @Override public void onLoad() {
package vc; public class VcPlugin extends Plugin { @Override public void onLoad() {
final VcApi api = new VcApi(getLogger());
0
2023-10-22 20:22:42+00:00
4k
Dwight-Studio/JArmEmu
src/main/java/fr/dwightstudio/jarmemu/gui/view/MemoryChunkView.java
[ { "identifier": "MemoryAccessor", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/obj/MemoryAccessor.java", "snippet": "public class MemoryAccessor {\n\n private final HashMap<Integer, IntegerProperty> memory;\n private final HashSet<Integer> initiationMap;\n\n public MemoryAccessor() {\n ...
import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import java.util.ArrayList; import fr.dwightstudio.jarmemu.sim.obj.MemoryAccessor; import fr.dwightstudio.jarmemu.util.converters.WordASCIIStringConverter; import javafx.beans.InvalidationListener; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ReadOnlyIntegerProperty; import javafx.beans.property.ReadOnlyIntegerWrapper; import javafx.beans.property.ReadOnlyStringProperty;
1,983
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * 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 fr.dwightstudio.jarmemu.gui.view; public class MemoryChunkView { private final MemoryAccessor memoryAccessor; private final ReadOnlyIntegerProperty addressProperty; private final IntegerProperty value0Property; private final IntegerProperty value1Property; private final IntegerProperty value2Property; private final IntegerProperty value3Property; public MemoryChunkView(MemoryAccessor memoryAccessor, int address) { this.memoryAccessor = memoryAccessor; this.addressProperty = new ReadOnlyIntegerWrapper(address); this.value0Property = memoryAccessor.getProperty(address); this.value1Property = memoryAccessor.getProperty(address + 4); this.value2Property = memoryAccessor.getProperty(address + 8); this.value3Property = memoryAccessor.getProperty(address + 12); } public MemoryAccessor getMemoryAccessor() { return memoryAccessor; } public ReadOnlyIntegerProperty getAddressProperty() { return addressProperty; } public IntegerProperty getValue0Property() { return value0Property; } public IntegerProperty getValue1Property() { return value1Property; } public IntegerProperty getValue2Property() { return value2Property; } public IntegerProperty getValue3Property() { return value3Property; } public ObservableValue<String> getASCIIProperty() { return new ChunkASCIIProperty(); } public class ChunkASCIIProperty extends ReadOnlyStringProperty { private final ArrayList<ChangeListener<? super String>> changeListeners; private final ArrayList<InvalidationListener> invalidationListeners;
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * 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 fr.dwightstudio.jarmemu.gui.view; public class MemoryChunkView { private final MemoryAccessor memoryAccessor; private final ReadOnlyIntegerProperty addressProperty; private final IntegerProperty value0Property; private final IntegerProperty value1Property; private final IntegerProperty value2Property; private final IntegerProperty value3Property; public MemoryChunkView(MemoryAccessor memoryAccessor, int address) { this.memoryAccessor = memoryAccessor; this.addressProperty = new ReadOnlyIntegerWrapper(address); this.value0Property = memoryAccessor.getProperty(address); this.value1Property = memoryAccessor.getProperty(address + 4); this.value2Property = memoryAccessor.getProperty(address + 8); this.value3Property = memoryAccessor.getProperty(address + 12); } public MemoryAccessor getMemoryAccessor() { return memoryAccessor; } public ReadOnlyIntegerProperty getAddressProperty() { return addressProperty; } public IntegerProperty getValue0Property() { return value0Property; } public IntegerProperty getValue1Property() { return value1Property; } public IntegerProperty getValue2Property() { return value2Property; } public IntegerProperty getValue3Property() { return value3Property; } public ObservableValue<String> getASCIIProperty() { return new ChunkASCIIProperty(); } public class ChunkASCIIProperty extends ReadOnlyStringProperty { private final ArrayList<ChangeListener<? super String>> changeListeners; private final ArrayList<InvalidationListener> invalidationListeners;
private WordASCIIStringConverter converter;
1
2023-10-17 18:22:09+00:00
4k
GTNewHorizons/FarmingForEngineers
src/main/java/com/guigs44/farmingforengineers/container/ContainerMarket.java
[ { "identifier": "MessageMarketList", "path": "src/main/java/com/guigs44/farmingforengineers/network/MessageMarketList.java", "snippet": "public class MessageMarketList implements IMessage {\n\n private Collection<MarketEntry> entryList;\n\n public MessageMarketList() {}\n\n public MessageMarket...
import java.util.List; import javax.annotation.Nullable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Items; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import com.google.common.collect.Lists; import com.guigs44.farmingforengineers.network.MessageMarketList; import com.guigs44.farmingforengineers.network.NetworkHandler; import com.guigs44.farmingforengineers.registry.MarketEntry; import com.guigs44.farmingforengineers.registry.MarketRegistry;
3,172
package com.guigs44.farmingforengineers.container; public class ContainerMarket extends Container { private final EntityPlayer player; private final int posX; private final int posY; private final int posZ; private final InventoryBasic marketInputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); private final InventoryBasic marketOutputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList(); private boolean sentItemList;
package com.guigs44.farmingforengineers.container; public class ContainerMarket extends Container { private final EntityPlayer player; private final int posX; private final int posY; private final int posZ; private final InventoryBasic marketInputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); private final InventoryBasic marketOutputBuffer = new InventoryBasic( "container.farmingforengineers:market", false, 1); protected final List<FakeSlotMarket> marketSlots = Lists.newArrayList(); private boolean sentItemList;
protected MarketEntry selectedEntry;
2
2023-10-17 00:25:50+00:00
4k
mnesimiyilmaz/sql4json
src/main/java/io/github/mnesimiyilmaz/sql4json/grouping/GroupByProcessor.java
[ { "identifier": "JsonColumnWithNonAggFunctionDefinion", "path": "src/main/java/io/github/mnesimiyilmaz/sql4json/definitions/JsonColumnWithNonAggFunctionDefinion.java", "snippet": "@Getter\npublic class JsonColumnWithNonAggFunctionDefinion {\n\n private final SQL4JsonParser.JsonColumnWithNonAggFunctio...
import io.github.mnesimiyilmaz.sql4json.definitions.JsonColumnWithNonAggFunctionDefinion; import io.github.mnesimiyilmaz.sql4json.definitions.SelectColumnDefinition; import io.github.mnesimiyilmaz.sql4json.utils.AggregateFunction; import io.github.mnesimiyilmaz.sql4json.utils.AggregationUtils; import io.github.mnesimiyilmaz.sql4json.utils.FieldKey; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import static io.github.mnesimiyilmaz.sql4json.utils.AggregateFunction.COUNT;
2,044
package io.github.mnesimiyilmaz.sql4json.grouping; /** * @author mnesimiyilmaz */ public class GroupByProcessor { private final GroupByInput groupByInput; private final Map<String, FieldKey> groupByFieldCache; private final List<SelectColumnDefinition> nonAggColumnsCache; private final List<SelectColumnDefinition> aggColumnsCache; public GroupByProcessor(GroupByInput groupByInput) { this.groupByInput = groupByInput; this.groupByFieldCache = new HashMap<>(); this.groupByInput.getGroupByColumns() .forEach(x -> groupByFieldCache.put(x.getColumnName(), FieldKey.of(x.getColumnName()))); this.nonAggColumnsCache = groupByInput.getSelectedColumns().stream() .filter(x -> x.getColumnDefinition().getAggregateFunction() == null).collect(Collectors.toList()); this.aggColumnsCache = groupByInput.getSelectedColumns() .stream().filter(x -> x.getColumnDefinition().getAggregateFunction() != null).collect(Collectors.toList()); } public List<Map<FieldKey, Object>> process() { Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = groupRows(); List<Map<FieldKey, Object>> groupByResult = applyAggregations(groupedRows); if (groupByInput.getHavingClause() != null) { groupByResult.removeIf(x -> !groupByInput.getHavingClause().test(x)); } return groupByResult; } private Map<GroupRowData, List<Map<FieldKey, Object>>> groupRows() { Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = new HashMap<>(); for (Map<FieldKey, Object> row : this.groupByInput.getFlattenedInputJsonNode()) { Map<String, Object> groupRowData = new HashMap<>();
package io.github.mnesimiyilmaz.sql4json.grouping; /** * @author mnesimiyilmaz */ public class GroupByProcessor { private final GroupByInput groupByInput; private final Map<String, FieldKey> groupByFieldCache; private final List<SelectColumnDefinition> nonAggColumnsCache; private final List<SelectColumnDefinition> aggColumnsCache; public GroupByProcessor(GroupByInput groupByInput) { this.groupByInput = groupByInput; this.groupByFieldCache = new HashMap<>(); this.groupByInput.getGroupByColumns() .forEach(x -> groupByFieldCache.put(x.getColumnName(), FieldKey.of(x.getColumnName()))); this.nonAggColumnsCache = groupByInput.getSelectedColumns().stream() .filter(x -> x.getColumnDefinition().getAggregateFunction() == null).collect(Collectors.toList()); this.aggColumnsCache = groupByInput.getSelectedColumns() .stream().filter(x -> x.getColumnDefinition().getAggregateFunction() != null).collect(Collectors.toList()); } public List<Map<FieldKey, Object>> process() { Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = groupRows(); List<Map<FieldKey, Object>> groupByResult = applyAggregations(groupedRows); if (groupByInput.getHavingClause() != null) { groupByResult.removeIf(x -> !groupByInput.getHavingClause().test(x)); } return groupByResult; } private Map<GroupRowData, List<Map<FieldKey, Object>>> groupRows() { Map<GroupRowData, List<Map<FieldKey, Object>>> groupedRows = new HashMap<>(); for (Map<FieldKey, Object> row : this.groupByInput.getFlattenedInputJsonNode()) { Map<String, Object> groupRowData = new HashMap<>();
for (JsonColumnWithNonAggFunctionDefinion groupByColumn : this.groupByInput.getGroupByColumns()) {
0
2023-10-24 18:34:33+00:00
4k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/treebank/AbstractTreebankLanguagePack.java
[ { "identifier": "Filter", "path": "src/berkeley_parser/edu/berkeley/nlp/util/Filter.java", "snippet": "public interface Filter<T> {\n\tboolean accept(T t);\n}" }, { "identifier": "Filters", "path": "src/berkeley_parser/edu/berkeley/nlp/util/Filters.java", "snippet": "public class Filters...
import java.io.Serializable; import edu.berkeley.nlp.util.Filter; import edu.berkeley.nlp.util.Filters;
2,472
package edu.berkeley.nlp.treebank; /** * This provides an implementation of parts of the TreebankLanguagePack API to * reduce the load on fresh implementations. Only the abstract methods below * need to be implemented to give a reasonable solution for a new language. * * @author Christopher Manning * @version 1.1 */ public abstract class AbstractTreebankLanguagePack implements TreebankLanguagePack, Serializable { /** * Use this as the default encoding for Readers and Writers of Treebank * data. */ public static final String DEFAULT_ENCODING = "UTF-8"; /** * Gives a handle to the TreebankLanguagePack */ public AbstractTreebankLanguagePack() { } /** * Returns a String array of punctuation tags for this treebank/language. * * @return The punctuation tags */ public abstract String[] punctuationTags(); /** * Returns a String array of punctuation words for this treebank/language. * * @return The punctuation words */ public abstract String[] punctuationWords(); /** * Returns a String array of sentence final punctuation tags for this * treebank/language. * * @return The sentence final punctuation tags */ public abstract String[] sentenceFinalPunctuationTags(); /** * Returns a String array of punctuation tags that EVALB-style evaluation * should ignore for this treebank/language. Traditionally, EVALB has * ignored a subset of the total set of punctuation tags in the English Penn * Treebank (quotes and period, comma, colon, etc., but not brackets) * * @return Whether this is a EVALB-ignored punctuation tag */ public String[] evalBIgnoredPunctuationTags() { return punctuationTags(); } /** * Accepts a String that is a punctuation tag name, and rejects everything * else. * * @return Whether this is a punctuation tag */ public boolean isPunctuationTag(String str) { return punctTagStringAcceptFilter.accept(str); } /** * Accepts a String that is a punctuation word, and rejects everything else. * If one can't tell for sure (as for ' in the Penn Treebank), it maks the * best guess that it can. * * @return Whether this is a punctuation word */ public boolean isPunctuationWord(String str) { return punctWordStringAcceptFilter.accept(str); } /** * Accepts a String that is a sentence end punctuation tag, and rejects * everything else. * * @return Whether this is a sentence final punctuation tag */ public boolean isSentenceFinalPunctuationTag(String str) { return sFPunctTagStringAcceptFilter.accept(str); } /** * Accepts a String that is a punctuation tag that should be ignored by * EVALB-style evaluation, and rejects everything else. Traditionally, EVALB * has ignored a subset of the total set of punctuation tags in the English * Penn Treebank (quotes and period, comma, colon, etc., but not brackets) * * @return Whether this is a EVALB-ignored punctuation tag */ public boolean isEvalBIgnoredPunctuationTag(String str) { return eIPunctTagStringAcceptFilter.accept(str); } /** * Return a filter that accepts a String that is a punctuation tag name, and * rejects everything else. * * @return The filter */ public Filter punctuationTagAcceptFilter() { return punctTagStringAcceptFilter; } /** * Return a filter that rejects a String that is a punctuation tag name, and * rejects everything else. * * @return The filter */ public Filter punctuationTagRejectFilter() {
package edu.berkeley.nlp.treebank; /** * This provides an implementation of parts of the TreebankLanguagePack API to * reduce the load on fresh implementations. Only the abstract methods below * need to be implemented to give a reasonable solution for a new language. * * @author Christopher Manning * @version 1.1 */ public abstract class AbstractTreebankLanguagePack implements TreebankLanguagePack, Serializable { /** * Use this as the default encoding for Readers and Writers of Treebank * data. */ public static final String DEFAULT_ENCODING = "UTF-8"; /** * Gives a handle to the TreebankLanguagePack */ public AbstractTreebankLanguagePack() { } /** * Returns a String array of punctuation tags for this treebank/language. * * @return The punctuation tags */ public abstract String[] punctuationTags(); /** * Returns a String array of punctuation words for this treebank/language. * * @return The punctuation words */ public abstract String[] punctuationWords(); /** * Returns a String array of sentence final punctuation tags for this * treebank/language. * * @return The sentence final punctuation tags */ public abstract String[] sentenceFinalPunctuationTags(); /** * Returns a String array of punctuation tags that EVALB-style evaluation * should ignore for this treebank/language. Traditionally, EVALB has * ignored a subset of the total set of punctuation tags in the English Penn * Treebank (quotes and period, comma, colon, etc., but not brackets) * * @return Whether this is a EVALB-ignored punctuation tag */ public String[] evalBIgnoredPunctuationTags() { return punctuationTags(); } /** * Accepts a String that is a punctuation tag name, and rejects everything * else. * * @return Whether this is a punctuation tag */ public boolean isPunctuationTag(String str) { return punctTagStringAcceptFilter.accept(str); } /** * Accepts a String that is a punctuation word, and rejects everything else. * If one can't tell for sure (as for ' in the Penn Treebank), it maks the * best guess that it can. * * @return Whether this is a punctuation word */ public boolean isPunctuationWord(String str) { return punctWordStringAcceptFilter.accept(str); } /** * Accepts a String that is a sentence end punctuation tag, and rejects * everything else. * * @return Whether this is a sentence final punctuation tag */ public boolean isSentenceFinalPunctuationTag(String str) { return sFPunctTagStringAcceptFilter.accept(str); } /** * Accepts a String that is a punctuation tag that should be ignored by * EVALB-style evaluation, and rejects everything else. Traditionally, EVALB * has ignored a subset of the total set of punctuation tags in the English * Penn Treebank (quotes and period, comma, colon, etc., but not brackets) * * @return Whether this is a EVALB-ignored punctuation tag */ public boolean isEvalBIgnoredPunctuationTag(String str) { return eIPunctTagStringAcceptFilter.accept(str); } /** * Return a filter that accepts a String that is a punctuation tag name, and * rejects everything else. * * @return The filter */ public Filter punctuationTagAcceptFilter() { return punctTagStringAcceptFilter; } /** * Return a filter that rejects a String that is a punctuation tag name, and * rejects everything else. * * @return The filter */ public Filter punctuationTagRejectFilter() {
return Filters.notFilter(punctTagStringAcceptFilter);
1
2023-10-22 13:13:22+00:00
4k
UZ9/cs-1331-drivers
src/com/cs1331/drivers/testing/TestContainer.java
[ { "identifier": "TestFailedException", "path": "src/com/cs1331/drivers/exception/TestFailedException.java", "snippet": "public class TestFailedException extends Exception {\n public TestFailedException() {\n }\n\n public TestFailedException(String message) {\n super(message);\n }\n}" ...
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import com.cs1331.drivers.annotations.AfterTest; import com.cs1331.drivers.annotations.BeforeTest; import com.cs1331.drivers.annotations.TestCase; import com.cs1331.drivers.annotations.Tip; import com.cs1331.drivers.exception.TestFailedException; import com.cs1331.drivers.utils.AsciiColorCode; import com.cs1331.drivers.utils.ColorUtils; import com.cs1331.drivers.utils.StringUtils; import com.cs1331.drivers.utils.Tuple; import java.util.ArrayList;
3,202
package com.cs1331.drivers.testing; /** * Represents a Runnable that can be thrown into a ThreadPoolExecutor. The * TestContainer will latch onto a Class<?> and attempt to run any methods * labeled as test functions, e.g. @TestCase or @BeforeTest */ public class TestContainer implements Runnable { /** * The class belonging to the TestContainer */ private Class<?> clazz; /** * As the methods are non-static, there must be an instance all share when * executing the methods. At the start of the test a single instance is * initialized for all tests to use. */ private Object instance = null; /** * Initializes a new TestContainer. A TestContainer is used to prevent certain * edge cases such as infinite loops. * * If an infinite loop occurs, the test will timeout and notify the user * accordingly. * * @param clazz The class containing the tests */ public TestContainer(Class<?> clazz) { this.clazz = clazz; } /** * Executes a method belonging to this instance. * This is used when cycling over the methods marked with @BeforeTest * and @AfterTest, as both require the same invocation logic. * * @param method The method to execute */ private void executeFunction(Method method) { try { method.invoke(instance); } catch (Exception e) {
package com.cs1331.drivers.testing; /** * Represents a Runnable that can be thrown into a ThreadPoolExecutor. The * TestContainer will latch onto a Class<?> and attempt to run any methods * labeled as test functions, e.g. @TestCase or @BeforeTest */ public class TestContainer implements Runnable { /** * The class belonging to the TestContainer */ private Class<?> clazz; /** * As the methods are non-static, there must be an instance all share when * executing the methods. At the start of the test a single instance is * initialized for all tests to use. */ private Object instance = null; /** * Initializes a new TestContainer. A TestContainer is used to prevent certain * edge cases such as infinite loops. * * If an infinite loop occurs, the test will timeout and notify the user * accordingly. * * @param clazz The class containing the tests */ public TestContainer(Class<?> clazz) { this.clazz = clazz; } /** * Executes a method belonging to this instance. * This is used when cycling over the methods marked with @BeforeTest * and @AfterTest, as both require the same invocation logic. * * @param method The method to execute */ private void executeFunction(Method method) { try { method.invoke(instance); } catch (Exception e) {
System.out.println(ColorUtils.formatColorString(AsciiColorCode.WHITE_BACKGROUND,
1
2023-10-20 03:06:59+00:00
4k
AkramLZ/ServerSync
serversync-bungee/src/main/java/me/akraml/serversync/bungee/BungeeServersManager.java
[ { "identifier": "Server", "path": "serversync-common/src/main/java/me/akraml/serversync/server/Server.java", "snippet": "public interface Server {\n\n /**\n * Retrieves the name of the current synchronized server.\n *\n * @return {@link Server}'s current name.\n */\n String getName...
import me.akraml.serversync.server.Server; import me.akraml.serversync.server.ServersManager; import net.md_5.bungee.api.config.ServerInfo; import java.net.InetSocketAddress;
1,849
/* * MIT License * * Copyright (c) 2023 Akram Louze * * 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 me.akraml.serversync.bungee; /** * Implementation of the {@link ServersManager} for a BungeeCord proxy environment. * This manager handles the registration and un-registration of server instances specifically * for BungeeCord. */ public final class BungeeServersManager extends ServersManager { private final BungeeServerSyncPlugin plugin; public BungeeServersManager(final BungeeServerSyncPlugin plugin) { this.plugin = plugin; this.heartbeatSchedulerDelay = plugin.getConfig().getInt("heartbeat-scheduler-delay"); this.maxAliveTime = plugin.getConfig().getInt("max-alive-time"); } /** * Unregisters a server from the BungeeCord proxy. This removes the server from the list of * servers known to the proxy, effectively making it inaccessible to players through the proxy. * * @param server The server to unregister from the proxy. */ @Override
/* * MIT License * * Copyright (c) 2023 Akram Louze * * 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 me.akraml.serversync.bungee; /** * Implementation of the {@link ServersManager} for a BungeeCord proxy environment. * This manager handles the registration and un-registration of server instances specifically * for BungeeCord. */ public final class BungeeServersManager extends ServersManager { private final BungeeServerSyncPlugin plugin; public BungeeServersManager(final BungeeServerSyncPlugin plugin) { this.plugin = plugin; this.heartbeatSchedulerDelay = plugin.getConfig().getInt("heartbeat-scheduler-delay"); this.maxAliveTime = plugin.getConfig().getInt("max-alive-time"); } /** * Unregisters a server from the BungeeCord proxy. This removes the server from the list of * servers known to the proxy, effectively making it inaccessible to players through the proxy. * * @param server The server to unregister from the proxy. */ @Override
protected void unregisterFromProxy(Server server) {
0
2023-10-21 12:47:58+00:00
4k
neftalito/R-Info-Plus
arbol/sentencia/Asignacion.java
[ { "identifier": "Programa", "path": "arbol/Programa.java", "snippet": "public class Programa extends AST {\n Identificador I;\n DeclaracionRobots DR;\n DeclaracionProcesos DP;\n DeclaracionVariable DV;\n DeclaracionAreas DA;\n Cuerpo C;\n Robot R;\n Ciudad city;\n CodePanel co...
import arbol.Programa; import arbol.Variable; import arbol.DeclaracionVariable; import arbol.expresion.Expresion; import arbol.Identificador;
2,988
package arbol.sentencia; public class Asignacion extends Sentencia { Identificador I; Expresion E; DeclaracionVariable DV; public Asignacion(final Identificador I, final Expresion E, final DeclaracionVariable DV) { this.I = I; this.E = E; this.DV = DV; } @Override public void ejecutar() throws Exception { synchronized (this) { this.E.setRobot(this.getRobot()); if (!this.DV.EstaParametro(this.I.toString())) { this.programa.getCity().parseError("Variable: " + this.I.toString() + "no encontrada"); throw new Exception("Variable: " + this.I.toString() + "no encontrada"); } final Variable tmp = this.DV.findByName(this.I.toString()); final String eValue = this.E.getValue(this.DV); if (tmp.getT().toString().equals("boolean") && !eValue.equals("V") && !eValue.equals("F")) { this.programa.getCity().parseError( "Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString()); throw new Exception( "Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString()); } if (tmp.getT().toString().equals("numero")) { try { System.out.println("e value vale: " + eValue); Integer.parseInt(eValue); } catch (Exception ex) { this.programa.getCity().parseError( "Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString()); throw new Exception( "Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString()); } } this.DV.findByName(this.I.toString()).setValue(eValue); } } @Override public Object clone() throws CloneNotSupportedException { final Object obj = null; final Identificador II = new Identificador(this.I.toString()); System.out.println("Intentando clonar expresion en asignacion"); final Expresion EE = (Expresion) this.E.clone(); return new Asignacion(II, EE, this.DV); } @Override public void setDV(final DeclaracionVariable varAST) { this.DV = varAST; } @Override
package arbol.sentencia; public class Asignacion extends Sentencia { Identificador I; Expresion E; DeclaracionVariable DV; public Asignacion(final Identificador I, final Expresion E, final DeclaracionVariable DV) { this.I = I; this.E = E; this.DV = DV; } @Override public void ejecutar() throws Exception { synchronized (this) { this.E.setRobot(this.getRobot()); if (!this.DV.EstaParametro(this.I.toString())) { this.programa.getCity().parseError("Variable: " + this.I.toString() + "no encontrada"); throw new Exception("Variable: " + this.I.toString() + "no encontrada"); } final Variable tmp = this.DV.findByName(this.I.toString()); final String eValue = this.E.getValue(this.DV); if (tmp.getT().toString().equals("boolean") && !eValue.equals("V") && !eValue.equals("F")) { this.programa.getCity().parseError( "Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString()); throw new Exception( "Se esperaba un valor booleano en la variable/parametro : " + tmp.getI().toString()); } if (tmp.getT().toString().equals("numero")) { try { System.out.println("e value vale: " + eValue); Integer.parseInt(eValue); } catch (Exception ex) { this.programa.getCity().parseError( "Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString()); throw new Exception( "Se esperaba un valor numerico en la variable/parametro : " + tmp.getI().toString()); } } this.DV.findByName(this.I.toString()).setValue(eValue); } } @Override public Object clone() throws CloneNotSupportedException { final Object obj = null; final Identificador II = new Identificador(this.I.toString()); System.out.println("Intentando clonar expresion en asignacion"); final Expresion EE = (Expresion) this.E.clone(); return new Asignacion(II, EE, this.DV); } @Override public void setDV(final DeclaracionVariable varAST) { this.DV = varAST; } @Override
public void setPrograma(final Programa P) {
0
2023-10-20 15:45:37+00:00
4k
wevez/ClientCoderPack
src/tech/tenamen/client/Client.java
[ { "identifier": "Main", "path": "src/tech/tenamen/Main.java", "snippet": "public class Main {\n public static IDE IDE = new InteliJIDE();\n public static Client client;\n\n public static File WORKING_DIR = new File(System.getProperty(\"user.dir\")),\n ASSETS_DIR = new File(WORKING_DIR, \"ass...
import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import tech.tenamen.Main; import tech.tenamen.property.OS; import tech.tenamen.util.NetUtil; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.*;
3,087
final JsonObject assetIndex = object.getAsJsonObject("assetIndex"); String assetId = null, assetSha1 = null, assetUrl = null; long assetSize = -1, assetTutorialSize = -1; if (assetIndex.has("id")) assetId = assetIndex.get("id").getAsString(); if (assetIndex.has("sha1")) assetSha1 = assetIndex.get("sha1").getAsString(); if (assetIndex.has("url")) assetUrl = assetIndex.get("url").getAsString(); if (assetIndex.has("size")) assetSize = assetIndex.get("size").getAsLong(); if (assetIndex.has("totalSize")) assetTutorialSize = assetIndex.get("totalSize").getAsLong(); if (assetId != null && assetSha1 != null && assetUrl != null && assetSize != -1 && assetTutorialSize != -1) { asset = new Asset(assetId, assetSha1, assetSize, assetTutorialSize, assetUrl); } } // downloads if (object.has("downloads")) { final JsonObject downloads = object.getAsJsonObject("downloads"); if (downloads.has("client")) { final JsonObject client = downloads.getAsJsonObject("client"); new Thread(() -> { NetUtil.download(client.get("url").getAsString(), new File(Main.LIBRARIES_DIR, "client.jar")); }).start(); Main.IDE.getLibraryNames().add("client.jar"); } if (downloads.has("client_mappings")) { final JsonObject clientMappings = downloads.getAsJsonObject("client_mappings"); } if (downloads.has("server")) { final JsonObject server = downloads.getAsJsonObject("server"); } if (downloads.has("server_mappings")) { final JsonObject serverMappings = downloads.getAsJsonObject("server_mappings"); } } // java version if (object.has("javaVersion")) { final JsonObject javaVersion = object.getAsJsonObject("javaVersion"); // if (javaVersion.has("component")) if (javaVersion.has("majorVersion")) this.javaMajorVersion = javaVersion.get("majorVersion").getAsInt(); } if (object.has("libraries")) { final JsonArray libraries = object.getAsJsonArray("libraries"); for (JsonElement e : libraries) { String libName = null, libPath = null, libSha1 = null, libUrl = null; long libSize = -1; final OSRule osRule = new OSRule(); final List<NativeLibrary> nativeLibraries = new ArrayList<>(); final JsonObject library = e.getAsJsonObject(); if (library.has("downloads")) { final JsonObject downloads = library.getAsJsonObject("downloads"); if (downloads.has("artifact")) { final JsonObject artifact = downloads.getAsJsonObject("artifact"); if (artifact.has("path")) libPath = artifact.get("path").getAsString(); if (artifact.has("sha1")) libSha1 = artifact.get("sha1").getAsString(); if (artifact.has("url")) libUrl = artifact.get("url").getAsString(); if (artifact.has("size")) libSize = artifact.get("size").getAsLong(); } if (downloads.has("classifiers")) { final JsonObject classifiers = downloads.getAsJsonObject("classifiers"); final Map<String, JsonObject> nativeObjects = new HashMap<>(); if (classifiers.has("natives-windows")) { nativeObjects.put("natives-windows", classifiers.getAsJsonObject("natives-windows")); } if (classifiers.has("natives-linux")) { nativeObjects.put("natives-linux", classifiers.getAsJsonObject("natives-linux")); } if (classifiers.has("natives-macos")) { nativeObjects.put("natives-macos", classifiers.getAsJsonObject("natives-macos")); } nativeObjects.forEach((k, v) -> { String nativePath = null, nativeSha1 = null, nativeUrl = null; long nativeSize = -1; if (v.has("path")) nativePath = v.get("path").getAsString(); if (v.has("sha1")) nativeSha1 = v.get("sha1").getAsString(); if (v.has("url")) nativeUrl = v.get("url").getAsString(); if (v.has("size")) nativeSize = v.get("size").getAsLong(); if (nativePath != null && nativeSha1 != null && nativeUrl != null && nativeSize != -1) { nativeLibraries.add(new NativeLibrary(k, nativePath, nativeSha1, nativeSize, nativeUrl)); } }); } } if (library.has("name")) { libName = library.get("name").getAsString(); } if (library.has("rules")) { for (JsonElement r : library.getAsJsonArray("rules")) { // os final JsonObject rule = r.getAsJsonObject(); if (rule.has("action")) { final String action = rule.get("action").getAsString(); osRule.setAllow(action.equalsIgnoreCase("allow")); } if (rule.has("os")) { final JsonObject os = rule.getAsJsonObject("os"); if (os.has("name")) osRule.setOSName(os.get("name").getAsString()); } } } if (libName != null && libPath != null && libSha1 != null && libUrl != null && libSize != -1) { this.LIBRARIES.add(new Library(libName, libPath, libSha1, libSize, libUrl, osRule, nativeLibraries)); } } } // release time if (object.has("releaseTime")) { final String releaseTime = object.get("releaseTime").getAsString(); } // time if (object.has("time")) { final String time = object.get("time").getAsString(); } // type if (object.has("type")) { final String type = object.get("type").getAsString(); } Main.IDE.getLibraryNames().add("jsr305-3.0.2.jar"); } public final String getVersionName() { return this.VERSION_NAME; } @Override
package tech.tenamen.client; public class Client implements Downloadable { private String VERSION_NAME; private File JSON_FILE, JAR_FILE; private final List<Library> LIBRARIES = new ArrayList<>(); public Asset asset; private int javaMajorVersion = -1; public Client(final File folder) throws Exception { if (!folder.isFile()) { final List<File> JSON_CANDIDATE = new ArrayList<>(), JAR_CANDIDATE = new ArrayList<>(); // collect json and jar candidates for (final File f : Objects.requireNonNull(folder.listFiles())) { if (!f.isFile()) continue; final String upperFileName = f.getName().toUpperCase(); if (upperFileName.endsWith(".JSON")) { JSON_CANDIDATE.add(f); } else if (upperFileName.endsWith(".JAR")) { JAR_CANDIDATE.add(f); } } for (File jsonCandidate : JSON_CANDIDATE) { final String jsonFileRawName = jsonCandidate.getName(); final String jsonFileName = jsonFileRawName.substring(0, jsonFileRawName.length() - ".json".length()); for (File jarCandidate : JAR_CANDIDATE) { final String jarFileRawName = jarCandidate.getName(); final String jarFileName = jarFileRawName.substring(0, jarFileRawName.length() - ".jar".length()); if (jsonFileName.equalsIgnoreCase(jarFileName)) { this.VERSION_NAME = jsonFileName; this.JAR_FILE = jarCandidate; this.JSON_FILE = jsonCandidate; break; } } if (JSON_FILE != null && JAR_FILE != null && VERSION_NAME != null) break; } if (JSON_FILE == null) throw new Exception("The folder doesn't have json"); if (JAR_FILE == null) throw new Exception("The folder doesn't have jar"); if (VERSION_NAME == null) throw new Exception("The name is null"); } else { throw new Exception("The folder is not folder"); } } public void parseDependencies() { JsonObject object = null; try { object = new GsonBuilder().setPrettyPrinting().create().fromJson(new FileReader(this.JSON_FILE), JsonObject.class); } catch (FileNotFoundException e) { e.printStackTrace(); } if (object == null) return; // arguments if (object.has("arguments")) { // TODO make launch property from json final JsonObject arguments = object.getAsJsonObject("arguments"); } // asset index if (object.has("assetIndex")) { final JsonObject assetIndex = object.getAsJsonObject("assetIndex"); String assetId = null, assetSha1 = null, assetUrl = null; long assetSize = -1, assetTutorialSize = -1; if (assetIndex.has("id")) assetId = assetIndex.get("id").getAsString(); if (assetIndex.has("sha1")) assetSha1 = assetIndex.get("sha1").getAsString(); if (assetIndex.has("url")) assetUrl = assetIndex.get("url").getAsString(); if (assetIndex.has("size")) assetSize = assetIndex.get("size").getAsLong(); if (assetIndex.has("totalSize")) assetTutorialSize = assetIndex.get("totalSize").getAsLong(); if (assetId != null && assetSha1 != null && assetUrl != null && assetSize != -1 && assetTutorialSize != -1) { asset = new Asset(assetId, assetSha1, assetSize, assetTutorialSize, assetUrl); } } // downloads if (object.has("downloads")) { final JsonObject downloads = object.getAsJsonObject("downloads"); if (downloads.has("client")) { final JsonObject client = downloads.getAsJsonObject("client"); new Thread(() -> { NetUtil.download(client.get("url").getAsString(), new File(Main.LIBRARIES_DIR, "client.jar")); }).start(); Main.IDE.getLibraryNames().add("client.jar"); } if (downloads.has("client_mappings")) { final JsonObject clientMappings = downloads.getAsJsonObject("client_mappings"); } if (downloads.has("server")) { final JsonObject server = downloads.getAsJsonObject("server"); } if (downloads.has("server_mappings")) { final JsonObject serverMappings = downloads.getAsJsonObject("server_mappings"); } } // java version if (object.has("javaVersion")) { final JsonObject javaVersion = object.getAsJsonObject("javaVersion"); // if (javaVersion.has("component")) if (javaVersion.has("majorVersion")) this.javaMajorVersion = javaVersion.get("majorVersion").getAsInt(); } if (object.has("libraries")) { final JsonArray libraries = object.getAsJsonArray("libraries"); for (JsonElement e : libraries) { String libName = null, libPath = null, libSha1 = null, libUrl = null; long libSize = -1; final OSRule osRule = new OSRule(); final List<NativeLibrary> nativeLibraries = new ArrayList<>(); final JsonObject library = e.getAsJsonObject(); if (library.has("downloads")) { final JsonObject downloads = library.getAsJsonObject("downloads"); if (downloads.has("artifact")) { final JsonObject artifact = downloads.getAsJsonObject("artifact"); if (artifact.has("path")) libPath = artifact.get("path").getAsString(); if (artifact.has("sha1")) libSha1 = artifact.get("sha1").getAsString(); if (artifact.has("url")) libUrl = artifact.get("url").getAsString(); if (artifact.has("size")) libSize = artifact.get("size").getAsLong(); } if (downloads.has("classifiers")) { final JsonObject classifiers = downloads.getAsJsonObject("classifiers"); final Map<String, JsonObject> nativeObjects = new HashMap<>(); if (classifiers.has("natives-windows")) { nativeObjects.put("natives-windows", classifiers.getAsJsonObject("natives-windows")); } if (classifiers.has("natives-linux")) { nativeObjects.put("natives-linux", classifiers.getAsJsonObject("natives-linux")); } if (classifiers.has("natives-macos")) { nativeObjects.put("natives-macos", classifiers.getAsJsonObject("natives-macos")); } nativeObjects.forEach((k, v) -> { String nativePath = null, nativeSha1 = null, nativeUrl = null; long nativeSize = -1; if (v.has("path")) nativePath = v.get("path").getAsString(); if (v.has("sha1")) nativeSha1 = v.get("sha1").getAsString(); if (v.has("url")) nativeUrl = v.get("url").getAsString(); if (v.has("size")) nativeSize = v.get("size").getAsLong(); if (nativePath != null && nativeSha1 != null && nativeUrl != null && nativeSize != -1) { nativeLibraries.add(new NativeLibrary(k, nativePath, nativeSha1, nativeSize, nativeUrl)); } }); } } if (library.has("name")) { libName = library.get("name").getAsString(); } if (library.has("rules")) { for (JsonElement r : library.getAsJsonArray("rules")) { // os final JsonObject rule = r.getAsJsonObject(); if (rule.has("action")) { final String action = rule.get("action").getAsString(); osRule.setAllow(action.equalsIgnoreCase("allow")); } if (rule.has("os")) { final JsonObject os = rule.getAsJsonObject("os"); if (os.has("name")) osRule.setOSName(os.get("name").getAsString()); } } } if (libName != null && libPath != null && libSha1 != null && libUrl != null && libSize != -1) { this.LIBRARIES.add(new Library(libName, libPath, libSha1, libSize, libUrl, osRule, nativeLibraries)); } } } // release time if (object.has("releaseTime")) { final String releaseTime = object.get("releaseTime").getAsString(); } // time if (object.has("time")) { final String time = object.get("time").getAsString(); } // type if (object.has("type")) { final String type = object.get("type").getAsString(); } Main.IDE.getLibraryNames().add("jsr305-3.0.2.jar"); } public final String getVersionName() { return this.VERSION_NAME; } @Override
public void download(OS os) {
1
2023-10-20 06:56:19+00:00
4k