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
HuXin0817/shop_api
framework/src/main/java/cn/lili/modules/verification/SliderImageUtil.java
[ { "identifier": "Base64DecodeMultipartFile", "path": "framework/src/main/java/cn/lili/common/utils/Base64DecodeMultipartFile.java", "snippet": "@Slf4j\npublic class Base64DecodeMultipartFile implements MultipartFile {\n\n private final byte[] imgContent;\n private final String header;\n\n public Base64DecodeMultipartFile(byte[] imgContent, String header) {\n this.imgContent = imgContent;\n this.header = header.split(\";\")[0];\n }\n\n @Override\n public String getName() {\n return System.currentTimeMillis() + Math.random() + \".\" + header.split(\"/\")[1];\n }\n\n @Override\n public String getOriginalFilename() {\n return System.currentTimeMillis() + (int) Math.random() * 10000 + \".\" + header.split(\"/\")[1];\n }\n\n @Override\n public String getContentType() {\n return header.split(\":\")[1];\n }\n\n @Override\n public boolean isEmpty() {\n return imgContent == null || imgContent.length == 0;\n }\n\n @Override\n public long getSize() {\n return imgContent.length;\n }\n\n @Override\n public byte[] getBytes() throws IOException {\n return imgContent;\n }\n\n @Override\n public InputStream getInputStream() {\n return new ByteArrayInputStream(imgContent);\n }\n\n @Override\n public void transferTo(File dest) throws IOException, IllegalStateException {\n OutputStream stream = null;\n try {\n stream = new FileOutputStream(dest);\n stream.write(imgContent);\n } catch (IOException e) {\n log.error(\"transferTo错误\", e);\n } finally {\n assert stream != null;\n stream.close();\n }\n }\n\n\n public static MultipartFile base64Convert(String base64) {\n\n String[] baseStrs = base64.split(\",\");\n Decoder decoder = Base64.getDecoder();\n byte[] b = decoder.decode(baseStrs[1]);\n\n for (int i = 0; i < b.length; ++i) {\n if (b[i] < 0) {\n b[i] += 256;\n }\n }\n return new Base64DecodeMultipartFile(b, baseStrs[0]);\n }\n\n\n public static InputStream base64ToInputStream(String base64) {\n ByteArrayInputStream stream = null;\n try {\n byte[] bytes = Base64.getDecoder().decode(base64);\n stream = new ByteArrayInputStream(bytes);\n } catch (Exception e) {\n log.error(\"base64ToInputStream错误\", e);\n }\n return stream;\n }\n\n public static String inputStreamToStream(InputStream in) {\n byte[] data = null;\n //读取图片字节数组\n try {\n ByteArrayOutputStream swapStream = new ByteArrayOutputStream();\n byte[] buff = new byte[100];\n int rc = 0;\n while ((rc = in.read(buff, 0, 100)) > 0) {\n swapStream.write(buff, 0, rc);\n }\n data = swapStream.toByteArray();\n } catch (IOException e) {\n log.error(\"转码错误\", e);\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (IOException e) {\n log.error(\"inputStreamToStream错误\", e);\n }\n }\n }\n return Base64.getEncoder().encodeToString(data);\n }\n}" }, { "identifier": "SerializableStream", "path": "framework/src/main/java/cn/lili/common/vo/SerializableStream.java", "snippet": "@Data\n@NoArgsConstructor\npublic class SerializableStream {\n private String base64;\n\n public SerializableStream(InputStream inputStream) {\n this.base64 = Base64DecodeMultipartFile.inputStreamToStream(inputStream);\n }\n\n}" } ]
import cn.lili.common.utils.Base64DecodeMultipartFile; import cn.lili.common.vo.SerializableStream; import lombok.extern.slf4j.Slf4j; import org.springframework.util.Base64Utils; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; import java.util.Random;
1,237
package cn.lili.modules.verification; /** * 验证码工具 * * @author Chopper * @version v4.0 * @since 2020/11/17 14:34 */ @Slf4j public class SliderImageUtil { private static final int BOLD = 5; private static final String IMG_FILE_TYPE = "jpg"; private static final String TEMP_IMG_FILE_TYPE = "png"; /** * 根据模板切图 * * @param sliderFile 滑块 * @param originalFile 原图 * @param watermark 水印 * @param interfereNum 干扰选项 * @return 滑块参数 * @throws Exception sliderFile, originalFile */ public static Map<String, Object> pictureTemplatesCut( SerializableStream sliderFile, SerializableStream interfereSliderFile, SerializableStream originalFile, String watermark, Integer interfereNum) throws Exception { Random random = new Random(); Map<String, Object> pictureMap = new HashMap<>(16); //拼图
package cn.lili.modules.verification; /** * 验证码工具 * * @author Chopper * @version v4.0 * @since 2020/11/17 14:34 */ @Slf4j public class SliderImageUtil { private static final int BOLD = 5; private static final String IMG_FILE_TYPE = "jpg"; private static final String TEMP_IMG_FILE_TYPE = "png"; /** * 根据模板切图 * * @param sliderFile 滑块 * @param originalFile 原图 * @param watermark 水印 * @param interfereNum 干扰选项 * @return 滑块参数 * @throws Exception sliderFile, originalFile */ public static Map<String, Object> pictureTemplatesCut( SerializableStream sliderFile, SerializableStream interfereSliderFile, SerializableStream originalFile, String watermark, Integer interfereNum) throws Exception { Random random = new Random(); Map<String, Object> pictureMap = new HashMap<>(16); //拼图
BufferedImage sliderImage = ImageIO.read(Base64DecodeMultipartFile.base64ToInputStream(sliderFile.getBase64()));
0
2023-12-24 19:45:18+00:00
2k
khoa070104/StudentManagerJava
src/view/StudentManagement.java
[ { "identifier": "Inputter", "path": "src/inputter/Inputter.java", "snippet": "public class Inputter {\n private static Scanner sc = new Scanner(System.in);\n\n public static String getInputString(String prompt) {\n System.out.print(prompt);\n return sc.nextLine();\n }\n\n public static int getInputInt(String prompt) {\n while (true) {\n try {\n System.out.print(prompt);\n return Integer.parseInt(sc.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Invalid input. Please enter a valid integer.\");\n }\n }\n }\n\n public static double getInputDouble(String prompt) {\n while (true) {\n try {\n System.out.print(prompt);\n return Double.parseDouble(sc.nextLine());\n } catch (NumberFormatException e) {\n System.out.println(\"Invalid input. Please enter a valid number.\");\n }\n }\n }\n public static String inputStr(String msg, String pattern) {\n while (true) {\n System.out.print(msg);\n String input = sc.nextLine().trim();\n if (Pattern.matches(pattern, input)) \n return input;\n else\n System.out.println(\"Invalid format. Please enter a valid value.\");\n }\n }\n}" }, { "identifier": "StudentList", "path": "src/model/StudentList.java", "snippet": "public class StudentList extends ArrayList<Student> {\n\n // this \n public void listStudent() {\n Collections.sort(this, (o1,o2)->o1.getStudentID().compareTo(o2.getStudentID()));\n System.out.println(\"List:\");\n for (Student t : this) {\n System.out.println(t.toString());\n }\n }\n\n public boolean readTextFile(String filename) {\n File f = new File(filename);\n if (!f.exists()) {\n return false;\n }\n try ( Scanner sc = new Scanner(f)) {\n while (sc.hasNext()) {\n String part[] = sc.nextLine().split(\",\");\n if (part.length == 6) {\n String id = part[0].substring(11);\n String fname = part[1].substring(11).trim();\n String lname = part[2].substring(10).trim();\n String age = part[3].substring(4).trim();\n String d = part[4].substring(6).trim();\n String gen = part[5].substring(8).trim();\n Student s = new Student(id, fname, lname, gen, d);\n this.add(s);\n }\n }\n\n } catch (Exception e) {\n return false;\n }\n return true;\n }\n public int searchId(String id){\n for (int i = 0; i < this.size(); i++) {\n if(this.get(i).getStudentID().equalsIgnoreCase(id))\n return i;\n }\n return -1;\n }\n\n public boolean seachIf(Predicate<Student> predicate) {\n for (Student p : this) {\n if (predicate.test(p)) {\n System.out.println(p.toString());\n return true;\n }\n }\n return false;\n }\n \n public boolean addNewStudent(){\n String id = Inputter.getInputString(\"Enter ID: \");\n if(searchId(id)!= -1)\n return false;\n \n String fname = Inputter.getInputString(\"Enter FirstName: \");\n String lname = Inputter.getInputString(\"Enter FirstName: \");\n String dob = Inputter.inputStr(\"Enter DOB: \", \"dd/MM/yyyy\");\n String gen = Inputter.getInputString(\"Enter gender: \");\n this.add(new Student(id, fname, lname, gen, dob));\n \n return true;\n }\n \n}" } ]
import inputter.Inputter; import model.StudentList;
1,008
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package view; /** * * @author Khoa Bug */ public class StudentManagement { public static void menu() { System.out.println("1. List\n2. Search\n3.Add new\n4.Exit"); } public static void menu_search() { System.out.println("1.Search Gender\n2.Search ID"); } public static void main(String[] args) { StudentManagement s11= new StudentManagement();
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package view; /** * * @author Khoa Bug */ public class StudentManagement { public static void menu() { System.out.println("1. List\n2. Search\n3.Add new\n4.Exit"); } public static void menu_search() { System.out.println("1.Search Gender\n2.Search ID"); } public static void main(String[] args) { StudentManagement s11= new StudentManagement();
StudentList s = new StudentList();
1
2023-12-25 16:57:07+00:00
2k
MuskStark/EasyECharts
src/main/java/com/github/muskstark/echart/attribute/series/PieSeries.java
[ { "identifier": "Grid", "path": "src/main/java/com/github/muskstark/echart/attribute/Grid.java", "snippet": "@Getter\npublic class Grid implements Serializable {\n\n private String id;\n private Boolean show;\n private Double zLevel;\n private Double z;\n private Object left;\n private Object right;\n private Object top;\n private Object bottom;\n private Object height;\n private Object width;\n private Boolean containLabel;\n private String backgroundColor;\n\n\n public Grid id(String id) {\n this.id = id;\n return this;\n }\n\n public Grid show(Boolean show) {\n this.show = show;\n return this;\n }\n\n public Grid zLevel(Double zLevel) {\n this.zLevel = zLevel;\n return this;\n }\n\n public Grid z(Double z) {\n this.z = z;\n return this;\n }\n\n public Grid left(Object left) {\n if(left instanceof String || left instanceof Double){\n this.left = left;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Grid right(Object right) {\n if(right instanceof String || right instanceof Double){\n this.right = right;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Grid top(Object top){\n if(top instanceof String || top instanceof Double){\n this.top = top;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Grid bottom(Object bottom){\n if(bottom instanceof String || bottom instanceof Double){\n this.bottom = bottom;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Grid height(Object height){\n if(height instanceof String || height instanceof Double){\n this.height = height;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Grid width(Object width) {\n if(width instanceof String || width instanceof Double){\n this.width = width;\n }else {\n throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);\n }\n return this;\n }\n\n public Grid containLabel(Boolean containLabel) {\n this.containLabel = containLabel;\n return this;\n }\n\n public Grid backgroundColor(String backgroundColor) {\n this.backgroundColor = backgroundColor;\n return this;\n }\n\n\n}" }, { "identifier": "EChartsExceptionsEnum", "path": "src/main/java/com/github/muskstark/echart/enums/EChartsExceptionsEnum.java", "snippet": "@Getter\npublic enum EChartsExceptionsEnum {\n\n ECharts_Invalid_TypeError(\"方法传入的参数为不受支持的类型\")\n ;\n private String message;\n\n private EChartsExceptionsEnum(String message) {\n this.message = message;\n }\n}" }, { "identifier": "EChartsException", "path": "src/main/java/com/github/muskstark/echart/exception/EChartsException.java", "snippet": "public class EChartsException extends RuntimeException {\n public EChartsException(EChartsExceptionsEnum exceptions) {\n super(exceptions.getMessage());\n }\n}" } ]
import com.github.muskstark.echart.attribute.Grid; import com.github.muskstark.echart.enums.EChartsExceptionsEnum; import com.github.muskstark.echart.exception.EChartsException; import lombok.Getter;
1,233
package com.github.muskstark.echart.attribute.series; @Getter public class PieSeries { private Double geoIndex; private Double calendarIndex; private Boolean selectedMode; private Double selectedOffset; private Boolean clockwise; private Double startAngle; private String minAngle; private Boolean minShowLabelAngle; private Object roseType; private Boolean avoidLabelOverlap; private Boolean stillShowZeroSum; private Double percentPrecision; private String cursor; private Object left; private Object right; private Object top; private Object bottom; private Object height; private Object width; private Boolean showEmptyCircle; public PieSeries geoIndex(Double geoIndex){ this.geoIndex = geoIndex; return this; } public PieSeries calendarIndex(Double calendarIndex){ this.calendarIndex = calendarIndex; return this; } public PieSeries selectedMode(Boolean selectedMode){ this.selectedMode = selectedMode; return this; } public PieSeries selectedOffset(Double selectedOffset){ this.selectedOffset = selectedOffset; return this; } public PieSeries clockwise(Boolean clockwise){ this.clockwise = clockwise; return this; } public PieSeries startAngle(Double startAngle){ this.startAngle = startAngle; return this; } public PieSeries minAngle(String minAngle){ this.minAngle = minAngle; return this; } public PieSeries minShowLabelAngle(Boolean minShowLabelAngle){ this.minShowLabelAngle = minShowLabelAngle; return this; } public PieSeries roseType(Object roseType){ if(!(roseType instanceof String) || !(roseType instanceof Boolean)){
package com.github.muskstark.echart.attribute.series; @Getter public class PieSeries { private Double geoIndex; private Double calendarIndex; private Boolean selectedMode; private Double selectedOffset; private Boolean clockwise; private Double startAngle; private String minAngle; private Boolean minShowLabelAngle; private Object roseType; private Boolean avoidLabelOverlap; private Boolean stillShowZeroSum; private Double percentPrecision; private String cursor; private Object left; private Object right; private Object top; private Object bottom; private Object height; private Object width; private Boolean showEmptyCircle; public PieSeries geoIndex(Double geoIndex){ this.geoIndex = geoIndex; return this; } public PieSeries calendarIndex(Double calendarIndex){ this.calendarIndex = calendarIndex; return this; } public PieSeries selectedMode(Boolean selectedMode){ this.selectedMode = selectedMode; return this; } public PieSeries selectedOffset(Double selectedOffset){ this.selectedOffset = selectedOffset; return this; } public PieSeries clockwise(Boolean clockwise){ this.clockwise = clockwise; return this; } public PieSeries startAngle(Double startAngle){ this.startAngle = startAngle; return this; } public PieSeries minAngle(String minAngle){ this.minAngle = minAngle; return this; } public PieSeries minShowLabelAngle(Boolean minShowLabelAngle){ this.minShowLabelAngle = minShowLabelAngle; return this; } public PieSeries roseType(Object roseType){ if(!(roseType instanceof String) || !(roseType instanceof Boolean)){
throw new EChartsException(EChartsExceptionsEnum.ECharts_Invalid_TypeError);
2
2023-12-25 08:03:42+00:00
2k
thanosmoschou/SpringBootPractise
databasewithjpa/src/test/java/com/thanos/databasewithjpa/services/impl/UserServiceImplTest.java
[ { "identifier": "User", "path": "databasewithjpa/src/main/java/com/thanos/databasewithjpa/domain/User.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\n@Table(name = \"users\")\npublic class User \n{\n @Id\n private String name;\n private int age;\n\n public void printInfo()\n {\n \tSystem.out.println(\"Name: \" + this.name + \" Age: \" + this.age);\n }\n}" }, { "identifier": "UserRepository", "path": "databasewithjpa/src/main/java/com/thanos/databasewithjpa/repositories/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository extends JpaRepository<User, String>\n{\n\t\n} " } ]
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.mockito.Mockito.when; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.thanos.databasewithjpa.domain.User; import com.thanos.databasewithjpa.repositories.UserRepository;
872
package com.thanos.databasewithjpa.services.impl; /* * Mockito is a powerful mocking framework for Java applications. * It allows you to create mock objects, define their behavior, and * verify interactions. To mock dependencies in your unit tests, use * Mockito’s @Mock annotation and @InjectMocks annotation to inject the * mocks into the class under test. * * Why Mock? * * Why should we use a mock instead of a real service object in a test? * Imagine the service implementation above has a dependency to a database or * some other third-party system. We don’t want to have our test run against the * database. If the database isn’t available, the test will fail even though our * system under test might be completely bug-free. The more dependencies we add in * a test, the more reasons a test has to fail. And most of those reasons will be * the wrong ones. If we use a mock instead, we can mock all those potential * failures away. * * Aside from reducing failures, mocking also reduces our tests' complexity and * thus saves us some effort. It takes a lot of boilerplate code to set up a * whole network of correctly-initialized objects to be used in a test. * Using mocks, we only have to “instantiate” one mock instead of a whole * rat-tail of objects the real object might need to be instantiated. * * In summary, we want to move from a potentially complex, slow, and * flaky integration test towards a simple, fast, and reliable unit test. * * As a mocking framework, we’ll use Mockito, since it’s well-rounded, * well-established, and well-integrated into Spring Boot. * * Mockito provides some handy annotations that reduce the manual work * of creating mock instances and passing them into the object we’re about to test. * * With JUnit Jupiter, we need to apply the MockitoExtension to our test: * * We can then use the @Mock and @InjectMocks annotations on fields of the test. * * Fields annotated with @Mock will then automatically be initialized with a * mock instance of their type, just like as we would call Mockito.mock() by hand. * * Mockito will then try to instantiate fields annotated with @InjectMocks by * passing all mocks into a constructor. Note that we need to provide such a * constructor for Mockito to work reliably. If Mockito doesn’t find a constructor, * it will try setter injection or field injection, but the cleanest way is still * a constructor. You can read about the algorithm behind this in Mockito’s Javadoc. * */ @ExtendWith(MockitoExtension.class) //Enable Mockito support public class UserServiceImplTest { @Mock
package com.thanos.databasewithjpa.services.impl; /* * Mockito is a powerful mocking framework for Java applications. * It allows you to create mock objects, define their behavior, and * verify interactions. To mock dependencies in your unit tests, use * Mockito’s @Mock annotation and @InjectMocks annotation to inject the * mocks into the class under test. * * Why Mock? * * Why should we use a mock instead of a real service object in a test? * Imagine the service implementation above has a dependency to a database or * some other third-party system. We don’t want to have our test run against the * database. If the database isn’t available, the test will fail even though our * system under test might be completely bug-free. The more dependencies we add in * a test, the more reasons a test has to fail. And most of those reasons will be * the wrong ones. If we use a mock instead, we can mock all those potential * failures away. * * Aside from reducing failures, mocking also reduces our tests' complexity and * thus saves us some effort. It takes a lot of boilerplate code to set up a * whole network of correctly-initialized objects to be used in a test. * Using mocks, we only have to “instantiate” one mock instead of a whole * rat-tail of objects the real object might need to be instantiated. * * In summary, we want to move from a potentially complex, slow, and * flaky integration test towards a simple, fast, and reliable unit test. * * As a mocking framework, we’ll use Mockito, since it’s well-rounded, * well-established, and well-integrated into Spring Boot. * * Mockito provides some handy annotations that reduce the manual work * of creating mock instances and passing them into the object we’re about to test. * * With JUnit Jupiter, we need to apply the MockitoExtension to our test: * * We can then use the @Mock and @InjectMocks annotations on fields of the test. * * Fields annotated with @Mock will then automatically be initialized with a * mock instance of their type, just like as we would call Mockito.mock() by hand. * * Mockito will then try to instantiate fields annotated with @InjectMocks by * passing all mocks into a constructor. Note that we need to provide such a * constructor for Mockito to work reliably. If Mockito doesn’t find a constructor, * it will try setter injection or field injection, but the cleanest way is still * a constructor. You can read about the algorithm behind this in Mockito’s Javadoc. * */ @ExtendWith(MockitoExtension.class) //Enable Mockito support public class UserServiceImplTest { @Mock
private UserRepository userRepository; //a fake repository for the test cases
1
2023-12-31 17:29:44+00:00
2k
echothreellc/kafka-connector
Kafka/KafkaExample/src/main/java/fish/payara/cloud/connectors/kafka/example/SendKafkaMessage.java
[ { "identifier": "KafkaConnection", "path": "Kafka/KafkaJCAAPI/src/main/java/fish/payara/cloud/connectors/kafka/api/KafkaConnection.java", "snippet": "public interface KafkaConnection extends AutoCloseable {\n \n public Future<RecordMetadata> send(ProducerRecord record) throws ResourceException;\n \n public Future<RecordMetadata> send(ProducerRecord record, Callback callback) throws ResourceException;\n \n public void flush() throws ResourceException;\n \n List<PartitionInfo> partitionsFor(String topic) throws ResourceException;\n \n public java.util.Map<MetricName,? extends Metric> metrics​() throws ResourceException;\n \n}" }, { "identifier": "KafkaConnectionFactory", "path": "Kafka/KafkaJCAAPI/src/main/java/fish/payara/cloud/connectors/kafka/api/KafkaConnectionFactory.java", "snippet": "public interface KafkaConnectionFactory {\n \n KafkaConnection createConnection() throws ResourceException;\n\n KafkaConnection createConnection(ConnectionSpec spec) throws ResourceException;\n\n \n}" } ]
import fish.payara.cloud.connectors.kafka.api.KafkaConnection; import fish.payara.cloud.connectors.kafka.api.KafkaConnectionFactory; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Resource; import javax.ejb.Schedule; import javax.ejb.Stateless; import javax.resource.ConnectionFactoryDefinition; import javax.resource.spi.TransactionSupport.TransactionSupportLevel; import org.apache.kafka.clients.producer.ProducerRecord;
904
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2017 Payara Foundation and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://github.com/payara/Payara/blob/master/LICENSE.txt * See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/legal/LICENSE.txt. * * GPL Classpath Exception: * The Payara Foundation designates this particular file as subject to the "Classpath" * exception as provided by the Payara Foundation in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package fish.payara.cloud.connectors.kafka.example; /** * * @author Steve Millidge (Payara Foundation) */ @ConnectionFactoryDefinition(name = "java:comp/env/KafkaConnectionFactory", description = "Kafka Conn Factory", interfaceName = "fish.payara.cloud.connectors.kafka.api.KafkaConnectionFactory", resourceAdapter = "kafka-rar-1.0.0-SNAPSHOT", minPoolSize = 2, maxPoolSize = 2, transactionSupport = TransactionSupportLevel.NoTransaction, properties = {"acks=all" }) @Stateless public class SendKafkaMessage { @Resource(lookup="java:comp/env/KafkaConnectionFactory")
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2017 Payara Foundation and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://github.com/payara/Payara/blob/master/LICENSE.txt * See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/legal/LICENSE.txt. * * GPL Classpath Exception: * The Payara Foundation designates this particular file as subject to the "Classpath" * exception as provided by the Payara Foundation in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package fish.payara.cloud.connectors.kafka.example; /** * * @author Steve Millidge (Payara Foundation) */ @ConnectionFactoryDefinition(name = "java:comp/env/KafkaConnectionFactory", description = "Kafka Conn Factory", interfaceName = "fish.payara.cloud.connectors.kafka.api.KafkaConnectionFactory", resourceAdapter = "kafka-rar-1.0.0-SNAPSHOT", minPoolSize = 2, maxPoolSize = 2, transactionSupport = TransactionSupportLevel.NoTransaction, properties = {"acks=all" }) @Stateless public class SendKafkaMessage { @Resource(lookup="java:comp/env/KafkaConnectionFactory")
KafkaConnectionFactory factory;
1
2023-12-24 23:25:44+00:00
2k
CompeyDev/stinky-mod
src/main/java/xyz/devcomp/mixin/ServerPlayerMixin.java
[ { "identifier": "Stinky", "path": "src/main/java/xyz/devcomp/Stinky.java", "snippet": "public class Stinky implements ModInitializer {\n\t// This logger is used to write text to the console and the log file.\n\t// It is considered best practice to use your mod id as the logger's name.\n\t// That way, it's clear which mod wrote info, warnings, and errors.\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(\"stinky\");\n\tpublic static final ConfigModel Config = new ConfigHandler().getConfig();\n\t// public static final ResourceLocation EC_SOUND_ID = new ResourceLocation(\"stinky:ping\");\n // public static SoundEvent EC_SOUND_EVENT = SoundEvent.createVariableRangeEvent(EC_SOUND_ID);\n\n\t@Override\n\tpublic void onInitialize() {\n\t\t// This code runs as soon as Minecraft is in a mod-load-ready state.\n\t\t// However, some things (like resources) may still be uninitialized.\n\t\t// Proceed with mild caution.\n\n\t\tLOGGER.info(\"Hello from Stinky!\");\n\t\t\n\t\tServerMessageEvents.CHAT_MESSAGE.register((PlayerChatMessage msg, ServerPlayer plr, ChatType.Bound bound) -> {\n\t\t\t// NOTE: This makes this command dysfunctional on offline mode servers\n\t\t\tString msgString = msg.signedContent();\n\t\t\t\n\t\t\tif (msgString.trim().equalsIgnoreCase(\";ec\")) {\n\t\t\t\t// We're setting the health to 0, instead of plr.kill(), because this \n\t\t\t\t// abuses a flaw in the graves VanillaTweaks datapack to make the player\n\t\t\t\t// respawn without creating a grave or losing their items\n\t\t\t\t\n\t\t\t\t// TODO: Play stinky:ping sound\n\t\t\t\tplr.setHealth(0);\n\t\t\t}\n\t\t});\n\n\n\t\t\n\t}\n}" }, { "identifier": "DeathStrings", "path": "src/main/java/xyz/devcomp/util/Strings.java", "snippet": "public class DeathStrings {\n public static String[] Arrow = {\n \"&cplayer&7 was shot by &ckiller\",\n \"&cplayer&7 didnt survive detroit\",\n \"&cplayer&7 had died to an arrow from &ckiller\",\n \"&cplayer&7 was shot dead with &ckiller's &cweapon\",\n };\n public static String[] Melee = {\n \"&cplayer&7 was slain by &ckiller's &cweapon\",\n \"&ckiller&7 violently murdered &cplayer with a &cweapon\",\n \"&cplayer&7 got fucking killed by &ckiller's &cweapon\",\n \"&cplayer&7 got stabbed by &ckiller's &cweapon\",\n \"&ckiller&7 turned off &cplayer's life support\"\n };\n public static String[] FallDamage = {\n \"&cplayer&7 jumped\",\n \"&cplayer&7 installed proprietary spyware\",\n \"&cplayer&7 is not very intelligent\"\n };\n public static String[] Suicide = {\n \"&cplayer&7 ate glue\",\n \"&cplayer&7 jumped\",\n \"&cplayer&7 committed suicide\"\n };\n public static String[] Burned = {\n \"&cplayer&7 used too much icyhot\",\n \"&cplayer&7 is a complete dumbass\",\n \"&cplayer&7 is toast\",\n };\n public static String[] Potion = {\n \"&cplayer&7 died to &ckiller's potion\"\n };\n public static String[] Drowned = {\n \"&cplayer&7 forgot to breathe\",\n \"&cplayer&7 drowned\",\n \"&cplayer&7 drank too much water\",\n \"&cplayer&7 depleted their oxygen\",\n };\n public static String[] Suffocation = {\n \"&cplayer&7 got stuck in a wall\"\n };\n public static String[] Mob = {\n \"&cplayer&7 was killed by a &ckiller\"\n };\n public static String[] Wildcard = {\n \"&cplayer&7 was killed\",\n \"&cplayer&7 died\",\n \"&cplayer&7? &cplayer&7?? &cplayer&7!!!!!\"\n };\n public static String[] Explosion = {\n \"&cplayer&7 was blown by &ckiller\",\n \"&cplayer&7 blew up\",\n \"&cplayer&7 exploded\",\n };\n public static String[] Starved = {\n \"&cplayer&7 forgot to eat\",\n \"&cplayer&7 starved to death\"\n };\n}" } ]
import java.util.Map; import xyz.devcomp.Stinky; import xyz.devcomp.util.Strings.DeathStrings; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import com.mojang.authlib.GameProfile; import net.minecraft.core.BlockPos; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerPlayer; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.damagesource.DamageType; import net.minecraft.world.damagesource.DamageTypes; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level;
1,344
package xyz.devcomp.mixin; @Mixin(ServerPlayer.class) public abstract class ServerPlayerMixin extends Player { public ServerPlayerMixin(Level level, BlockPos blockPos, float f, GameProfile gameProfile) { super(level, blockPos, f, gameProfile); } @Inject(method = "die(Lnet/minecraft/world/damagesource/DamageSource;)V", at = @At("TAIL")) private void broadcastDeathMessage(DamageSource damageSource, CallbackInfo ci) { ServerPlayer victim = (ServerPlayer) (Object) this; MinecraftServer server = this.getServer(); if (damageSource.getDirectEntity() instanceof ServerPlayer aggressor) { if (aggressor == victim) { // suicide balls server.sendSystemMessage(
package xyz.devcomp.mixin; @Mixin(ServerPlayer.class) public abstract class ServerPlayerMixin extends Player { public ServerPlayerMixin(Level level, BlockPos blockPos, float f, GameProfile gameProfile) { super(level, blockPos, f, gameProfile); } @Inject(method = "die(Lnet/minecraft/world/damagesource/DamageSource;)V", at = @At("TAIL")) private void broadcastDeathMessage(DamageSource damageSource, CallbackInfo ci) { ServerPlayer victim = (ServerPlayer) (Object) this; MinecraftServer server = this.getServer(); if (damageSource.getDirectEntity() instanceof ServerPlayer aggressor) { if (aggressor == victim) { // suicide balls server.sendSystemMessage(
Component.literal(DeathStrings.Suicide[(int) (Math.random() * DeathStrings.Suicide.length)]));
1
2023-12-26 16:23:46+00:00
2k
xyzell/OOP_UAS
Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/service/impl/GuestServiceImpl.java
[ { "identifier": "Account", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/pojo/Account.java", "snippet": "public class Account {\n private String idAccount;\n private String email;\n private String username;\n private String password;\n private String level;\n\n public Account() {\n }\n\n public String getIdAccount() {\n return idAccount;\n }\n\n public void setIdAccount(String idAccount) {\n this.idAccount = idAccount;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getLevel() {\n return level;\n }\n\n public void setLevel(String level) {\n this.level = level;\n }\n \n \n \n}" }, { "identifier": "Guest", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/pojo/Guest.java", "snippet": "public class Guest {\n private String ID_Guest;\n private String guest_name;\n private String guest_gender;\n private String guest_pnumber;\n private int guest_age;\n private boolean loginStatus;\n private Account account;\n\n public Guest() {\n }\n\n public String getID_Guest() {\n return ID_Guest;\n }\n\n public void setID_Guest(String ID_Guest) {\n this.ID_Guest = ID_Guest;\n }\n\n public String getGuest_name() {\n return guest_name;\n }\n\n public void setGuest_name(String guest_name) {\n this.guest_name = guest_name;\n }\n\n public String getGuest_gender() {\n return guest_gender;\n }\n\n public void setGuest_gender(String guest_gender) {\n this.guest_gender = guest_gender;\n }\n\n public String getGuest_pnumber() {\n return guest_pnumber;\n }\n\n public void setGuest_pnumber(String guest_pnumber) {\n this.guest_pnumber = guest_pnumber;\n }\n\n public int getGuest_age() {\n return guest_age;\n }\n\n public void setGuest_age(int guest_age) {\n this.guest_age = guest_age;\n }\n\n public boolean isLoginStatus() {\n return loginStatus;\n }\n\n public void setLoginStatus(boolean loginStatus) {\n this.loginStatus = loginStatus;\n }\n\n public Account getAccount() {\n return account;\n }\n\n public void setAccount(Account account) {\n this.account = account;\n }\n\n \n}" }, { "identifier": "GuestService", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/service/GuestService.java", "snippet": "public interface GuestService extends CrudRepository<Guest, Integer>{\n \n}" }, { "identifier": "ConnectionManager", "path": "Hotel_TA/src/main/java/com/itenas/oop/org/uashotel/utilities/ConnectionManager.java", "snippet": "public class ConnectionManager {\n private String DB_URL = \"jdbc:mysql://localhost:3306/hotel1\";\n private String username;\n private String password;\n private Connection connection;\n\n \n\n public ConnectionManager() {\n this.username = \"root\";\n this.password = \"basdat2022\";\n }\n\n public String getDB_URL() {\n return DB_URL;\n }\n\n public String getUsername() {\n return username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public Connection connect() {\n if (connection == null) {\n try {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(getDB_URL(), \n getUsername(), getPassword());\n } catch (ClassNotFoundException | SQLException ex) {\n Logger.getLogger(ConnectionManager.class.getName())\n .log(Level.SEVERE, null, ex);\n }\n }\n return connection;\n }\n \n public Connection disconnect() {\n try {\n connection.close();\n } catch (SQLException ex) {\n Logger.getLogger(ConnectionManager.class.getName())\n .log(Level.SEVERE, null, ex);\n }\n return connection;\n }\n}" } ]
import com.itenas.oop.org.uashotel.pojo.Account; import com.itenas.oop.org.uashotel.pojo.Guest; import com.itenas.oop.org.uashotel.service.GuestService; import com.itenas.oop.org.uashotel.utilities.ConnectionManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List;
1,271
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.itenas.oop.org.uashotel.service.impl; /** * * @author User */ public class GuestServiceImpl implements GuestService{ private ConnectionManager conMan; private Connection conn; Statement stmt; ResultSet rs; @Override
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package com.itenas.oop.org.uashotel.service.impl; /** * * @author User */ public class GuestServiceImpl implements GuestService{ private ConnectionManager conMan; private Connection conn; Statement stmt; ResultSet rs; @Override
public List<Guest> findAll() {
1
2023-12-24 11:39:51+00:00
2k
LawMashira/Springboot-3-Security-Registration-and-Login-
Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/controller/UserController.java
[ { "identifier": "User", "path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/entity/User.java", "snippet": "@Table(name = \"ASPIRING_STUDENTS_TB\")\n@Entity\n@Setter\n@Getter\n@NoArgsConstructor\npublic class User {\n /*@Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String name;\n private String email;\n private String password;\n\n @ManyToMany(fetch = FetchType.EAGER,cascade = {CascadeType.PERSIST,CascadeType.MERGE,CascadeType.DETACH})\n @JoinTable(name = \"user_roles\",\n joinColumns =@JoinColumn(name = \"user_id\",referencedColumnName = \"id\"),\n inverseJoinColumns = @JoinColumn(name = \"role_id\",referencedColumnName = \"id\"))\n private Collection<Role> roles = new HashSet<>();*/\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String firstName;\n private String lastName;\n private String email;\n private String password;\n @ManyToMany(fetch = FetchType.EAGER,\n cascade = {CascadeType.PERSIST,\n CascadeType.MERGE, CascadeType.DETACH})\n @JoinTable(name = \"user_roles\",\n joinColumns = @JoinColumn(name = \"user_id\", referencedColumnName = \"id\"),\n inverseJoinColumns = @JoinColumn(name = \"role_id\", referencedColumnName = \"id\"))\n private Collection<Role> roles = new HashSet<>();\n\n\n}" }, { "identifier": "UserNotFoundException", "path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/exception/UserNotFoundException.java", "snippet": "public class UserNotFoundException extends RuntimeException {\n public UserNotFoundException(String message) {\n super(message);\n }\n}" }, { "identifier": "UserService", "path": "Student-Online-Admission-System/src/main/java/com/student/online/admission/system/rd/year/service/UserService.java", "snippet": "public interface UserService {\n User registerUser(User user) throws UserAlreadyExistsException;\n List<User> getUsers();\n\n void deleteUser (String email);\n User getUser(String email) throws UserNotFoundException;\n}" } ]
import com.student.online.admission.system.rd.year.entity.User; import com.student.online.admission.system.rd.year.exception.UserNotFoundException; import com.student.online.admission.system.rd.year.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List;
834
package com.student.online.admission.system.rd.year.controller; @RestController @RequestMapping("/users") @RequiredArgsConstructor public class UserController { /* @Autowired private final UserService userService; @GetMapping("/all") public ResponseEntity<List<User>> getUsers() { return new ResponseEntity<>(userService.getUsers(), HttpStatus.FOUND); } @GetMapping("/{email}") public ResponseEntity<?> getUserByEmail(@PathVariable("email") String email) { try { User theUser= userService.getUser(email); return ResponseEntity.ok(theUser); } catch (UserNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); }catch (Exception e){ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error in fetching the user"); } } @DeleteMapping("/delete/{userId}") public ResponseEntity <String> deleteUser(@PathVariable("userId") String email){ try { userService.deleteUser(email); return ResponseEntity.ok("User deleted "); }catch (UserNotFoundException e){ return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); }catch ( Exception e ){ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error in deleting the user"); } } */ //********************************************************************
package com.student.online.admission.system.rd.year.controller; @RestController @RequestMapping("/users") @RequiredArgsConstructor public class UserController { /* @Autowired private final UserService userService; @GetMapping("/all") public ResponseEntity<List<User>> getUsers() { return new ResponseEntity<>(userService.getUsers(), HttpStatus.FOUND); } @GetMapping("/{email}") public ResponseEntity<?> getUserByEmail(@PathVariable("email") String email) { try { User theUser= userService.getUser(email); return ResponseEntity.ok(theUser); } catch (UserNotFoundException e) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); }catch (Exception e){ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error in fetching the user"); } } @DeleteMapping("/delete/{userId}") public ResponseEntity <String> deleteUser(@PathVariable("userId") String email){ try { userService.deleteUser(email); return ResponseEntity.ok("User deleted "); }catch (UserNotFoundException e){ return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage()); }catch ( Exception e ){ return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error in deleting the user"); } } */ //********************************************************************
private final UserService userService;
2
2023-12-30 19:51:38+00:00
2k
LeeKyeongYong/SBookStudy
src/main/java/com/multibook/bookorder/domain/product/product/entity/Product.java
[ { "identifier": "Book", "path": "src/main/java/com/multibook/bookorder/domain/book/book/entity/Book.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Book extends BaseTime {\n @ManyToOne\n private Member author;\n @OneToOne\n private Product product;\n private String title;\n private String body;\n private int price;\n private boolean published;\n}" }, { "identifier": "Member", "path": "src/main/java/com/multibook/bookorder/domain/member/member/entity/Member.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true, exclude = {\"myBooks\", \"owner\"})\npublic class Member extends BaseTime {\n private String username;\n private String password;\n private String nickname;\n private long restCash;\n\n @OneToMany(mappedBy = \"owner\", cascade = ALL, orphanRemoval = true)\n @Builder.Default\n private List<MyBook> myBooks = new ArrayList<>();\n\n public void addMyBook(Book book) {\n MyBook myBook = MyBook.builder()\n .owner(this)\n .book(book)\n .build();\n\n myBooks.add(myBook);\n }\n\n public void removeMyBook(Book book) {\n myBooks.removeIf(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean hasBook(Book book) {\n return myBooks\n .stream()\n .anyMatch(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean has(Product product) {\n return switch (product.getRelTypeCode()) {\n case \"book\" -> hasBook(product.getBook());\n default -> false;\n };\n }\n\n @Transient\n public Collection<? extends GrantedAuthority> getAuthorities() {\n List<GrantedAuthority> authorities = new ArrayList<>();\n\n authorities.add(new SimpleGrantedAuthority(\"ROLE_MEMBER\"));\n\n if (List.of(\"system\", \"admin\").contains(username)) {\n authorities.add(new SimpleGrantedAuthority(\"ROLE_ADMIN\"));\n }\n\n return authorities;\n }\n\n public boolean isAdmin() {\n return getAuthorities().stream()\n .anyMatch(a -> a.getAuthority().equals(\"ROLE_ADMIN\"));\n }\n}" }, { "identifier": "AppConfig", "path": "src/main/java/com/multibook/bookorder/global/app/AppConfig.java", "snippet": "@Configuration\n@RequiredArgsConstructor\npublic class AppConfig {\n private static String activeProfile;\n\n @Value(\"${spring.profiles.active}\")\n public void setActiveProfile(String value) {\n activeProfile = value;\n }\n\n public static boolean isNotProd() {\n return isProd() == false;\n }\n\n public static boolean isProd() {\n return activeProfile.equals(\"prod\");\n }\n\n @Getter\n private static String siteName;\n\n @Value(\"${custom.site.name}\")\n public void setSiteName(String siteName) {\n this.siteName = siteName;\n }\n\n @Getter\n private static EntityManager entityManager;\n\n @Autowired\n public void setEntityManager(EntityManager entityManager) {\n this.entityManager = entityManager;\n }\n\n @Getter\n private static String tempDirPath;\n\n @Value(\"${custom.temp.dirPath}\")\n public void setTempDirPath(String tempDirPath) {\n this.tempDirPath = tempDirPath;\n }\n\n @Getter\n private static String genFileDirPath;\n\n @Value(\"${custom.genFile.dirPath}\")\n public void setGenFileDirPath(String genFileDirPath) {\n this.genFileDirPath = genFileDirPath;\n }\n\n @Getter\n private static String tossPaymentsWidgetSecretKey;\n\n @Value(\"${custom.tossPayments.widget.secretKey}\")\n public void setTossPaymentsWidgetSecretKey(String tossPaymentsWidgetSecretKey) {\n this.tossPaymentsWidgetSecretKey = tossPaymentsWidgetSecretKey;\n }\n}" }, { "identifier": "BaseTime", "path": "src/main/java/com/multibook/bookorder/global/jpa/BaseTime.java", "snippet": "@MappedSuperclass\n@EntityListeners(AuditingEntityListener.class) // @CreatedDate, @LastModifiedDate를 사용하기 위해 필요\n@Getter\n@ToString(callSuper = true)\npublic abstract class BaseTime extends BaseEntity {\n @CreatedDate\n private LocalDateTime createDate;\n @LastModifiedDate\n private LocalDateTime modifyDate;\n\n public String getModelName() {\n return UtZip.str.lcfirst(this.getClass().getSimpleName());\n }\n}" } ]
import com.multibook.bookorder.domain.book.book.entity.Book; import com.multibook.bookorder.domain.member.member.entity.Member; import com.multibook.bookorder.global.app.AppConfig; import com.multibook.bookorder.global.jpa.BaseTime; import com.querydsl.core.annotations.QueryEntity; import jakarta.persistence.Entity; import jakarta.persistence.ManyToOne; import lombok.*; import static lombok.AccessLevel.PROTECTED;
1,240
package com.multibook.bookorder.domain.product.product.entity; @Entity @Builder @AllArgsConstructor(access = PROTECTED) @NoArgsConstructor(access = PROTECTED) @Setter @Getter @ToString(callSuper = true)
package com.multibook.bookorder.domain.product.product.entity; @Entity @Builder @AllArgsConstructor(access = PROTECTED) @NoArgsConstructor(access = PROTECTED) @Setter @Getter @ToString(callSuper = true)
public class Product extends BaseTime {
3
2023-12-26 14:58:59+00:00
2k
Farley-Chen/fastcdc-java
src/main/java/io/github/farleychen/fastcdc/RingByteArray.java
[ { "identifier": "EMPTY_BYTE_ARRAY", "path": "src/main/java/io/github/farleychen/fastcdc/ArrayUtils.java", "snippet": "public static final byte[] EMPTY_BYTE_ARRAY = new byte[0];" }, { "identifier": "subarray", "path": "src/main/java/io/github/farleychen/fastcdc/ArrayUtils.java", "snippet": "public static byte[] subarray(final byte[] array, int startIndexInclusive, int endIndexExclusive) {\n if (array == null) {\n return null;\n }\n if (startIndexInclusive < 0) {\n startIndexInclusive = 0;\n }\n if (endIndexExclusive > array.length) {\n endIndexExclusive = array.length;\n }\n final int newSize = endIndexExclusive - startIndexInclusive;\n if (newSize <= 0) {\n return EMPTY_BYTE_ARRAY;\n }\n\n final byte[] subarray = new byte[newSize];\n System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);\n return subarray;\n}" } ]
import static io.github.farleychen.fastcdc.ArrayUtils.EMPTY_BYTE_ARRAY; import static io.github.farleychen.fastcdc.ArrayUtils.subarray;
772
package io.github.farleychen.fastcdc; /** * refer to <a * href=https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-ios/src/main/java/com/jme3/util/RingBuffer.java>jmonkeyengine</a> * <p> * A circular array (array with wrap-around). * * @author FengChen */ class RingByteArray { /** * array elements */ private final byte[] elements; /** * number of elements in array */ private int size = 0; /** * index of first element of array */ private int firstElementIndex = 0; /** * index of next available slot */ private int addElementIndex = 0; RingByteArray(final int capacity) { Assert.isTrue(capacity >= 0); elements = new byte[capacity]; } boolean isEmpty() { return size == 0; } int size() { return size; } void addAll(final byte[] bytes) { for (final var aByte : bytes) { add(aByte); } } void add(final byte aByte) { if (size == elements.length) { throw new RuntimeException("Ring byte array overflow"); } elements[addElementIndex] = aByte; // wrap-around addElementIndex = (addElementIndex + 1) % elements.length; size++; } void position(final int index) { Assert.isTrue(index >= 0); if (index > size) { throw new RuntimeException("Ring byte array underflow"); } // wrap-around firstElementIndex = (firstElementIndex + index) % elements.length; size -= index; } byte get(final int index) { Assert.isTrue(index >= 0); if (index >= size) { throw new RuntimeException("Ring byte array underflow"); } // wrap-around return elements[(firstElementIndex + index) % elements.length]; } byte[] getRange(final int fromInclusive, final int toExclusive) { Assert.isTrue(fromInclusive >= 0); Assert.isTrue(fromInclusive <= toExclusive); if (fromInclusive >= size || toExclusive > size) { throw new RuntimeException("Ring byte array underflow"); } if (fromInclusive == toExclusive) {
package io.github.farleychen.fastcdc; /** * refer to <a * href=https://github.com/jMonkeyEngine/jmonkeyengine/blob/master/jme3-ios/src/main/java/com/jme3/util/RingBuffer.java>jmonkeyengine</a> * <p> * A circular array (array with wrap-around). * * @author FengChen */ class RingByteArray { /** * array elements */ private final byte[] elements; /** * number of elements in array */ private int size = 0; /** * index of first element of array */ private int firstElementIndex = 0; /** * index of next available slot */ private int addElementIndex = 0; RingByteArray(final int capacity) { Assert.isTrue(capacity >= 0); elements = new byte[capacity]; } boolean isEmpty() { return size == 0; } int size() { return size; } void addAll(final byte[] bytes) { for (final var aByte : bytes) { add(aByte); } } void add(final byte aByte) { if (size == elements.length) { throw new RuntimeException("Ring byte array overflow"); } elements[addElementIndex] = aByte; // wrap-around addElementIndex = (addElementIndex + 1) % elements.length; size++; } void position(final int index) { Assert.isTrue(index >= 0); if (index > size) { throw new RuntimeException("Ring byte array underflow"); } // wrap-around firstElementIndex = (firstElementIndex + index) % elements.length; size -= index; } byte get(final int index) { Assert.isTrue(index >= 0); if (index >= size) { throw new RuntimeException("Ring byte array underflow"); } // wrap-around return elements[(firstElementIndex + index) % elements.length]; } byte[] getRange(final int fromInclusive, final int toExclusive) { Assert.isTrue(fromInclusive >= 0); Assert.isTrue(fromInclusive <= toExclusive); if (fromInclusive >= size || toExclusive > size) { throw new RuntimeException("Ring byte array underflow"); } if (fromInclusive == toExclusive) {
return EMPTY_BYTE_ARRAY;
0
2023-12-26 18:47:28+00:00
2k
Maksymth/main
java basics/sprints/sprint 5 (5 tasks)/src/Run.java
[ { "identifier": "FirstTask", "path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/FirstTask.java", "snippet": "public class FirstTask {\r\n private static String dayOfWeekStrings[] = { \"Monday\", \"Tuesday\", \"Wensday\", \"Thursday\",\r\n \"Friday\", \"Saturday\", \"Sunday\" };\r\n\r\n public static void dayOfWeekShower(int day, int month, int year, int upperSpace, int bottomSpace) {\r\n Row.skip(upperSpace);\r\n\r\n int nYear = year - (14 - month) / 12;\r\n int x = nYear + nYear / 4 - nYear / 100 + nYear / 400;\r\n int nMonth = month + 12 * ((14 - month) / 12) - 2;\r\n\r\n int intResult = (day + x + 31 * nMonth / 12 - 1) % 7;\r\n\r\n Display.itn(dayOfWeekStrings[intResult]);\r\n\r\n Row.skip(bottomSpace);\r\n }\r\n}\r" }, { "identifier": "SecoundTask", "path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/SecoundTask.java", "snippet": "public class SecoundTask {\r\n public static void twoRollsDisplayer(int times) {\r\n for (int i = 0; i < times; i++) {\r\n int currentTime = i + 1;\r\n if (i == 0) {\r\n Row.skip(3);\r\n } else {\r\n Row.skip(1);\r\n }\r\n Display.itn(\"Time: \" + currentTime);\r\n Display.itn(\"First roll result: \" + rollResult());\r\n Display.itn(\"Secound roll result: \" + rollResult());\r\n Row.skip(1);\r\n }\r\n }\r\n\r\n private static int rollResult() {\r\n double rollResult = Math.random() * 6 + 1;\r\n\r\n return (int) rollResult;\r\n }\r\n}" }, { "identifier": "ThirdTask", "path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/ThirdTask.java", "snippet": "public class ThirdTask {\r\n public static void offcutLengthDisplayer(double x1, double y1, double x2, double y2) {\r\n double expression, result;\r\n\r\n expression = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);\r\n result = Math.sqrt(expression);\r\n\r\n Row.skip(3);\r\n Display.itn(\"Offcut length is - \" + result);\r\n Row.skip(1);\r\n }\r\n}\r" }, { "identifier": "FourthTask", "path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/FourthTask.java", "snippet": "public class FourthTask {\r\n private static final double EARTH_MASS = 5.97 * Math.pow(10, 24);\r\n private static final double EARTH_RADIUS = 6371 * Math.pow(10, 3); // in kilometers\r\n private static final double GRAVITY_CONSTANT = 6.67 * Math.pow(10, -11);\r\n\r\n public static void satelliteEscapeVelocityDisplayer(double input) { // output in meters\r\n double sideExpression, distanceToEarth, result; // parameters\r\n\r\n distanceToEarth = input; // input setting\r\n\r\n sideExpression = (GRAVITY_CONSTANT * EARTH_MASS) / (EARTH_RADIUS + distanceToEarth); // expression\r\n result = Math.sqrt(sideExpression);\r\n\r\n Row.skip(3);\r\n Display.itn(\"Satellite speed is - \" + Math.round(result) + \" m/s.\");\r\n Row.skip(1);\r\n }\r\n}" }, { "identifier": "Fifth", "path": "java basics/sprints/sprint 5 (5 tasks)/src/tasks/Fifth.java", "snippet": "public class Fifth {\r\n private static final int UP_TO = 12;\r\n\r\n public static void rabbitsPopulationCalculation(String titleSymbol, String divisionSymbol) {\r\n title();\r\n space(titleSymbol);\r\n content(divisionSymbol);\r\n }\r\n\r\n private static void title() {\r\n Display.itn(\" Ordered number | Result \");\r\n }\r\n\r\n private static void space(String titleSymbol) {\r\n for (int i = 0; i < 36; i++) {\r\n Display.it(titleSymbol);\r\n }\r\n Row.skip(1);\r\n }\r\n\r\n private static void content(String divisionSymbol) {\r\n for (int currentRowFromZero = 0; currentRowFromZero <= UP_TO; currentRowFromZero++) {\r\n if (currentRowFromZero > 9) {\r\n Display.itn(\" \" + currentRowFromZero + \" \" + divisionSymbol + \" \"\r\n + calculationResult(currentRowFromZero) + \" \");\r\n } else {\r\n Display.itn(\" \" + currentRowFromZero + \" \" + divisionSymbol + \" \"\r\n + calculationResult(currentRowFromZero) + \" \");\r\n }\r\n }\r\n }\r\n\r\n private static String calculationResult(int currentRow) {\r\n double expression;\r\n\r\n expression = (1 / Math.sqrt(5))\r\n * (Math.pow(((1 + Math.sqrt(5)) / 2), currentRow) - Math.pow(((1 - Math.sqrt(5)) / 2), currentRow));\r\n\r\n int sideResult = (int) expression;\r\n\r\n String result = Integer.toString(sideResult);\r\n\r\n return result;\r\n }\r\n}" } ]
import global.*; import tasks.FirstTask; import tasks.SecoundTask; import tasks.ThirdTask; import tasks.FourthTask; import tasks.Fifth;
1,333
// * Import // Code public class Run { public static void main(String[] args) { FirstTask.dayOfWeekShower(23, 12, 2023, 4, 1); Display.itn("\n\n--------------------------------------------------------- End of task.\n\n");
// * Import // Code public class Run { public static void main(String[] args) { FirstTask.dayOfWeekShower(23, 12, 2023, 4, 1); Display.itn("\n\n--------------------------------------------------------- End of task.\n\n");
SecoundTask.twoRollsDisplayer(25);
1
2023-12-30 04:25:22+00:00
2k
embuc/random-sentence-generator
src/test/java/se/emirbuc/randomsentence/RandomSentencesTest.java
[ { "identifier": "RandomSentences", "path": "src/main/java/se/emirbuc/randomsentence/RandomSentences.java", "snippet": "public class RandomSentences {\n\n\tprivate final static String SPACE = \" \";\n\tprivate final static String PERIOD = \".\";\n\n\tprivate static final Random r = new Random();\n\n\t/**\n\t * The <code>Enum Length</code>.\n\t *\n\t * @author Emir Bucalovic (embuc)\n\t * @since 2015-okt-05\n\t */\n\tpublic enum Length {\n\t\t/** Three word sentence, think 'title | name | short description'*/\n\t\tSHORT, \n\t\t/** Six word sentences.*/\n\t\tMEDIUM, \n\t\t/** Twelve word sentences, think 'description'.*/\n\t\tLONG\n\t}\n\n\t/**\n\t * Produces one random sentence with supplied length.\n\t * @param length\n\t * @return sentence as a String\n\t */\n\tpublic static String generateRandomSentence(Length length) {\n\t\tif (length == null) {\n\t\t\tlength = Length.SHORT;\n\t\t}\n\t\tStringBuilder sb = new StringBuilder();\n\t\tString first = Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)];\n\t\tchar c = first.charAt(0);\n\t\tfirst = first.replace(c, Character.toUpperCase(c));\n\t\tsb.append(first);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append((Grammar.VERB[rand(Grammar.VERB.length - 1)]));\n\t\tif (length == Length.SHORT) {\n\t\t\tsb.append(PERIOD);\n\t\t\treturn sb.toString();\n\t\t}\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.PREPOSITION[rand(Grammar.PREPOSITION.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)] + SPACE + Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\t\tif (length == Length.MEDIUM) {\n\t\t\tsb.append(PERIOD);\n\t\t\treturn sb.toString();\n\t\t}\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.PREPOSITION[rand(Grammar.PREPOSITION.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append((Grammar.VERB[rand(Grammar.VERB.length - 1)]));\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.ARTICLE[rand(Grammar.ARTICLE.length - 1)]);\n\t\tsb.append(SPACE);\n\t\tsb.append(Grammar.NOUN[rand(Grammar.NOUN.length - 1)]);\n\n\t\tsb.append(PERIOD);\n\t\treturn sb.toString();\n\t}\n\n\tstatic int rand(int length) {\n\t\tif (length == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tint ri = r.nextInt() % length;\n\t\tif (ri < 0)\n\t\t\tri += length;\n\t\treturn ri;\n\t}\n\n}" }, { "identifier": "Length", "path": "src/main/java/se/emirbuc/randomsentence/RandomSentences.java", "snippet": "public enum Length {\n\t/** Three word sentence, think 'title | name | short description'*/\n\tSHORT, \n\t/** Six word sentences.*/\n\tMEDIUM, \n\t/** Twelve word sentences, think 'description'.*/\n\tLONG\n}" } ]
import se.emirbuc.randomsentence.RandomSentences; import se.emirbuc.randomsentence.RandomSentences.Length; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Test;
1,241
/* The MIT License (MIT) * * Copyright (c) 2015 Emir Bucalovic (embuc) * * 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 se.emirbuc.randomsentence; /** * RandomSentencesTest class. * * @author Emir Bucalovic (embuc) * @since 2015-okt-01 */ public class RandomSentencesTest { @Test public void instantiation() {
/* The MIT License (MIT) * * Copyright (c) 2015 Emir Bucalovic (embuc) * * 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 se.emirbuc.randomsentence; /** * RandomSentencesTest class. * * @author Emir Bucalovic (embuc) * @since 2015-okt-01 */ public class RandomSentencesTest { @Test public void instantiation() {
RandomSentences target = new RandomSentences();
0
2023-12-29 23:21:36+00:00
2k
SDeVuyst/pingys-waddles-1.20.1
src/main/java/com/sdevuyst/pingyswaddles/datagen/ModItemModelProvider.java
[ { "identifier": "PingysWaddles", "path": "src/main/java/com/sdevuyst/pingyswaddles/PingysWaddles.java", "snippet": "@Mod(PingysWaddles.MOD_ID)\npublic class PingysWaddles\n{\n // Define mod id in a common place for everything to reference\n public static final String MOD_ID = \"pingyswaddles\";\n // Directly reference a slf4j logger\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public PingysWaddles()\n {\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n // register Creative Tab\n ModCreativeModTabs.register(modEventBus);\n // register items\n ModItems.register(modEventBus);\n // register blocks\n ModBlocks.register(modEventBus);\n //register entities\n ModEntities.register(modEventBus);\n\n // Register the commonSetup method for modloading\n modEventBus.addListener(this::commonSetup);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n\n // Register the item to a creative tab\n modEventBus.addListener(this::addCreative);\n\n }\n\n private void commonSetup(final FMLCommonSetupEvent event)\n {\n\n }\n\n // Add the example block item to the building blocks tab\n private void addCreative(BuildCreativeModeTabContentsEvent event)\n {\n\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n\n }\n\n // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent\n @Mod.EventBusSubscriber(modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientModEvents\n {\n @SubscribeEvent\n public static void onClientSetup(FMLClientSetupEvent event)\n {\n EntityRenderers.register(ModEntities.EMPEROR_PENGUIN.get(), EmperorPenguinRenderer::new);\n EntityRenderers.register(ModEntities.SURFBOARD.get(), SurfboardRenderer::new);\n }\n }\n}" }, { "identifier": "ModItems", "path": "src/main/java/com/sdevuyst/pingyswaddles/item/ModItems.java", "snippet": "public class ModItems {\n public static final DeferredRegister<Item> ITEMS =\n DeferredRegister.create(ForgeRegistries.ITEMS, PingysWaddles.MOD_ID);\n\n public static final RegistryObject<Item> EMPEROR_PENGUIN_SPAWN_EGG = ITEMS.register(\"emperor_penguin_spawn_egg\",\n () -> new ForgeSpawnEggItem(ModEntities.EMPEROR_PENGUIN, 0xf9f6ee, 0xf0b722, new Item.Properties()));\n\n public static final RegistryObject<Item> OAK_SURFBOARD = ITEMS.register(\"oak_surfboard\",\n () -> new SurfboardItem(false, SurfboardEntity.Type.OAK, new Item.Properties()));\n\n public static void register(IEventBus eventBus) {\n ITEMS.register(eventBus);\n }\n}" } ]
import com.sdevuyst.pingyswaddles.PingysWaddles; import com.sdevuyst.pingyswaddles.item.ModItems; import net.minecraft.data.PackOutput; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraftforge.client.model.generators.ItemModelBuilder; import net.minecraftforge.client.model.generators.ItemModelProvider; import net.minecraftforge.common.data.ExistingFileHelper; import net.minecraftforge.registries.RegistryObject;
938
package com.sdevuyst.pingyswaddles.datagen; public class ModItemModelProvider extends ItemModelProvider { public ModItemModelProvider(PackOutput output, ExistingFileHelper existingFileHelper) { super(output, PingysWaddles.MOD_ID, existingFileHelper); } @Override protected void registerModels() {
package com.sdevuyst.pingyswaddles.datagen; public class ModItemModelProvider extends ItemModelProvider { public ModItemModelProvider(PackOutput output, ExistingFileHelper existingFileHelper) { super(output, PingysWaddles.MOD_ID, existingFileHelper); } @Override protected void registerModels() {
withExistingParent(ModItems.EMPEROR_PENGUIN_SPAWN_EGG.getId().getPath(), mcLoc("item/template_spawn_egg"));
1
2023-12-31 09:54:03+00:00
2k
IGinX-THU/Parquet
src/main/java/org/apache/parquet/local/CodecFactory.java
[ { "identifier": "NoopBytesInputCompressor", "path": "src/main/java/org/apache/parquet/local/codec/NoopBytesInputCompressor.java", "snippet": "public class NoopBytesInputCompressor implements CompressionCodecFactory.BytesInputCompressor {\n @Override\n public BytesInput compress(BytesInput bytes) throws IOException {\n return bytes;\n }\n\n @Override\n public CompressionCodecName getCodecName() {\n return CompressionCodecName.UNCOMPRESSED;\n }\n\n @Override\n public void release() {}\n}" }, { "identifier": "NoopBytesInputDecompressor", "path": "src/main/java/org/apache/parquet/local/codec/NoopBytesInputDecompressor.java", "snippet": "public class NoopBytesInputDecompressor implements CompressionCodecFactory.BytesInputDecompressor {\n @Override\n public void decompress(\n ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize)\n throws IOException {\n if (compressedSize != uncompressedSize) {\n throw new IOException(\n \"Non-compressed data did not have matching compressed and uncompressed sizes.\");\n }\n output.clear();\n output.put((ByteBuffer) input.duplicate().position(0).limit(compressedSize));\n }\n\n @Override\n public BytesInput decompress(BytesInput bytes, int uncompressedSize) {\n return bytes;\n }\n\n @Override\n public void release() {}\n}" }, { "identifier": "SnappyBytesInputCompressor", "path": "src/main/java/org/apache/parquet/local/codec/SnappyBytesInputCompressor.java", "snippet": "public class SnappyBytesInputCompressor implements CompressionCodecFactory.BytesInputCompressor {\n\n @Override\n public BytesInput compress(BytesInput bytes) throws IOException {\n int maxOutputSize = Snappy.maxCompressedLength((int) bytes.size());\n byte[] outgoing = new byte[maxOutputSize];\n int compressedSize = Snappy.compress(bytes.toByteArray(), 0, (int) bytes.size(), outgoing, 0);\n return BytesInput.from(outgoing, 0, compressedSize);\n }\n\n @Override\n public CompressionCodecName getCodecName() {\n return CompressionCodecName.SNAPPY;\n }\n\n @Override\n public void release() {}\n}" }, { "identifier": "SnappyBytesInputDecompressor", "path": "src/main/java/org/apache/parquet/local/codec/SnappyBytesInputDecompressor.java", "snippet": "public class SnappyBytesInputDecompressor\n implements CompressionCodecFactory.BytesInputDecompressor {\n\n @Override\n public BytesInput decompress(BytesInput bytes, int uncompressedSize) throws IOException {\n byte[] ingoing = bytes.toByteArray();\n byte[] outgoing = Snappy.uncompress(ingoing);\n if (outgoing.length != uncompressedSize) {\n throw new IOException(\"Non-compressed data did not have matching uncompressed sizes.\");\n }\n return BytesInput.from(outgoing);\n }\n\n @Override\n public void decompress(\n ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize)\n throws IOException {\n output.clear();\n int size = Snappy.uncompress(input, output);\n output.limit(size);\n }\n\n @Override\n public void release() {}\n}" } ]
import org.apache.parquet.compression.CompressionCodecFactory; import org.apache.parquet.hadoop.metadata.CompressionCodecName; import org.apache.parquet.local.codec.NoopBytesInputCompressor; import org.apache.parquet.local.codec.NoopBytesInputDecompressor; import org.apache.parquet.local.codec.SnappyBytesInputCompressor; import org.apache.parquet.local.codec.SnappyBytesInputDecompressor; import java.util.HashMap; import java.util.Map;
1,152
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.parquet.local; public class CodecFactory implements CompressionCodecFactory { private final Map<CompressionCodecName, BytesInputCompressor> compressors = new HashMap<>(); private final Map<CompressionCodecName, BytesInputDecompressor> decompressors = new HashMap<>(); @Override public BytesInputCompressor getCompressor(CompressionCodecName codecName) { return createCompressor(codecName); } @Override public BytesInputDecompressor getDecompressor(CompressionCodecName codecName) { return decompressors.computeIfAbsent(codecName, this::createDecompressor); } protected BytesInputCompressor createCompressor(CompressionCodecName codecName) { switch (codecName) { case UNCOMPRESSED:
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.parquet.local; public class CodecFactory implements CompressionCodecFactory { private final Map<CompressionCodecName, BytesInputCompressor> compressors = new HashMap<>(); private final Map<CompressionCodecName, BytesInputDecompressor> decompressors = new HashMap<>(); @Override public BytesInputCompressor getCompressor(CompressionCodecName codecName) { return createCompressor(codecName); } @Override public BytesInputDecompressor getDecompressor(CompressionCodecName codecName) { return decompressors.computeIfAbsent(codecName, this::createDecompressor); } protected BytesInputCompressor createCompressor(CompressionCodecName codecName) { switch (codecName) { case UNCOMPRESSED:
return new NoopBytesInputCompressor();
0
2023-12-29 01:48:28+00:00
2k
AweiMC/DragonMounts3
common/src/main/java/net/dragonmounts3/tools/DM3Item.java
[ { "identifier": "DM3Mod", "path": "common/src/main/java/net/dragonmounts3/DM3Mod.java", "snippet": "public class DM3Mod {\n public static final String MOD_ID = \"dragonmounts\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n public static void init() {\n DragonTypeManager.init();//\n DM3Item.ItemRegister();\n\n }\n}" }, { "identifier": "DM3Hoe", "path": "common/src/main/java/net/dragonmounts3/tools/DM3ToolMaterial/DM3Hoe.java", "snippet": "public class DM3Hoe extends HoeItem {\n public DM3Hoe(ToolMaterial material, int attackDamage, float attackSpeed, Settings settings) {\n super(material, attackDamage, attackSpeed, settings);\n }\n}" }, { "identifier": "DM3Shovel", "path": "common/src/main/java/net/dragonmounts3/tools/DM3ToolMaterial/DM3Shovel.java", "snippet": "public class DM3Shovel extends ShovelItem {\n public DM3Shovel(ToolMaterial material, float attackDamage, float attackSpeed, Settings settings) {\n super(material, attackDamage, attackSpeed, settings);\n }\n}" }, { "identifier": "DM3Sword", "path": "common/src/main/java/net/dragonmounts3/tools/DM3ToolMaterial/DM3Sword.java", "snippet": "public class DM3Sword extends SwordItem {\n public DM3Sword(ToolMaterial toolMaterial, int attackDamage, float attackSpeed, Settings settings) {\n super(toolMaterial, attackDamage, attackSpeed, settings);\n }\n}" }, { "identifier": "DM3ToolMaterials", "path": "common/src/main/java/net/dragonmounts3/tools/DM3ToolMaterial/DM3ToolMaterials.java", "snippet": "public enum DM3ToolMaterials implements ToolMaterial {\n FOREST(3, 2700, 0F, 0F, 30, () -> Ingredient.ofItems(Items.NETHER_STAR)),\n ENCHANT(3, 2700, 0F, 0F, 30, () -> Ingredient.ofItems(Items.NETHER_STAR)),\n AETHER(3, 2700, 0F, 0F, 30, () -> Ingredient.ofItems(Items.NETHER_STAR));\n\n\n\n //材料类型注册\n private final int miningLevel;\n private final int itemDurability;\n private final float miningSpeed;\n private final float attackDamage;\n private final int enchantability;\n private final Lazy<Ingredient> repairIngredient;\n\n DM3ToolMaterials(int miningLevel, int itemDurability, float miningSpeed, float attackDamage, int enchantability, Supplier<Ingredient> repairIngredient) {\n this.miningLevel = miningLevel;\n this.itemDurability = itemDurability;\n this.miningSpeed = miningSpeed;\n this.attackDamage = attackDamage;\n this.enchantability = enchantability;\n this.repairIngredient = new Lazy(repairIngredient);\n }\n\n public int getDurability() {\n return this.itemDurability;\n }\n\n public float getMiningSpeedMultiplier() {\n return this.miningSpeed;\n }\n\n public float getAttackDamage() {\n return this.attackDamage;\n }\n\n public int getMiningLevel() {\n return this.miningLevel;\n }\n\n public int getEnchantability() {\n return this.enchantability;\n }\n\n public Ingredient getRepairIngredient() {\n return this.repairIngredient.get();\n }\n\n}" }, { "identifier": "DragonTypeManager", "path": "common/src/main/java/net/dragonmounts3/util/DragonTypeManager.java", "snippet": "public class DragonTypeManager {\n private static final Set<String> dragonTypes = new LinkedHashSet<>();\n\n static {\n initDefaultTypes();\n }\n\n private static void initDefaultTypes() {\n dragonTypes.add(\"aether\");\n dragonTypes.add(\"enchant\");\n dragonTypes.add(\"ender\");\n dragonTypes.add(\"fire\");\n dragonTypes.add(\"forest\");\n dragonTypes.add(\"ice\");\n dragonTypes.add(\"moonlight\");\n dragonTypes.add(\"nether\");\n dragonTypes.add(\"sculk\");\n dragonTypes.add(\"storm\");\n dragonTypes.add(\"sunlight\");\n dragonTypes.add(\"terra\");\n dragonTypes.add(\"water\");\n }\n\n public static synchronized void addDragonType(String type) {\n // 可以在这里进行网络同步,向所有玩家发送新的 DragonType\n dragonTypes.add(type);\n }\n\n public static synchronized Set<String> getDragonTypes() {\n return new LinkedHashSet<>(dragonTypes);\n }\n}" }, { "identifier": "ToolType", "path": "common/src/main/java/net/dragonmounts3/util/ToolType.java", "snippet": "public enum ToolType {\n SWORD,\n PICKAXE,\n SHOVEL,\n HOE\n\n}" } ]
import dev.architectury.registry.CreativeTabRegistry; import dev.architectury.registry.registries.DeferredRegister; import dev.architectury.registry.registries.RegistrySupplier; import net.dragonmounts3.DM3Mod; import net.dragonmounts3.tools.DM3ToolMaterial.DM3Hoe; import net.dragonmounts3.tools.DM3ToolMaterial.DM3Shovel; import net.dragonmounts3.tools.DM3ToolMaterial.DM3Sword; import net.dragonmounts3.tools.DM3ToolMaterial.DM3ToolMaterials; import net.dragonmounts3.util.DragonTypeManager; import net.dragonmounts3.util.ToolType; import net.minecraft.item.*; import net.minecraft.registry.RegistryKeys; import net.minecraft.text.Text; import net.minecraft.util.Identifier; import java.util.function.Supplier;
1,507
package net.dragonmounts3.tools; public interface DM3Item { DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM_GROUP); // 创建一个 DeferredRegister 来注册物品 RegistrySupplier<ItemGroup> DM3_GROUP = ITEM_GROUPS.register(new Identifier("dragonmounts3.title.group"), () -> CreativeTabRegistry.create( Text.translatable("dragonmounts3.title.group"), () -> Items.DIAMOND.asItem().getDefaultStack() )); DeferredRegister<Item> ITEMS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM); static void ItemRegister() { ITEM_GROUPS.register(); ITEMS.register(); // 这里注册你的物品 registerTools(); } static Item.Settings ItemToGroup() { return new Item.Settings().arch$tab(DM3_GROUP); } static void register(String name, Supplier<Item> item) { ITEMS.register(new Identifier(DM3Mod.MOD_ID,(name)), item); } static void registerTools() {
package net.dragonmounts3.tools; public interface DM3Item { DeferredRegister<ItemGroup> ITEM_GROUPS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM_GROUP); // 创建一个 DeferredRegister 来注册物品 RegistrySupplier<ItemGroup> DM3_GROUP = ITEM_GROUPS.register(new Identifier("dragonmounts3.title.group"), () -> CreativeTabRegistry.create( Text.translatable("dragonmounts3.title.group"), () -> Items.DIAMOND.asItem().getDefaultStack() )); DeferredRegister<Item> ITEMS = DeferredRegister.create(DM3Mod.MOD_ID, RegistryKeys.ITEM); static void ItemRegister() { ITEM_GROUPS.register(); ITEMS.register(); // 这里注册你的物品 registerTools(); } static Item.Settings ItemToGroup() { return new Item.Settings().arch$tab(DM3_GROUP); } static void register(String name, Supplier<Item> item) { ITEMS.register(new Identifier(DM3Mod.MOD_ID,(name)), item); } static void registerTools() {
for (String dragonType : DragonTypeManager.getDragonTypes()) {
5
2023-12-28 12:11:21+00:00
2k
amnoah/BetterDefusal
src/main/java/better/defusal/BetterDefusal.java
[ { "identifier": "BetterDefusalCommand", "path": "src/main/java/better/defusal/commands/BetterDefusalCommand.java", "snippet": "public class BetterDefusalCommand extends Command {\n\n public BetterDefusalCommand() {\n setName(\"betterdefusal\");\n setPermission(\"better.defusal.command\");\n setSubcommands(new ReloadSubCommand(), new SetItemSubCommand());\n setRequiresArgs(false);\n setTabCompletions(\"Reload\", \"SetItem\");\n }\n\n @Override\n public void execute(CommandSender commandSender, String[] strings) {\n commandSender.sendMessage(\"§7BetterDefusal version §8\" + BetterDefusal.VERSION + \"§7!\");\n }\n}" }, { "identifier": "InteractListener", "path": "src/main/java/better/defusal/listener/InteractListener.java", "snippet": "public class InteractListener implements Listener {\n\n @EventHandler\n public void onInteractEntityRightClick(PlayerInteractEntityEvent event) {\n if (event.isCancelled()) return;\n if (!event.getPlayer().hasPermission(\"better.defusal.use\")) return;\n\n Material defusalItem = BetterDefusal.getInstance().getDefusalItem();\n ItemStack mainHand = event.getPlayer().getInventory().getItemInMainHand();\n ItemStack offHand = event.getPlayer().getInventory().getItemInOffHand();\n Damageable damageable = null;\n\n // Verify the right item is used.\n if (defusalItem != null) {\n if (mainHand.getType() == defusalItem) {\n if (mainHand.getItemMeta() instanceof Damageable && BetterDefusal.getInstance().isDurabilityUsed())\n damageable = (Damageable) mainHand.getItemMeta();\n } else if (offHand.getType() == defusalItem) {\n if (offHand.getItemMeta() instanceof Damageable && BetterDefusal.getInstance().isDurabilityUsed())\n damageable = (Damageable) offHand.getItemMeta();\n } else return;\n }\n\n Location location = event.getRightClicked().getLocation();\n Material material;\n\n // Determine the material to be dropped.\n if (event.getRightClicked() instanceof TNTPrimed) {\n material = Material.TNT;\n } else if(event.getRightClicked() instanceof ExplosiveMinecart) {\n material = Material.TNT_MINECART;\n } else if (event.getRightClicked() instanceof FallingBlock && BetterDefusal.getInstance().isAllBlocks()) {\n material = ((FallingBlock) event.getRightClicked()).getBlockData().getMaterial();\n } else return;\n\n // Drop the material and get rid of the entity.\n event.getRightClicked().getWorld().dropItem(location, new ItemStack(material));\n event.getRightClicked().getWorld().playSound(location, Sound.ENTITY_PLAYER_HURT, 1, 2);\n event.getRightClicked().remove();\n\n // Apply damage.\n if (damageable == null) return;\n if (event.getPlayer().getGameMode().equals(GameMode.CREATIVE)) return;\n damageable.setDamage(damageable.getDamage() + 1);\n if (mainHand.getType() == defusalItem) mainHand.setItemMeta(damageable);\n else offHand.setItemMeta(damageable);\n }\n}" }, { "identifier": "ReloadListener", "path": "src/main/java/better/defusal/listener/ReloadListener.java", "snippet": "public class ReloadListener implements Listener {\n\n @EventHandler\n public void onReload(ReloadEvent event) {\n BetterDefusal.getInstance().reload();\n }\n}" } ]
import better.defusal.commands.BetterDefusalCommand; import better.defusal.listener.InteractListener; import better.defusal.listener.ReloadListener; import com.imjustdoom.cmdinstruction.CMDInstruction; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List;
1,199
package better.defusal; public class BetterDefusal extends JavaPlugin { public final static List<String> MATERIALS = new ArrayList<>(); public final static String VERSION = "1.0.0"; private static BetterDefusal instance; private boolean allBlocks, durabilityUsed; private Material defusalItem; /** * Generate a list of possible items to use as the "wire cutter". */ static { MATERIALS.add("*"); for (Material material : Material.values()) if (material.isItem()) MATERIALS.add(material.name().toLowerCase()); } /* * Getters. */ /** * Return the material used as the wire cutters. */ public Material getDefusalItem() { return defusalItem; } /** * Return the plugin's current instance. */ public static BetterDefusal getInstance() { return instance; } /** * Return whether falling blocks can also be "defused". */ public boolean isAllBlocks() { return allBlocks; } /** * Return whether defusing uses item durability */ public boolean isDurabilityUsed() { return durabilityUsed; } /* * Methods. */ @Override public void onEnable() { instance = this; new Metrics(this, 20535); CMDInstruction.registerCommands(this, new BetterDefusalCommand()); Bukkit.getPluginManager().registerEvents(new InteractListener(), this); if (Bukkit.getPluginManager().getPlugin("BetterReload") != null)
package better.defusal; public class BetterDefusal extends JavaPlugin { public final static List<String> MATERIALS = new ArrayList<>(); public final static String VERSION = "1.0.0"; private static BetterDefusal instance; private boolean allBlocks, durabilityUsed; private Material defusalItem; /** * Generate a list of possible items to use as the "wire cutter". */ static { MATERIALS.add("*"); for (Material material : Material.values()) if (material.isItem()) MATERIALS.add(material.name().toLowerCase()); } /* * Getters. */ /** * Return the material used as the wire cutters. */ public Material getDefusalItem() { return defusalItem; } /** * Return the plugin's current instance. */ public static BetterDefusal getInstance() { return instance; } /** * Return whether falling blocks can also be "defused". */ public boolean isAllBlocks() { return allBlocks; } /** * Return whether defusing uses item durability */ public boolean isDurabilityUsed() { return durabilityUsed; } /* * Methods. */ @Override public void onEnable() { instance = this; new Metrics(this, 20535); CMDInstruction.registerCommands(this, new BetterDefusalCommand()); Bukkit.getPluginManager().registerEvents(new InteractListener(), this); if (Bukkit.getPluginManager().getPlugin("BetterReload") != null)
Bukkit.getPluginManager().registerEvents(new ReloadListener(), this);
2
2023-12-22 05:38:25+00:00
2k
MinsTail/essential
src/main/java/com/dotSoftix/guiManager/clickgui/Button.java
[ { "identifier": "ModuleLoader", "path": "src/main/java/com/dotSoftix/EssentialClient/modules/ModuleLoader.java", "snippet": "public class ModuleLoader {\n public String name;\n public boolean toggled;\n public int keyCode;\n public Category category;\n public Minecraft mc = Minecraft.getMinecraft();\n\n public ModuleLoader(String name, int key, Category c) {\n this.name = name;\n this.keyCode = key;\n this.category = c;\n }\n\n public boolean isEnabled() {\n return toggled;\n }\n\n public int getKeyCode() {\n return keyCode;\n }\n\n public void onEnable() {\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n public void onDisable(){\n MinecraftForge.EVENT_BUS.unregister(this);\n }\n\n public void setKey(int key){\n this.keyCode = key;\n }\n\n public Category getCategory() {\n return category;\n }\n\n public String getName() {\n return this.name;\n }\n public void disable() {\n toggled = false;\n }\n\n public void onUpdate() {\n\n }\n\n public void toggle() {\n toggled = !toggled;\n if (toggled) {\n onEnable();\n } else {\n onDisable();\n }\n }\n\n public enum Category {\n MOVEMENT,\n RENDER,\n COMBAT,\n EXPLOIT,\n EXPERIMENTAL;\n }\n\n public void setToggled() {\n this.toggled = toggled;\n if (this.toggled) {\n onEnable();\n } else {\n onDisable();\n }\n }\n}" }, { "identifier": "checkRedanMode", "path": "src/main/java/com/dotSoftix/EssentialClient/guiModes/checkRedanMode.java", "snippet": "public class checkRedanMode {\n public static boolean isRedanModeActivated = false;\n}" }, { "identifier": "checkBlueMode", "path": "src/main/java/com/dotSoftix/EssentialClient/guiModes/checkBlueMode.java", "snippet": "public class checkBlueMode {\n public static boolean blueMode = false;\n}" } ]
import com.dotSoftix.EssentialClient.modules.ModuleLoader; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.Gui; import org.lwjgl.input.Keyboard; import com.dotSoftix.EssentialClient.guiModes.checkRedanMode; import com.dotSoftix.EssentialClient.guiModes.checkBlueMode; import java.awt.*; import java.io.IOException;
883
package com.dotSoftix.guiManager.clickgui; public class Button { public Minecraft mc = Minecraft.getMinecraft(); public int x, y, width, height; public boolean binding; public ModuleLoader module; public Button(int x, int y, int width, int height, ModuleLoader module) { this.x = x; this.y = y; this.width = width; this.height = height; this.module = module; } public void drawScreen(int mouseX, int mouseY, float partialTicks) { if(checkRedanMode.isRedanModeActivated) { //Gui.drawRect(x + 10, y, x + width - 10 + 2, y + height + 2, new Color(0xD8CBCBCB, true).hashCode()); System.out.println("activated"); Gui.drawRect(x + 10, y, x + width - 10, y + height, new Color(0xD81C1B1B, true).hashCode()); mc.fontRenderer.drawStringWithShadow(!binding ? module.name : "< PRESS KEY >", x + width / 2 - mc.fontRenderer.getStringWidth(!binding ? module.name : "< PRESS KEY >") / 2, y + height / 2 - 9 / 2, module.toggled && !binding ? com.dotSoftix.EssentialClient.modules.ui.fadeColor(10) : -1); }
package com.dotSoftix.guiManager.clickgui; public class Button { public Minecraft mc = Minecraft.getMinecraft(); public int x, y, width, height; public boolean binding; public ModuleLoader module; public Button(int x, int y, int width, int height, ModuleLoader module) { this.x = x; this.y = y; this.width = width; this.height = height; this.module = module; } public void drawScreen(int mouseX, int mouseY, float partialTicks) { if(checkRedanMode.isRedanModeActivated) { //Gui.drawRect(x + 10, y, x + width - 10 + 2, y + height + 2, new Color(0xD8CBCBCB, true).hashCode()); System.out.println("activated"); Gui.drawRect(x + 10, y, x + width - 10, y + height, new Color(0xD81C1B1B, true).hashCode()); mc.fontRenderer.drawStringWithShadow(!binding ? module.name : "< PRESS KEY >", x + width / 2 - mc.fontRenderer.getStringWidth(!binding ? module.name : "< PRESS KEY >") / 2, y + height / 2 - 9 / 2, module.toggled && !binding ? com.dotSoftix.EssentialClient.modules.ui.fadeColor(10) : -1); }
if(checkBlueMode.blueMode) {
2
2023-12-28 15:15:14+00:00
2k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/service/impl/loginServiceImpl.java
[ { "identifier": "systemSetting", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/systemSetting.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class systemSetting {\n /**\n * 绑定IP和端口\n */\n private String bing;\n /**\n * 请求的超时时间\n */\n private Integer timeout;\n /**\n * 部署服务流量走代理\n */\n private String proxy_url;\n /**\n * GPT中创建的对话分享\n */\n private Boolean public_share;\n /**\n * 访问网站密码\n */\n private String site_password;\n /**\n * 重载服务密码\n */\n private String setup_password;\n /**\n * 白名单(null则不限制,为空数组[]则限制所有账号)\n */\n private String whitelist;\n\n /**\n * pandoraNext验证license_id\n */\n private String license_id;\n\n /**\n * tokensTool登录Username\n */\n private String loginUsername;\n\n /**\n * tokensTool密码Password\n */\n private String loginPassword;\n\n /**\n * tokensTool 验证信息\n */\n private validation validation;\n\n /**\n * tokensTool 更新token网址\n * 为\"default\"则调用本机的,不为“default\"则自定义\n */\n private String autoToken_url;\n\n /**\n * 是否开启拿tokensTool的后台token\n */\n private Boolean isGetToken;\n /**\n * tokensTool 拿到getTokenPassword\n * 为\"getTokenPassword\" 默认:123456\n * 默认拿getTokenPassword\n */\n private String getTokenPassword;\n\n /**\n * tokensTool 更新containerName(容器名)\n * 通过容器名实现开启,关闭,重新启动容器\n */\n private String containerName;\n\n\n /**\n * PandoraNext tls证书\n */\n private tls tls;\n\n /**\n * PandoraNext config.json位置\n */\n private String configPosition;\n\n /**\n * PandoraNext 接口地址添加前缀\n */\n private String isolated_conv_title;\n\n /**\n * PandoraNext 会话标题\n */\n private String proxy_api_prefix;\n\n /**\n * 禁用注册账号功能,true或false\n */\n private Boolean disable_signup;\n\n /**\n * 在proxy模式使用gpt-4模型调用/backend-api/conversation接口是否自动打码,使用消耗为4+10。\n */\n private Boolean auto_conv_arkose;\n\n /**\n * 在proxy模式是否使用PandoraNext的文件代理服务,避免官方文件服务的墙。\n */\n private Boolean proxy_file_service;\n\n /**\n * 配置自定义的DoH主机名,建议使用IP形式。默认在+8区使用223.6.6.6,其余地区使用1.1.1.1。\n */\n private String custom_doh_host;\n\n /**\n * 自动刷新session的开关\n */\n private Boolean auto_updateSession;\n\n /**\n * 自动刷新session的时间 (天为单位)\n */\n private Integer auto_updateTime;\n\n /**\n * 自动刷新session的个数 (个)\n */\n private Integer auto_updateNumber;\n\n /**\n * PadoraNext的公网访问地址\n */\n private String pandoraNext_outUrl;\n\n /**\n * oneAPi的公网访问地址\n */\n private String oneAPi_outUrl;\n\n /**\n * oneApi访问令牌\n */\n private String oneAPi_intoToken;\n}" }, { "identifier": "loginService", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/service/loginService.java", "snippet": "public interface loginService {\n\n /**\n * 新增保存登录信息\n * 通过config.json文件可以实现修改密码,修改数据\n *\n * @return \"登录成功!\"\n * \"用户名账号错误\"\n */\n\n boolean login(systemSetting setting);\n}" }, { "identifier": "systemService", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/service/systemService.java", "snippet": "public interface systemService {\n /**\n * 修改config.json里的系统值\n *\n * @return \"修改成功!\"or\"修改失败\"\n */\n String requiredSetting(systemSetting tem);\n\n /**\n * 查询config.json里的系统值\n *\n * @return systemSettings类\n */\n systemSetting selectSetting();\n\n /**\n * 查询config.json里的baseUrl\n *\n * @return systemSettings类\n */\n systemSetting selectSettingUrl();\n\n}" } ]
import com.tokensTool.pandoraNext.pojo.systemSetting; import com.tokensTool.pandoraNext.service.loginService; import com.tokensTool.pandoraNext.service.systemService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
1,468
package com.tokensTool.pandoraNext.service.impl; /** * @author Yangyang * @create 2023-11-17 14:15 */ @Slf4j @Service public class loginServiceImpl implements loginService { /** * systemService从这里面 * 拿到两个变量 * loginUsername * loginPassword * 返回登录成功!或用户名账号错误" */ @Autowired private systemService systemService; /** * 新增保存登录信息 * 通过config.json文件可以实现修改密码,修改数据 * * @return "登录成功!" * "用户名账号错误" */ @Override
package com.tokensTool.pandoraNext.service.impl; /** * @author Yangyang * @create 2023-11-17 14:15 */ @Slf4j @Service public class loginServiceImpl implements loginService { /** * systemService从这里面 * 拿到两个变量 * loginUsername * loginPassword * 返回登录成功!或用户名账号错误" */ @Autowired private systemService systemService; /** * 新增保存登录信息 * 通过config.json文件可以实现修改密码,修改数据 * * @return "登录成功!" * "用户名账号错误" */ @Override
public boolean login(systemSetting setting) {
0
2023-11-17 11:37:37+00:00
2k
bryan31/Akali
src/main/java/org/dromara/akali/spring/AkaliAutoConfiguration.java
[ { "identifier": "FallbackStrategy", "path": "src/main/java/org/dromara/akali/strategy/FallbackStrategy.java", "snippet": "public class FallbackStrategy implements AkaliStrategy{\n\n private final Map<String, Method> fallBackMethodMap = new ConcurrentHashMap<>();\n\n @Override\n public AkaliStrategyEnum getStrategy() {\n return AkaliStrategyEnum.FALLBACK;\n }\n\n @Override\n public Object process(Object bean, Method method, Object[] args) throws Exception{\n String fallbackMethodName = StrUtil.format(\"{}Fallback\", method.getName());\n\n Method fallbackMethod;\n if (fallBackMethodMap.containsKey(fallbackMethodName)){\n fallbackMethod = fallBackMethodMap.get(fallbackMethodName);\n }else{\n fallbackMethod = ReflectUtil.getMethod(bean.getClass(), fallbackMethodName, method.getParameterTypes());\n fallBackMethodMap.put(fallbackMethodName, fallbackMethod);\n }\n\n if (ObjectUtil.isNull(fallbackMethod)){\n throw new RuntimeException(StrUtil.format(\"[AKALI] Can't find fallback method [{}] in bean [{}]\", fallbackMethodName, bean.getClass().getName()));\n }\n\n return fallbackMethod.invoke(bean, args);\n }\n}" }, { "identifier": "MethodHotspotStrategy", "path": "src/main/java/org/dromara/akali/strategy/MethodHotspotStrategy.java", "snippet": "public class MethodHotspotStrategy implements AkaliStrategy {\n\n private TimedCache<String, Object> timedCache;\n private SegmentLock segmentLock;\n\n public MethodHotspotStrategy() {\n timedCache = CacheUtil.newTimedCache(1000 * 60);\n timedCache.schedulePrune(1000);\n segmentLock = new SegmentLock(64);\n }\n\n @Override\n public AkaliStrategyEnum getStrategy() {\n return AkaliStrategyEnum.HOT_METHOD;\n }\n\n @Override\n public Object process(Object bean, Method method, Object[] args) throws Exception {\n String hotKey = StrUtil.format(\"{}-{}\", MethodUtil.resolveMethodName(method), DigestUtil.md5Hex(JSON.toJSONString(args)));\n\n\n if (timedCache.containsKey(hotKey)) {\n return timedCache.get(hotKey);\n } else {\n try {\n segmentLock.lockInterruptibleSafe(hotKey);\n if (timedCache.containsKey(hotKey)) {\n return timedCache.get(hotKey);\n }\n Object result = method.invoke(bean, args);\n timedCache.put(hotKey, result);\n return result;\n }finally {\n segmentLock.unlock(hotKey);\n }\n }\n }\n}" } ]
import org.dromara.akali.strategy.FallbackStrategy; import org.dromara.akali.strategy.MethodHotspotStrategy; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
688
package org.dromara.akali.spring; @Configuration public class AkaliAutoConfiguration { @Bean public AkaliScanner akaliScanner(){ return new AkaliScanner(); } @Bean
package org.dromara.akali.spring; @Configuration public class AkaliAutoConfiguration { @Bean public AkaliScanner akaliScanner(){ return new AkaliScanner(); } @Bean
public FallbackStrategy fallbackStrategy(){
0
2023-11-10 07:28:38+00:00
2k
quarkiverse/quarkus-langchain4j
openai/openai-vanilla/deployment/src/test/java/org/acme/examples/aiservices/RemovableChatMemoryTest.java
[ { "identifier": "assertMultipleRequestMessage", "path": "openai/openai-vanilla/deployment/src/test/java/org/acme/examples/aiservices/MessageAssertUtils.java", "snippet": "static void assertMultipleRequestMessage(Map<String, Object> requestAsMap, List<MessageContent> messageContents) {\n assertMessages(requestAsMap, listOfMessages -> {\n assertThat(listOfMessages).asInstanceOf(LIST_MAP).hasSize(messageContents.size()).satisfies(l -> {\n for (int i = 0; i < messageContents.size(); i++) {\n MessageContent messageContent = messageContents.get(i);\n assertThat((Map<String, String>) l.get(i)).satisfies(message -> {\n assertThat(message)\n .containsEntry(\"role\", messageContent.getRole());\n if (messageContent.getContent() == null) {\n if (message.containsKey(\"content\")) {\n assertThat(message).containsEntry(\"content\", null);\n }\n } else {\n assertThat(message).containsEntry(\"content\", messageContent.getContent());\n }\n\n });\n }\n });\n });\n}" }, { "identifier": "assertSingleRequestMessage", "path": "openai/openai-vanilla/deployment/src/test/java/org/acme/examples/aiservices/MessageAssertUtils.java", "snippet": "static void assertSingleRequestMessage(Map<String, Object> requestAsMap, String value) {\n assertMessages(requestAsMap, (listOfMessages -> {\n assertThat(listOfMessages).singleElement(as(MAP_STRING_STRING)).satisfies(message -> {\n assertThat(message)\n .containsEntry(\"role\", \"user\")\n .containsEntry(\"content\", value);\n });\n }));\n}" }, { "identifier": "WiremockUtils", "path": "openai/openai-vanilla/deployment/src/test/java/io/quarkiverse/langchain4j/openai/test/WiremockUtils.java", "snippet": "public class WiremockUtils {\n\n public static final String DEFAULT_TOKEN = \"whatever\";\n private static final String DEFAULT_CHAT_MESSAGE_CONTENT = \"Hello there, how may I assist you today?\";\n private static final String CHAT_MESSAGE_CONTENT_TEMPLATE;\n private static final String DEFAULT_CHAT_RESPONSE_BODY;\n public static final ResponseDefinitionBuilder CHAT_RESPONSE_WITHOUT_BODY;\n private static final ResponseDefinitionBuilder DEFAULT_CHAT_RESPONSE;\n\n static {\n try (InputStream is = getClassLoader().getResourceAsStream(\"chat/default.json\")) {\n CHAT_MESSAGE_CONTENT_TEMPLATE = new String(is.readAllBytes(), StandardCharsets.UTF_8);\n DEFAULT_CHAT_RESPONSE_BODY = String.format(CHAT_MESSAGE_CONTENT_TEMPLATE, DEFAULT_CHAT_MESSAGE_CONTENT);\n CHAT_RESPONSE_WITHOUT_BODY = aResponse().withHeader(\"Content-Type\", \"application/json\");\n DEFAULT_CHAT_RESPONSE = CHAT_RESPONSE_WITHOUT_BODY\n .withBody(DEFAULT_CHAT_RESPONSE_BODY);\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n private static ClassLoader getClassLoader() {\n ClassLoader loader = Thread.currentThread().getContextClassLoader();\n while (loader instanceof QuarkusClassLoader) {\n loader = loader.getParent();\n }\n return loader;\n }\n\n private static ResponseDefinitionBuilder defaultChatCompletionResponse() {\n return DEFAULT_CHAT_RESPONSE;\n }\n\n public static MappingBuilder chatCompletionMapping(String token) {\n return post(urlEqualTo(\"/v1/chat/completions\"))\n .withHeader(\"Authorization\", equalTo(\"Bearer \" + token));\n }\n\n public static RequestPatternBuilder chatCompletionRequestPattern(String token) {\n return postRequestedFor(urlEqualTo(\"/v1/chat/completions\"))\n .withHeader(\"Authorization\", equalTo(\"Bearer \" + token));\n }\n\n public static RequestPatternBuilder chatCompletionRequestPattern(String token, String organization) {\n return chatCompletionRequestPattern(token)\n .withHeader(\"OpenAI-Organization\", equalTo(organization));\n }\n\n public static MappingBuilder moderationMapping(String token) {\n return post(urlEqualTo(\"/v1/moderations\"))\n .withHeader(\"Authorization\", equalTo(\"Bearer \" + token));\n }\n\n public static MappingBuilder defaultChatCompletionsStub() {\n return defaultChatCompletionsStub(DEFAULT_TOKEN);\n }\n\n public static MappingBuilder defaultChatCompletionsStub(String token) {\n return chatCompletionMapping(token)\n .willReturn(defaultChatCompletionResponse());\n }\n\n public static MappingBuilder chatCompletionsMessageContent(Optional<String> token, String messageContent) {\n return chatCompletionMapping(token.orElse(DEFAULT_TOKEN))\n .willReturn(\n CHAT_RESPONSE_WITHOUT_BODY.withBody(String.format(CHAT_MESSAGE_CONTENT_TEMPLATE, messageContent)));\n }\n\n}" } ]
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options; import static dev.langchain4j.data.message.ChatMessageType.AI; import static dev.langchain4j.data.message.ChatMessageType.USER; import static org.acme.examples.aiservices.MessageAssertUtils.assertMultipleRequestMessage; import static org.acme.examples.aiservices.MessageAssertUtils.assertSingleRequestMessage; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; import jakarta.inject.Inject; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.WireMockServer; import com.github.tomakehurst.wiremock.stubbing.ServeEvent; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import dev.langchain4j.data.message.ChatMessage; import dev.langchain4j.data.message.SystemMessage; import dev.langchain4j.service.MemoryId; import dev.langchain4j.service.UserMessage; import dev.langchain4j.store.memory.chat.ChatMemoryStore; import io.quarkiverse.langchain4j.RegisterAiService; import io.quarkiverse.langchain4j.openai.test.WiremockUtils; import io.quarkus.arc.Arc; import io.quarkus.arc.ManagedContext; import io.quarkus.test.QuarkusUnitTest;
1,486
package org.acme.examples.aiservices; public class RemovableChatMemoryTest { public static final int FIRST_MEMORY_ID = 1; public static final int SECOND_MEMORY_ID = 2; private static final int WIREMOCK_PORT = 8089; @RegisterExtension static final QuarkusUnitTest unitTest = new QuarkusUnitTest() .setArchiveProducer(
package org.acme.examples.aiservices; public class RemovableChatMemoryTest { public static final int FIRST_MEMORY_ID = 1; public static final int SECOND_MEMORY_ID = 2; private static final int WIREMOCK_PORT = 8089; @RegisterExtension static final QuarkusUnitTest unitTest = new QuarkusUnitTest() .setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class).addClasses(WiremockUtils.class, MessageAssertUtils.class))
2
2023-11-13 09:10:27+00:00
2k
noear/folkmq
folkmq-test/src/test/java/features/cases/BaseTestCase.java
[ { "identifier": "MqClient", "path": "folkmq/src/main/java/org/noear/folkmq/client/MqClient.java", "snippet": "public interface MqClient extends Closeable {\n /**\n * 连接\n */\n MqClient connect() throws IOException;\n\n /**\n * 断开连接\n */\n void disconnect() throws IOException;\n\n /**\n * 客户端配置\n */\n MqClient config(ClientConfigHandler configHandler);\n\n /**\n * 自动回执\n *\n * @param auto 自动(默认为 true)\n */\n MqClient autoAcknowledge(boolean auto);\n\n /**\n * 订阅主题\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n * @param consumerHandler 消费处理\n */\n void subscribe(String topic, String consumerGroup, MqConsumeHandler consumerHandler) throws IOException;\n\n /**\n * 取消订阅主题\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n */\n void unsubscribe(String topic, String consumerGroup) throws IOException;\n\n /**\n * 同步发布消息\n *\n * @param topic 主题\n * @param message 消息\n */\n void publish(String topic, IMqMessage message) throws IOException;\n\n /**\n * 异步发布消息\n *\n * @param topic 主题\n * @param message 消息\n */\n CompletableFuture<Boolean> publishAsync(String topic, IMqMessage message) throws IOException;\n\n /**\n * 取消发布\n *\n * @param topic 主题\n * @param tid 事务id\n */\n void unpublish(String topic, String tid) throws IOException;\n\n /**\n * 取消发布\n *\n * @param topic 主题\n * @param tid 事务id\n */\n CompletableFuture<Boolean> unpublishAsync(String topic, String tid) throws IOException;\n}" }, { "identifier": "MqServer", "path": "folkmq/src/main/java/org/noear/folkmq/server/MqServer.java", "snippet": "public interface MqServer {\n /**\n * 服务端配置\n */\n MqServer config(ServerConfigHandler configHandler);\n\n /**\n * 配置观察者\n */\n MqServer watcher(MqWatcher watcher);\n\n /**\n * 配置访问账号\n *\n * @param ak 访问者身份\n * @param sk 访问者密钥\n */\n MqServer addAccess(String ak, String sk);\n\n /**\n * 配置访问账号\n *\n * @param accessMap 访问账号集合\n */\n MqServer addAccessAll(Map<String, String> accessMap);\n\n /**\n * 启动\n */\n MqServer start(int port) throws Exception;\n\n /**\n * 停止\n */\n void stop();\n\n\n /**\n * 获取内部服务\n */\n MqServiceInternal getServerInternal();\n}" } ]
import org.noear.folkmq.client.MqClient; import org.noear.folkmq.server.MqServer;
882
package features.cases; /** * @author noear * @since 1.0 */ public abstract class BaseTestCase { private final int port; protected MqServer server;
package features.cases; /** * @author noear * @since 1.0 */ public abstract class BaseTestCase { private final int port; protected MqServer server;
protected MqClient client;
0
2023-11-18 19:09:28+00:00
2k
leluque/java2uml
src/main/java/br/com/luque/java2uml/plantuml/writer/sequencediagram/PlantUMLHelper.java
[ { "identifier": "Message", "path": "src/main/java/br/com/luque/java2uml/core/sequencediagram/model/Message.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Message implements Comparable<Message> {\n private Instant instant;\n private MethodExecution from;\n private MethodExecution to;\n\n public enum Types {\n SYNCHRONOUS, ASYNCHRONOUS, CREATION\n }\n\n private Types type;\n\n public Message(MethodExecution to) {\n setInstant(Instant.now());\n setTo(to);\n setType(getDefaultTypeFor(to));\n }\n\n public Message(MethodExecution to, Types type) {\n setInstant(Instant.now());\n setTo(to);\n setType(type);\n }\n\n public Message(MethodExecution from, MethodExecution to) {\n setInstant(Instant.now());\n setFrom(from);\n setTo(to);\n setType(getDefaultTypeFor(to));\n }\n\n public Message(MethodExecution from, MethodExecution to, Types type) {\n setInstant(Instant.now());\n setFrom(from);\n setTo(to);\n setType(type);\n }\n\n public Instant getInstant() {\n return instant;\n }\n\n private void setInstant(Instant instant) {\n this.instant = Objects.requireNonNull(instant);\n }\n\n public MethodExecution getFrom() {\n return from;\n }\n\n private void setFrom(MethodExecution from) {\n this.from = Objects.requireNonNull(from);\n }\n\n public MethodExecution getTo() {\n return to;\n }\n\n private void setTo(MethodExecution to) {\n this.to = Objects.requireNonNull(to);\n }\n\n public Types getType() {\n return type;\n }\n\n public static Types getDefaultTypeFor(MethodExecution methodExecution) {\n return methodExecution.getMethod().isConstructor() ? Types.CREATION : Types.SYNCHRONOUS;\n }\n\n public void setType(Types type) {\n Objects.requireNonNull(type);\n if ((to.getMethod().isConstructor() && Types.CREATION != type) ||\n (!to.getMethod().isConstructor() && Types.CREATION == type)) {\n throw new IllegalArgumentException(\"The type CREATION must be used for constructors\");\n }\n this.type = type;\n }\n\n @Override\n public int compareTo(Message other) {\n return instant.compareTo((other.instant));\n }\n\n @Override\n public String toString() {\n return from + \" -> \" + to;\n }\n}" }, { "identifier": "MethodExecution", "path": "src/main/java/br/com/luque/java2uml/core/sequencediagram/model/MethodExecution.java", "snippet": "public class MethodExecution {\n private String id;\n private Participant participant;\n private Method method;\n private long threadId;\n\n public MethodExecution(Long threadId, String id, Participant participant, Method method) {\n setThreadId(threadId);\n setId(id);\n setParticipant(participant);\n setMethod(method);\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = Objects.requireNonNull(id);\n }\n\n public long getThreadId() {\n return threadId;\n }\n\n public void setThreadId(long threadId) {\n this.threadId = Objects.requireNonNull(threadId);\n }\n\n public Participant getParticipant() {\n return participant;\n }\n\n private void setParticipant(Participant participant) {\n this.participant = Objects.requireNonNull(participant);\n }\n\n public Method getMethod() {\n return method;\n }\n\n private void setMethod(Method method) {\n this.method = Objects.requireNonNull(method);\n }\n\n public boolean correspondsTo(long threadId, String className, String objectId, boolean constructor, String methodName, String methodReturnType, String... methodParameterTypes) {\n return this.threadId == threadId\n && participant.getClassName().equals(className)\n && Objects.equals(participant.getObjectId(), objectId)\n && method.isConstructor()\n && method.getName().equals(methodName)\n && method.getReturnType().equals(methodReturnType)\n && Arrays.equals(method.getParameterTypes(), methodParameterTypes);\n }\n\n @Override\n public String toString() {\n return participant + \".\" + method;\n }\n}" }, { "identifier": "Participant", "path": "src/main/java/br/com/luque/java2uml/core/sequencediagram/model/Participant.java", "snippet": "public class Participant {\n private Stereotypes stereotype;\n private String objectId;\n private String className;\n\n public Participant(String className, String objectId) {\n this(null, className, objectId);\n }\n\n public Participant(Stereotypes stereotype, String className, String objectId) {\n setStereotype(stereotype);\n setClassName(className);\n setObjectId(objectId);\n }\n\n public Stereotypes getStereotype() {\n return stereotype;\n }\n\n public void setStereotype(Stereotypes stereotype) {\n this.stereotype = stereotype;\n }\n\n public String getObjectId() {\n return objectId;\n }\n\n public void setObjectId(String objectId) {\n this.objectId = objectId;\n }\n\n public String getClassName() {\n return className;\n }\n\n private void setClassName(String className) {\n Objects.requireNonNull(className);\n className = className.trim();\n if (className.isEmpty()) {\n throw new IllegalArgumentException(\"Cannot be empty!\");\n }\n this.className = className;\n }\n\n @Override\n public String toString() {\n return (objectId == null ? \"\" : objectId) + \":\" + className;\n }\n}" } ]
import br.com.luque.java2uml.core.sequencediagram.model.Message; import br.com.luque.java2uml.core.sequencediagram.model.MethodExecution; import br.com.luque.java2uml.core.sequencediagram.model.Participant;
1,467
package br.com.luque.java2uml.plantuml.writer.sequencediagram; public class PlantUMLHelper { public static final String ENTRY_POINT_CLASS_NAME = "Actor"; public static final String ENTRY_POINT_OBJECT_NAME = "actor";
package br.com.luque.java2uml.plantuml.writer.sequencediagram; public class PlantUMLHelper { public static final String ENTRY_POINT_CLASS_NAME = "Actor"; public static final String ENTRY_POINT_OBJECT_NAME = "actor";
public static String getParticipantClassName(MethodExecution methodExecution) {
1
2023-11-10 16:49:58+00:00
2k
javpower/JavaVision
src/main/java/com/github/javpower/javavision/framework/jackson/JacksonConfig.java
[ { "identifier": "JacksonDateDeserializer", "path": "src/main/java/com/github/javpower/javavision/framework/jackson/deserializer/JacksonDateDeserializer.java", "snippet": "public class JacksonDateDeserializer extends JsonDeserializer<Date> {\n\n public static final JacksonDateDeserializer INSTANCE = new JacksonDateDeserializer();\n\n /**\n * 日期格式数组\n */\n private static final String[] DATE_PATTERNS = {\n \"yyyy-MM-dd HH:mm:ss\",\n \"yyyy-MM-dd\",\n };\n\n @Override\n public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {\n String dateString = jsonParser.getText();\n if (dateString == null) {\n return null;\n }\n dateString = dateString.trim();\n if (StringUtils.isBlank(dateString)) {\n return null;\n }\n Date date = null;\n boolean flag = false;\n for (int i = 0; i < DATE_PATTERNS.length; i++) {\n try {\n String datePattern = DATE_PATTERNS[i];\n SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);\n date = simpleDateFormat.parse(dateString);\n flag = true;\n break;\n } catch (ParseException e) {\n }\n }\n if (flag) {\n return date;\n } else {\n throw new IllegalArgumentException(\"不能解析的日期:\" + dateString);\n }\n }\n\n}" }, { "identifier": "JacksonStringDeserializer", "path": "src/main/java/com/github/javpower/javavision/framework/jackson/deserializer/JacksonStringDeserializer.java", "snippet": "public class JacksonStringDeserializer extends JsonDeserializer<String> {\n\n public static final JacksonStringDeserializer INSTANCE = new JacksonStringDeserializer();\n\n @Override\n public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {\n String value = jsonParser.getValueAsString();\n if (value != null) {\n // 去除字符串空格\n value = value.trim();\n }\n return value;\n }\n}" }, { "identifier": "JacksonBigDecimalSerializer", "path": "src/main/java/com/github/javpower/javavision/framework/jackson/serializer/JacksonBigDecimalSerializer.java", "snippet": "public class JacksonBigDecimalSerializer extends JsonSerializer<BigDecimal> {\n @Override\n public void serialize(BigDecimal param, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {\n if (param != null) {\n BigDecimal result = param.setScale(2, BigDecimal.ROUND_HALF_UP);\n jsonGenerator.writeString(result.toString());\n } else {\n jsonGenerator.writeNull();\n }\n\n }\n}" }, { "identifier": "JacksonStringSerializer", "path": "src/main/java/com/github/javpower/javavision/framework/jackson/serializer/JacksonStringSerializer.java", "snippet": "public class JacksonStringSerializer extends JsonSerializer<String> {\n\n public static final JacksonStringSerializer INSTANCE = new JacksonStringSerializer();\n\n @Override\n public void serialize(String string, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {\n if (string != null) {\n // 去除字符串空格\n string = string.trim();\n }\n jsonGenerator.writeString(string);\n }\n}" } ]
import cn.hutool.core.date.DatePattern; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import com.github.javpower.javavision.framework.jackson.deserializer.JacksonDateDeserializer; import com.github.javpower.javavision.framework.jackson.deserializer.JacksonStringDeserializer; import com.github.javpower.javavision.framework.jackson.serializer.JacksonBigDecimalSerializer; import com.github.javpower.javavision.framework.jackson.serializer.JacksonStringSerializer; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.math.BigDecimal; import java.time.ZoneId; import java.util.Date; import java.util.Locale; import java.util.TimeZone;
1,108
package com.github.javpower.javavision.framework.jackson; /** * @author gc.x * @date 2022/4/13 **/ @Configuration public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> { builder.locale(Locale.CHINA); builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault())); builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN); // 反序列化(处理请求参数) // 去掉请求参数中字符串左右两边的空格 builder.deserializerByType(String.class, JacksonStringDeserializer.INSTANCE); builder.deserializerByType(Date.class, JacksonDateDeserializer.INSTANCE); // 序列化(处理响应结果) // 避免long类型精度丢失,将long类型序列化成字符串 builder.serializerByType(Long.class, ToStringSerializer.instance); // 去掉响应结果中字符串左右两边的空格 builder.serializerByType(String.class, JacksonStringSerializer.INSTANCE);
package com.github.javpower.javavision.framework.jackson; /** * @author gc.x * @date 2022/4/13 **/ @Configuration public class JacksonConfig { @Bean public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() { return builder -> { builder.locale(Locale.CHINA); builder.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault())); builder.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN); // 反序列化(处理请求参数) // 去掉请求参数中字符串左右两边的空格 builder.deserializerByType(String.class, JacksonStringDeserializer.INSTANCE); builder.deserializerByType(Date.class, JacksonDateDeserializer.INSTANCE); // 序列化(处理响应结果) // 避免long类型精度丢失,将long类型序列化成字符串 builder.serializerByType(Long.class, ToStringSerializer.instance); // 去掉响应结果中字符串左右两边的空格 builder.serializerByType(String.class, JacksonStringSerializer.INSTANCE);
builder.serializerByType(BigDecimal.class, new JacksonBigDecimalSerializer());
2
2023-11-10 01:57:37+00:00
2k
naveenchr/SpringBoot-SeleniumFramework
src/test/java/com/auto/framework/pageobjects/demoqa/TextBoxPF.java
[ { "identifier": "TEXTBOX_PAGE", "path": "src/main/java/com/auto/framework/constants/Constants.java", "snippet": "public static final String TEXTBOX_PAGE = \"text-box\";" }, { "identifier": "BasePage", "path": "src/test/java/com/auto/framework/pageobjects/common/BasePage.java", "snippet": "@Slf4j\n@Component\n//@Scope(\"driverscope\")\npublic class BasePage extends ActionsBaseClass {\n\n\t@Autowired\n\tpublic IUIElements iUIElements;\n\n\t@Autowired\n\tpublic IElementVerification iElementVerification;\n\n\t@Autowired\n\tpublic IExplicitWait iExplicitWait;\n\n\t@Autowired\n\tpublic IJavaScriptActions iJavaScriptActions;\n\n\tpublic void teardownDriver() {\n\t\tlog.info(\"Taking Screenshots\");\n\t\tattachScreenShot();\n\t\tlog.info(\"Closing Browsers\");\n\t\tif (nonNull(driver)) {\n\t\t\tdriver.close();\n\t\t}\n\t}\n\n\t@Attachment(value = \"Screen shot\", type = \"image/png\", fileExtension = \".png\")\n\tpublic byte[] attachScreenShot() {\n\t\ttry {\n\t\t\treturn ((TakesScreenshot) applicationContext.getBean(WebDriver.class)).getScreenshotAs(OutputType.BYTES);\n\t\t} catch (WebDriverException e) {\n\t\t\tlog.error(\"Selenium screenshot capture failed: {}\", e.getMessage());\n\t\t}\n\t\treturn new byte[0];\n\t}\n\n}" }, { "identifier": "UserModal", "path": "src/test/java/com/auto/framework/testdata/UserModal.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UserModal {\n\tprivate String firstName;\n\tprivate String lastName;\n\tprivate String email;\n\tprivate String currAddress;\n\tprivate String permAddress;\n\tprivate String age;\n\tprivate String salary;\n\tprivate String department;\n\n}" } ]
import static com.auto.framework.constants.Constants.TEXTBOX_PAGE; import org.openqa.selenium.By; import org.springframework.stereotype.Component; import com.auto.framework.pageobjects.common.BasePage; import com.auto.framework.testdata.UserModal; import io.qameta.allure.Step; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j;
699
package com.auto.framework.pageobjects.demoqa; /************************************************************************************************************************ * @Date : Oct. 20, 2023 * @Author : naveenchr * @Description : Page object fragment for Text Box menu * @Version : 1.0 ************************************************************************************************************************/ @Component @AllArgsConstructor @Slf4j public class TextBoxPF extends BasePage { private static By fullnameTF = By.id("userName"); private static By emailTF = By.id("userEmail"); private static By currentAddressTF = By.cssSelector("#currentAddress"); private static By permanentAddressTF = By.xpath("//*[@id='permanentAddress']"); private static By submitButton = By.cssSelector("#submit"); private static By nameText = By.cssSelector("p#name"); private static By emailText = By.cssSelector("p#email"); private static By currAddText = By.cssSelector("p#currentAddress"); private static By permAddText = By.cssSelector("p#permanentAddress"); public void openTextBoxPage() { iUIElements.openURL(myProperties.getDemoUrl() + TEXTBOX_PAGE); }
package com.auto.framework.pageobjects.demoqa; /************************************************************************************************************************ * @Date : Oct. 20, 2023 * @Author : naveenchr * @Description : Page object fragment for Text Box menu * @Version : 1.0 ************************************************************************************************************************/ @Component @AllArgsConstructor @Slf4j public class TextBoxPF extends BasePage { private static By fullnameTF = By.id("userName"); private static By emailTF = By.id("userEmail"); private static By currentAddressTF = By.cssSelector("#currentAddress"); private static By permanentAddressTF = By.xpath("//*[@id='permanentAddress']"); private static By submitButton = By.cssSelector("#submit"); private static By nameText = By.cssSelector("p#name"); private static By emailText = By.cssSelector("p#email"); private static By currAddText = By.cssSelector("p#currentAddress"); private static By permAddText = By.cssSelector("p#permanentAddress"); public void openTextBoxPage() { iUIElements.openURL(myProperties.getDemoUrl() + TEXTBOX_PAGE); }
public void updateTextBoxes(UserModal userData) {
2
2023-11-12 21:51:45+00:00
2k
SpiralMoon/maplestory.openapi
java/src/main/java/dev/spiralmoon/maplestory/api/dto/history/CubeHistoryDTO.java
[ { "identifier": "Utils", "path": "java/src/main/java/dev/spiralmoon/maplestory/api/Utils.java", "snippet": "public class Utils {\n\n public static LocalDateTime toLocalDateTime(@NonNull String date) {\n\n final String[] patterns = {\n \"yyyy-MM-dd'T'HH:mm:ss.SSSX\",\n \"yyyy-MM-dd'T'HH:mmXXX\",\n \"yyyy-MM-dd\"\n };\n\n LocalDateTime kstDateTime = null;\n\n for (String pattern : patterns) {\n try {\n\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);\n\n if (pattern.equals(\"yyyy-MM-dd\")) {\n LocalDate localDate = LocalDate.parse(date, formatter);\n kstDateTime = localDate.atStartOfDay().atZone(ZoneId.of(\"Asia/Seoul\")).toLocalDateTime();\n } else {\n kstDateTime = LocalDateTime.parse(date, formatter).atZone(ZoneId.of(\"Asia/Seoul\")).toLocalDateTime();\n }\n\n break;\n } catch (DateTimeParseException e) {\n // nothing to do\n }\n }\n\n return kstDateTime;\n }\n}" }, { "identifier": "PotentialOptionGrade", "path": "java/src/main/java/dev/spiralmoon/maplestory/api/dto/PotentialOptionGrade.java", "snippet": "@Getter\npublic enum PotentialOptionGrade {\n\n RARE(\"레어\"),\n EPIC(\"에픽\"),\n UNIQUE(\"유니크\"),\n LEGENDARY(\"레전드리\");\n\n private final String grade;\n\n PotentialOptionGrade (String grade) {\n this.grade = grade;\n }\n\n /**\n * 한글로 정의된 잠재옵션 등급을 PotentialOptionGrade으로 변환합니다.\n *\n * @param text support only \"레어\", \"에픽\", \"유니크\", \"레전드리\"\n */\n public static PotentialOptionGrade fromString(String text) {\n for (PotentialOptionGrade grade : PotentialOptionGrade.values()) {\n if (grade.grade.equals(text)) {\n return grade;\n }\n }\n\n throw new IllegalArgumentException(\"No enum constant for string: \" + text);\n }\n}" } ]
import com.google.gson.annotations.SerializedName; import dev.spiralmoon.maplestory.api.Utils; import dev.spiralmoon.maplestory.api.dto.PotentialOptionGrade; import lombok.AllArgsConstructor; import lombok.Data; import lombok.ToString; import java.time.LocalDateTime; import java.util.List;
1,298
package dev.spiralmoon.maplestory.api.dto.history; /** * 큐브 히스토리 */ @AllArgsConstructor @Data @ToString public class CubeHistoryDTO { /** * 큐브 히스토리 식별자 */ @SerializedName("id") private String id; /** * 캐릭터 명 */ @SerializedName("character_name") private String characterName; /** * 월드 명 */ @SerializedName("world_name") private String worldName; /** * 사용 일시 */ @SerializedName("date_create") private String dateCreate; /** * 사용 큐브 */ @SerializedName("cube_type") private String cubeType; /** * 사용 결과 */ @SerializedName("item_upgrade_result") private String itemUpgradeResult; /** * 미라클 타임 적용 여부 */ @SerializedName("miracle_time_flag") private String miracleTimeFlag; /** * 장비 분류 */ @SerializedName("item_equipment_part") private String itemEquipmentPart; /** * 장비 레벨 */ @SerializedName("item_level") private int itemLevel; /** * 큐브 사용한 장비 */ @SerializedName("target_item") private String targetItem; /** * 잠재능력 등급 */ @SerializedName("potential_option_grade") private String potentialOptionGrade; /** * 에디셔널 잠재능력 등급 */ @SerializedName("additional_potential_option_grade") private String additionalPotentialOptionGrade; /** * 천장에 도달하여 확정 등급 상승한 여부 */ @SerializedName("upgradeGuarantee") private boolean upgradeGuarantee; /** * 현재까지 쌓은 스택 */ @SerializedName("upgradeGuaranteeCount") private int upgradeGuaranteeCount; /** * 사용 전 잠재능력 옵션 */ @SerializedName("before_potential_option") private List<CubeResultOptionDTO> beforePotentialOption; /** * 사용 전 에디셔널 잠재능력 옵션 */ @SerializedName("before_additional_potential_option") private List<CubeResultOptionDTO> beforeAdditionalPotentialOption; /** * 사용 후 잠재능력 옵션 */ @SerializedName("after_potential_option") private List<CubeResultOptionDTO> afterPotentialOption; /** * 사용 후 에디셔널 잠재능력 옵션 */ @SerializedName("after_additional_potential_option") private List<CubeResultOptionDTO> afterAdditionalPotentialOption; public boolean isItemUpgrade() { return this.itemUpgradeResult.equals("성공"); } public boolean isMiracleTimeFlag() { return !this.miracleTimeFlag.equals("이벤트 적용되지 않음"); }
package dev.spiralmoon.maplestory.api.dto.history; /** * 큐브 히스토리 */ @AllArgsConstructor @Data @ToString public class CubeHistoryDTO { /** * 큐브 히스토리 식별자 */ @SerializedName("id") private String id; /** * 캐릭터 명 */ @SerializedName("character_name") private String characterName; /** * 월드 명 */ @SerializedName("world_name") private String worldName; /** * 사용 일시 */ @SerializedName("date_create") private String dateCreate; /** * 사용 큐브 */ @SerializedName("cube_type") private String cubeType; /** * 사용 결과 */ @SerializedName("item_upgrade_result") private String itemUpgradeResult; /** * 미라클 타임 적용 여부 */ @SerializedName("miracle_time_flag") private String miracleTimeFlag; /** * 장비 분류 */ @SerializedName("item_equipment_part") private String itemEquipmentPart; /** * 장비 레벨 */ @SerializedName("item_level") private int itemLevel; /** * 큐브 사용한 장비 */ @SerializedName("target_item") private String targetItem; /** * 잠재능력 등급 */ @SerializedName("potential_option_grade") private String potentialOptionGrade; /** * 에디셔널 잠재능력 등급 */ @SerializedName("additional_potential_option_grade") private String additionalPotentialOptionGrade; /** * 천장에 도달하여 확정 등급 상승한 여부 */ @SerializedName("upgradeGuarantee") private boolean upgradeGuarantee; /** * 현재까지 쌓은 스택 */ @SerializedName("upgradeGuaranteeCount") private int upgradeGuaranteeCount; /** * 사용 전 잠재능력 옵션 */ @SerializedName("before_potential_option") private List<CubeResultOptionDTO> beforePotentialOption; /** * 사용 전 에디셔널 잠재능력 옵션 */ @SerializedName("before_additional_potential_option") private List<CubeResultOptionDTO> beforeAdditionalPotentialOption; /** * 사용 후 잠재능력 옵션 */ @SerializedName("after_potential_option") private List<CubeResultOptionDTO> afterPotentialOption; /** * 사용 후 에디셔널 잠재능력 옵션 */ @SerializedName("after_additional_potential_option") private List<CubeResultOptionDTO> afterAdditionalPotentialOption; public boolean isItemUpgrade() { return this.itemUpgradeResult.equals("성공"); } public boolean isMiracleTimeFlag() { return !this.miracleTimeFlag.equals("이벤트 적용되지 않음"); }
public PotentialOptionGrade getPotentialOptionGradeEnum() {
1
2023-11-14 17:53:10+00:00
2k
feiniaojin/graceful-response-boot2
src/test/java/com/feiniaojin/gracefulresponse/test/cases/Test0.java
[ { "identifier": "TestApplication", "path": "src/test/java/com/feiniaojin/gracefulresponse/test/app/TestApplication.java", "snippet": "@SpringBootApplication\n@EnableGracefulResponse\npublic class TestApplication {\n public static void main(String[] args) {\n SpringApplication.run(TestApplication.class, args);\n }\n}" }, { "identifier": "ExtendProperties", "path": "src/test/java/com/feiniaojin/gracefulresponse/test/app/dto/ExtendProperties.java", "snippet": "public class ExtendProperties {\n @NotNull(message = \"扩展属性property1不能为空\")\n private String property1;\n\n public String getProperty1() {\n return property1;\n }\n\n public void setProperty1(String property1) {\n this.property1 = property1;\n }\n}" }, { "identifier": "UserInfoCommand", "path": "src/test/java/com/feiniaojin/gracefulresponse/test/app/dto/UserInfoCommand.java", "snippet": "public class UserInfoCommand {\n @NotNull(message = \"userId is null !\")\n private Long userId;\n\n @NotNull(message = \"userName is null !\")\n @Length(min = 6, max = 12)\n @ValidationStatusCode(code = \"520\")\n private String userName;\n\n @NotNull(message = \"extendProperties is null !\")\n @Valid\n private ExtendProperties extendProperties;\n\n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public ExtendProperties getExtendProperties() {\n return extendProperties;\n }\n\n public void setExtendProperties(ExtendProperties extendProperties) {\n this.extendProperties = extendProperties;\n }\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import com.feiniaojin.gracefulresponse.test.app.TestApplication; import com.feiniaojin.gracefulresponse.test.app.dto.ExtendProperties; import com.feiniaojin.gracefulresponse.test.app.dto.UserInfoCommand; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.result.StatusResultMatchers; import java.util.HashMap; import java.util.Map;
1,554
package com.feiniaojin.gracefulresponse.test.cases; @SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @TestPropertySource(properties = {"spring.config.location=classpath:application-test0.yaml"}) public class Test0 { @Test @DisplayName("测试返回空") public void testVoidResponse(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/example/voidResponse"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("0"); actions.andExpectAll(statusMatcher, codeMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("测试执行成功统一封装") public void testSuccess(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/example/success"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("0"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isNotEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("自定义异常+异常码+运行时异常") public void testRuntime(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/example/runtime"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("1024"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("DTO内参数校验") public void testValidateDto(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/example/validateDto"); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("userName","userName"); ObjectMapper objectMapper = new ObjectMapper(); String reqBody = objectMapper.writeValueAsString(paramMap); requestBuilder.content(reqBody); requestBuilder.contentType("application/json"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("1"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("Controller方法入参校验") public void testValidateMethodParam(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/example/validateMethodParam"); Map<String, Object> paramMap = new HashMap<>(); ObjectMapper objectMapper = new ObjectMapper(); String reqBody = objectMapper.writeValueAsString(paramMap); requestBuilder.content(reqBody); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("1314"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("级联校验") public void testValidatePropertyType(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/example/validate/propertyType"); UserInfoCommand command=new UserInfoCommand(); command.setUserId(1L); command.setUserName("userName");
package com.feiniaojin.gracefulresponse.test.cases; @SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc @TestPropertySource(properties = {"spring.config.location=classpath:application-test0.yaml"}) public class Test0 { @Test @DisplayName("测试返回空") public void testVoidResponse(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/example/voidResponse"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("0"); actions.andExpectAll(statusMatcher, codeMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("测试执行成功统一封装") public void testSuccess(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/example/success"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("0"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isNotEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("自定义异常+异常码+运行时异常") public void testRuntime(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/example/runtime"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("1024"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("DTO内参数校验") public void testValidateDto(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/example/validateDto"); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("userName","userName"); ObjectMapper objectMapper = new ObjectMapper(); String reqBody = objectMapper.writeValueAsString(paramMap); requestBuilder.content(reqBody); requestBuilder.contentType("application/json"); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("1"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("Controller方法入参校验") public void testValidateMethodParam(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/example/validateMethodParam"); Map<String, Object> paramMap = new HashMap<>(); ObjectMapper objectMapper = new ObjectMapper(); String reqBody = objectMapper.writeValueAsString(paramMap); requestBuilder.content(reqBody); ResultActions actions = mockMvc.perform(requestBuilder); StatusResultMatchers status = MockMvcResultMatchers.status(); ResultMatcher statusMatcher = status.is(200); ResultMatcher codeMatcher = MockMvcResultMatchers.jsonPath("$.status.code").value("1314"); ResultMatcher payloadMatcher = MockMvcResultMatchers.jsonPath("$.payload").isEmpty(); actions.andExpectAll(statusMatcher, codeMatcher, payloadMatcher).andDo(MockMvcResultHandlers.print()); } @Test @DisplayName("级联校验") public void testValidatePropertyType(@Autowired MockMvc mockMvc) throws Exception { MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post("/example/validate/propertyType"); UserInfoCommand command=new UserInfoCommand(); command.setUserId(1L); command.setUserName("userName");
ExtendProperties properties = new ExtendProperties();
1
2023-11-15 10:54:19+00:00
2k
BlyznytsiaOrg/bring
core/src/test/java/io/github/blyznytsiaorg/bring/core/bpp/BeanPostProcessorFactoryConstructorLimitationTest.java
[ { "identifier": "BringApplication", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/BringApplication.java", "snippet": "@Slf4j\npublic class BringApplication {\n private static final String BRING_PACKAGE = \"io.github.blyznytsiaorg\";\n\n /**\n * Private constructor to prevent instantiation of the class.\n * Instances of this class should be created using the static methods {@link #run(Class)} or {@link #run(String)}.\n */\n private BringApplication() {\n }\n\n /**\n * Run the Bring application context based on the provided configuration class.\n *\n * @param clazz the class containing configuration information and annotated beans\n * @return the initialized {@link BringApplicationContext} instance\n * @see BringApplicationContext\n */\n public static BringApplicationContext run(Class<?> clazz) {\n // print banner\n Banner.printBanner();\n\n // Create context: register Bean definitions\n String[] bringPackages = new String[]{BRING_PACKAGE, clazz.getPackageName()};\n BringApplicationContext context = new BringApplicationContext(bringPackages);\n log.info(\"Starting application\");\n // Invoke Bean Post Processors, create Bean objects\n context.refresh();\n \n return context;\n }\n\n /**\n * Run the Bring application context based on the provided base package for component scanning.\n *\n * @param basePackage the base package to scan for annotated beans\n * @return the initialized {@link BringApplicationContext} instance\n * @see BringApplicationContext\n */\n public static BringApplicationContext run(String basePackage) {\n // print banner\n Banner.printBanner();\n\n // Create context: register Bean definitions\n String[] bringPackages = new String[]{BRING_PACKAGE, basePackage};\n BringApplicationContext context = new BringApplicationContext(bringPackages);\n\n // Invoke Bean Post Processors, create Bean objects\n context.refresh();\n\n return context;\n }\n\n /**\n * Run the Bring application context based on the provided base package for component scanning.\n *\n * @param basePackages the base packages to scan for annotated beans\n * @return the initialized {@link BringApplicationContext} instance\n */\n public static BringApplicationContext run(String... basePackages) {\n // print banner\n Banner.printBanner();\n\n // Create context: register Bean definitions\n String[] bringPackages = basePackages(basePackages);\n\n BringApplicationContext context = new BringApplicationContext(bringPackages);\n\n // Invoke Bean Post Processors, create Bean objects\n context.refresh();\n\n return context;\n }\n\n private static String[] basePackages(String... basePackage) {\n String[] bringPackages = new String[basePackage.length + 1];\n bringPackages[0] = BRING_PACKAGE;\n System.arraycopy(basePackage, 0, bringPackages, 1, basePackage.length);\n return bringPackages;\n }\n \n}" }, { "identifier": "BeanPostProcessorConstructionLimitationException", "path": "core/src/main/java/io/github/blyznytsiaorg/bring/core/exception/BeanPostProcessorConstructionLimitationException.java", "snippet": "public class BeanPostProcessorConstructionLimitationException extends RuntimeException {\n /**\n * Constructs a new BeanPostProcessorConstructionLimitationException with the specified detail message.\n *\n * @param message The detail message describing the limitation or issue encountered\n */\n public BeanPostProcessorConstructionLimitationException(String message) {\n super(message);\n }\n}" } ]
import io.github.blyznytsiaorg.bring.core.BringApplication; import io.github.blyznytsiaorg.bring.core.exception.BeanPostProcessorConstructionLimitationException; import lombok.SneakyThrows; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows;
1,009
package io.github.blyznytsiaorg.bring.core.bpp; class BeanPostProcessorFactoryConstructorLimitationTest { @SneakyThrows @DisplayName("Should throw exception when bpp without default constructor") @Test void shouldThrowExceptionWhenBppWithoutDefaultConstructor() { //given var expectedMessage = "BeanProcessor 'NoDefaultConstructorBeanPostProcessor' should have only default constructor without params"; Executable executable = () -> { //when
package io.github.blyznytsiaorg.bring.core.bpp; class BeanPostProcessorFactoryConstructorLimitationTest { @SneakyThrows @DisplayName("Should throw exception when bpp without default constructor") @Test void shouldThrowExceptionWhenBppWithoutDefaultConstructor() { //given var expectedMessage = "BeanProcessor 'NoDefaultConstructorBeanPostProcessor' should have only default constructor without params"; Executable executable = () -> { //when
BringApplication.run("testdata.bpp", "testdata.bpp");
0
2023-11-10 13:42:05+00:00
2k
RIA-AED/RIABandwidthSaver
src/main/java/com/ghostchu/plugins/riabandwidthsaver/RIABandwidthSaver.java
[ { "identifier": "CMIHook", "path": "src/main/java/com/ghostchu/plugins/riabandwidthsaver/hooks/cmi/CMIHook.java", "snippet": "public class CMIHook extends AFKHook implements Listener {\n\n public CMIHook(RIABandwidthSaver plugin) {\n super(plugin);\n }\n\n @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)\n public void onPlayerAfk(CMIAfkEnterEvent event) {\n getPlugin().playerEcoEnable(event.getPlayer());\n }\n\n @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)\n public void onPlayerLeaveAfk(CMIAfkLeaveEvent event) {\n getPlugin().playerEcoDisable(event.getPlayer());\n }\n}" }, { "identifier": "ESSXHook", "path": "src/main/java/com/ghostchu/plugins/riabandwidthsaver/hooks/essx/ESSXHook.java", "snippet": "public class ESSXHook extends AFKHook {\n public ESSXHook(RIABandwidthSaver plugin) {\n super(plugin);\n }\n\n @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR)\n public void onPlayerAfk(AfkStatusChangeEvent event) {\n if (event.getValue()) {\n getPlugin().playerEcoEnable(event.getAffected().getBase());\n } else {\n getPlugin().playerEcoDisable(event.getAffected().getBase());\n }\n }\n\n}" } ]
import com.comphenix.protocol.PacketType; import com.comphenix.protocol.ProtocolLibrary; import com.comphenix.protocol.events.*; import com.comphenix.protocol.injector.temporary.TemporaryPlayer; import com.ghostchu.plugins.riabandwidthsaver.hooks.cmi.CMIHook; import com.ghostchu.plugins.riabandwidthsaver.hooks.essx.ESSXHook; import io.netty.buffer.ByteBuf; import io.netty.util.ReferenceCountUtil; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.*; import java.util.stream.Collectors; import java.util.stream.Stream;
835
package com.ghostchu.plugins.riabandwidthsaver; public final class RIABandwidthSaver extends JavaPlugin implements Listener { private final Set<UUID> AFK_PLAYERS = new HashSet<>(); private final Map<PacketType, PacketInfo> PKT_TYPE_STATS = new ConcurrentHashMap<>(); private final Map<UUID, PacketInfo> PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>(); private final Map<PacketType, PacketInfo> UNFILTERED_PKT_TYPE_STATS = new ConcurrentHashMap<>(); private final Map<UUID, PacketInfo> UNFILTERED_PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>(); private final ThreadLocalRandom RANDOM = ThreadLocalRandom.current(); private boolean calcAllPackets = false; private final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); private final List<AFKHook> afkHooks = new ArrayList<>(); @Override public void onEnable() { // Plugin startup logic saveDefaultConfig(); Bukkit.getPluginManager().registerEvents(this, this); reloadConfig(); scanHooks(); } private void scanHooks() { if(Bukkit.getPluginManager().getPlugin("CMI") != null){ afkHooks.add(new CMIHook(this)); getLogger().info("CMI AFK状态钩子已注册!"); } if(Bukkit.getPluginManager().getPlugin("Essentials") != null){
package com.ghostchu.plugins.riabandwidthsaver; public final class RIABandwidthSaver extends JavaPlugin implements Listener { private final Set<UUID> AFK_PLAYERS = new HashSet<>(); private final Map<PacketType, PacketInfo> PKT_TYPE_STATS = new ConcurrentHashMap<>(); private final Map<UUID, PacketInfo> PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>(); private final Map<PacketType, PacketInfo> UNFILTERED_PKT_TYPE_STATS = new ConcurrentHashMap<>(); private final Map<UUID, PacketInfo> UNFILTERED_PLAYER_PKT_SAVED_STATS = new ConcurrentHashMap<>(); private final ThreadLocalRandom RANDOM = ThreadLocalRandom.current(); private boolean calcAllPackets = false; private final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor(); private final List<AFKHook> afkHooks = new ArrayList<>(); @Override public void onEnable() { // Plugin startup logic saveDefaultConfig(); Bukkit.getPluginManager().registerEvents(this, this); reloadConfig(); scanHooks(); } private void scanHooks() { if(Bukkit.getPluginManager().getPlugin("CMI") != null){ afkHooks.add(new CMIHook(this)); getLogger().info("CMI AFK状态钩子已注册!"); } if(Bukkit.getPluginManager().getPlugin("Essentials") != null){
afkHooks.add(new ESSXHook(this));
1
2023-11-18 11:52:47+00:00
2k
Samuel-Ricardo/Pic-Pay_simplified
src/test/java/com/picpay/payment/data/UserData.java
[ { "identifier": "User", "path": "src/main/java/com/picpay/payment/domain/entities/user/User.java", "snippet": "@Entity(name = \"tb_users\") @Table(name = \"tb_users\")\n@AllArgsConstructor @NoArgsConstructor\n@EqualsAndHashCode(of = \"id\")\n@Getter @Setter\npublic class User implements UserDetails {\n\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n\n private String firstName;\n private String lastName;\n\n @Column(unique = true)\n private String email;\n private String password;\n\n @Column(unique = true)\n private String document;\n private BigDecimal balance;\n @Enumerated(EnumType.STRING)\n private UserType userType;\n\n @Enumerated\n private Role role;\n\n\n public static User from(UserDTO dto) {\n var user = new User();\n BeanUtils.copyProperties(dto, user);\n\n return user;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return role.getAuthorities();\n }\n\n @Override\n public String getUsername() {\n return email;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n}" }, { "identifier": "Role", "path": "src/main/java/com/picpay/payment/domain/entities/auth/Role.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic enum Role {\n USER (\n Set.of(\n READ_USER,\n EXECUTE_TRANSACTION,\n READ_TRANSACTION\n )\n ),\n ADMIN(\n Stream.concat(\n USER.permissions.stream(),\n Set.of(\n DELETE_USER,\n CREATE_USER,\n UPDATE_USER\n ).stream()\n ).collect(Collectors.toSet())\n\n );\n\n private final Set<Permissions> permissions;\n\n public List<SimpleGrantedAuthority> getAuthorities() {\n var authorities = getPermissions()\n .stream()\n .map(permission -> new SimpleGrantedAuthority(permission.getPermission()))\n .collect(Collectors.toSet());\n\n authorities.add(new SimpleGrantedAuthority(\"ROLE_\"+this.name()));\n return authorities.stream().toList();\n }\n}" }, { "identifier": "UserType", "path": "src/main/java/com/picpay/payment/domain/entities/user/UserType.java", "snippet": "public enum UserType {\n COMMON,\n MERCHANT,\n}" } ]
import com.picpay.payment.domain.dto.user.UserDTO; import com.picpay.payment.domain.entities.user.User; import org.springframework.test.context.ActiveProfiles; import static com.picpay.payment.domain.entities.auth.Role.*; import static com.picpay.payment.domain.entities.user.UserType.*; import java.math.BigDecimal; import java.util.Random; import java.util.UUID; import java.util.function.Function; import java.util.random.RandomGenerator;
734
package com.picpay.payment.data; @ActiveProfiles("test") public class UserData { public static final UserDTO VALID_COMMON_USER_DATA = new UserDTO(
package com.picpay.payment.data; @ActiveProfiles("test") public class UserData { public static final UserDTO VALID_COMMON_USER_DATA = new UserDTO(
"User",
0
2023-11-18 18:00:28+00:00
2k
sondosaabed/Taskaty
app/src/main/java/com/taskaty/informational/GettingStarted.java
[ { "identifier": "Preferences", "path": "app/src/main/java/com/taskaty/model/Preferences.java", "snippet": "public class Preferences {\n /*\n Attriutes\n */\n // I initialize Sample Tasks in the tasks list\n static Task t1 = new Task(0,\"Smile to a Stranger\",\"Today I will smile and make someone happy\",\"\",null, false);\n static Task t2 = new Task(1,\"Submit Assignment 1\",\"Your mobile course work\",\"Study\", LocalDate.parse(\"2023-11-18\"), true);\n private static final String DATA = \"DATA\";\n private static final String FIRST_TIME = \"is_first_time\";\n private static SharedPreferences preferences;\n private static SharedPreferences.Editor editor;\n\n /*\n I created these two methods in order to show diffrent activities when the user starts or gets back\n */\n public static boolean isFirstTime(Context context) {\n preferences = getPreferences(context);\n return preferences.getBoolean(FIRST_TIME, true);\n }\n\n public static void setNotFirstTime(Context context) {\n preferences = getPreferences(context);\n editor = preferences.edit();\n editor.putBoolean(FIRST_TIME, false);\n editor.apply();\n }\n\n public static ArrayList<Task> initializeTaskatySample(){\n return new ArrayList<>(Arrays.asList(t1, t2));\n }\n\n public static ArrayList<Task> loadTasks(Context context) {\n preferences = getPreferences(context);\n Gson gson = new Gson();\n String str = preferences.getString(DATA, \"\");\n Task[] tasks = gson.fromJson(str, Task[].class);\n if(tasks != null){\n return new ArrayList<>(Arrays.asList(tasks));\n }\n return initializeTaskatySample();\n }\n\n /*\n I created this method to save the tasks list which I called after each modification on the list\n */\n public static void saveTaskaty(ArrayList<Task> tasks) {\n Gson gson = new Gson();\n String str = gson.toJson(tasks);\n editor.putString(DATA, str);\n editor.apply();\n }\n\n public static SharedPreferences getPreferences(Context context) {\n if (preferences == null) {\n preferences = PreferenceManager.getDefaultSharedPreferences(context);\n editor = preferences.edit();\n }\n return preferences;\n }\n}" }, { "identifier": "TasksList", "path": "app/src/main/java/com/taskaty/taskManagment/TasksList.java", "snippet": "public class TasksList extends AppCompatActivity{\n /*\n Attributes\n */\n ImageButton add;\n Button search;\n ListView tasksVeiw;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n initialize();\n }\n\n private void initialize() {\n if(getSupportActionBar()!=null)\n getSupportActionBar().hide();\n setContentView(R.layout.tasks_list);\n\n setAdd(findViewById(R.id.add));\n setTasks(findViewById(R.id.taskListView));\n setSearch(findViewById(R.id.search));\n\n Tasks.initTasks(this);\n\n ArrayAdapter<Task> listAdapter = new ArrayAdapter<>(this,\n android.R.layout.simple_list_item_1,\n Tasks.getTaskaty());\n getTasks().setAdapter(listAdapter);\n\n handle_add(getAdd());\n handle_taskClick(getTasks());\n handle_search(getSearch());\n }\n\n private void handle_search(Button search) {\n /*\n When a user searches for a task by it's name\n - if it's not found the status inform of not found will be shown\n */\n search.setOnClickListener(veiw->{\n Intent intent = new Intent(this, FindTasks.class);\n startActivity(intent);\n });\n }\n\n private void handle_taskClick(ListView tasks) {\n /*\n When a user clicks on a list item they are allowed to edit it\n */\n tasks.setOnItemClickListener((parent, view, position, id) -> {\n Intent intent = new Intent(this, EditTask.class);\n intent.putExtra(\"selectedTaskID\", position);\n startActivity(intent);\n });\n }\n\n private void handle_add(ImageButton add) {\n /*\n When the user clicks Add, the user is able to fill a form and add a new one\n */\n add.setOnClickListener(veiw->{\n Intent intent = new Intent(this, AddNewTask.class);\n startActivity(intent);\n });\n }\n\n /*\n Getters & Setters\n */\n public void setAdd(ImageButton add) {\n this.add = add;\n }\n public ImageButton getAdd() {\n return add;\n }\n public void setTasks(ListView tasks) {\n this.tasksVeiw = tasks;\n }\n public ListView getTasks() {\n return tasksVeiw;\n }\n public Button getSearch() {\n return search;\n }\n public void setSearch(Button search) {\n this.search = search;\n }\n}" } ]
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.widget.Button; import com.taskaty.model.Preferences; import com.taskaty.taskManagment.TasksList; import com.taskaty.R;
1,412
package com.taskaty.informational; /* This is the starting activity of the mobile app, the user is able to start */ public class GettingStarted extends AppCompatActivity { /* Attributes */ Button start; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Check if it's the first time for the user using taskaty if so show them getting started otherwise show them welcome back for more personalized experience */ if (Preferences.isFirstTime(this)) { Preferences.setNotFirstTime(this); setContentView(R.layout.getting_started); initialize(); } else { startActivity(new Intent(this, WelcomeBack.class)); finish(); } } private void initialize() { if(getSupportActionBar()!=null) getSupportActionBar().hide(); setContentView(R.layout.getting_started); setStart(findViewById(R.id.start)); handle_start(getStart()); } private void handle_start(Button start) { /* When the start button is clicked show the main tasks list It will contain two sample task I added */ start.setOnClickListener(view -> {
package com.taskaty.informational; /* This is the starting activity of the mobile app, the user is able to start */ public class GettingStarted extends AppCompatActivity { /* Attributes */ Button start; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* Check if it's the first time for the user using taskaty if so show them getting started otherwise show them welcome back for more personalized experience */ if (Preferences.isFirstTime(this)) { Preferences.setNotFirstTime(this); setContentView(R.layout.getting_started); initialize(); } else { startActivity(new Intent(this, WelcomeBack.class)); finish(); } } private void initialize() { if(getSupportActionBar()!=null) getSupportActionBar().hide(); setContentView(R.layout.getting_started); setStart(findViewById(R.id.start)); handle_start(getStart()); } private void handle_start(Button start) { /* When the start button is clicked show the main tasks list It will contain two sample task I added */ start.setOnClickListener(view -> {
Intent intent = new Intent(this, TasksList.class);
1
2023-11-10 13:10:12+00:00
2k
Charles7c/continew-starter
continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/IpUtils.java
[ { "identifier": "ProjectProperties", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/autoconfigure/project/ProjectProperties.java", "snippet": "@Data\n@ConfigurationProperties(prefix = \"project\")\npublic class ProjectProperties {\n\n /**\n * 名称\n */\n private String name;\n\n /**\n * 应用名称\n */\n private String appName;\n\n /**\n * 版本\n */\n private String version;\n\n /**\n * 描述\n */\n private String description;\n\n /**\n * URL\n */\n private String url;\n\n /**\n * 基本包\n */\n private String basePackage;\n\n /**\n * 联系人\n */\n private Contact contact;\n\n /**\n * 许可协议\n */\n private License license;\n\n /**\n * 是否为生产环境\n */\n private boolean production = false;\n\n /**\n * 是否启用本地解析 IP 归属地\n */\n public static final boolean IP_ADDR_LOCAL_PARSE_ENABLED;\n\n static {\n IP_ADDR_LOCAL_PARSE_ENABLED = SpringUtil.getProperty(\"project.ip-addr-local-parse-enabled\", boolean.class, false)\n || SpringUtil.getProperty(\"project.ipAddrLocalParseEnabled\", boolean.class, false);\n }\n\n /**\n * 联系人配置属性\n */\n @Data\n public static class Contact {\n /**\n * 名称\n */\n private String name;\n\n /**\n * 邮箱\n */\n private String email;\n\n /**\n * URL\n */\n private String url;\n }\n\n /**\n * 许可协议配置属性\n */\n @Data\n public static class License {\n /**\n * 名称\n */\n private String name;\n\n /**\n * URL\n */\n private String url;\n }\n}" }, { "identifier": "StringConstants", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/constant/StringConstants.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class StringConstants implements StrPool {\n\n /**\n * 空字符串\n */\n public static final String EMPTY = \"\";\n\n /**\n * 空格\n */\n public static final String SPACE = \" \";\n\n /**\n * 分号\n */\n public static final String SEMICOLON = \";\";\n\n /**\n * 星号\n */\n public static final String ASTERISK = \"*\";\n\n /**\n * 问号\n */\n public static final String QUESTION_MARK = \"?\";\n\n /**\n * 中文逗号\n */\n public static final String CHINESE_COMMA = \",\";\n\n /**\n * 路径模式\n */\n public static final String PATH_PATTERN = \"/**\";\n}" } ]
import top.charles7c.continew.starter.core.constant.StringConstants; import java.util.Set; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.net.NetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.spring.SpringUtil; import cn.hutool.http.HtmlUtil; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.dreamlu.mica.ip2region.core.Ip2regionSearcher; import net.dreamlu.mica.ip2region.core.IpInfo; import top.charles7c.continew.starter.core.autoconfigure.project.ProjectProperties;
1,244
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.core.util; /** * IP 工具类 * * @author Charles7c * @since 1.0.0 */ @Slf4j @NoArgsConstructor(access = AccessLevel.PRIVATE) public class IpUtils { /** * 太平洋网开放 API:查询 IP 归属地 */ private static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true"; /** * 查询 IP 归属地 * * @param ip IP 地址 * @return IP 归属地 */ public static String getAddress(String ip) {
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.core.util; /** * IP 工具类 * * @author Charles7c * @since 1.0.0 */ @Slf4j @NoArgsConstructor(access = AccessLevel.PRIVATE) public class IpUtils { /** * 太平洋网开放 API:查询 IP 归属地 */ private static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp?ip=%s&json=true"; /** * 查询 IP 归属地 * * @param ip IP 地址 * @return IP 归属地 */ public static String getAddress(String ip) {
if (ProjectProperties.IP_ADDR_LOCAL_PARSE_ENABLED) {
0
2023-11-16 15:48:18+00:00
2k
rafaelsantos01/icaro
src/main/java/com/mail/icaro/modules/email/service/sendNewEmailSync/SendNewEmailSyncService.java
[ { "identifier": "SendNewEmailSyncRequestDTO", "path": "src/main/java/com/mail/icaro/modules/email/service/sendNewEmailSync/dto/SendNewEmailSyncRequestDTO.java", "snippet": "@Getter\n@Setter\npublic class SendNewEmailSyncRequestDTO {\n\n @NotNull\n @NotBlank\n @NotEmpty\n @Email\n private String userMail;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String title;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String content;\n}" }, { "identifier": "SendNewEmailSyncResponseDTO", "path": "src/main/java/com/mail/icaro/modules/email/service/sendNewEmailSync/dto/SendNewEmailSyncResponseDTO.java", "snippet": "@Getter\n@Setter\npublic class SendNewEmailSyncResponseDTO {\n\n private String userMail;\n\n private String title;\n\n private String content;\n\n private UUID id;\n\n private boolean sync;\n\n}" }, { "identifier": "ShippingHistory", "path": "src/main/java/com/mail/icaro/modules/history/entity/ShippingHistory.java", "snippet": "@Getter\n@Setter\n\n@Entity\n@Table(name = \"shipping_history\")\npublic class ShippingHistory extends DateBase {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\", columnDefinition = \"uuid\")\n private UUID id;\n\n @Column(name = \"content\")\n private String content;\n\n @Column(name = \"title\")\n private String title;\n\n @Column(name = \"user_mail\")\n private String userMail;\n\n @Column(name = \"sync\")\n private Boolean sync;\n\n @Column(name = \"fail_send\")\n private Boolean failSend;\n\n}" }, { "identifier": "ShippingHistoryRepository", "path": "src/main/java/com/mail/icaro/modules/history/repository/ShippingHistoryRepository.java", "snippet": "@Repository\npublic interface ShippingHistoryRepository extends JpaRepository<ShippingHistory, UUID> {\n List<ShippingHistory> findBySyncFalseAndFailSendNull();\n List<ShippingHistory> findBySyncFalse();\n}" }, { "identifier": "SendNewEmailDTO", "path": "src/main/java/com/mail/icaro/modules/email/service/sendNewEmail/dto/SendNewEmailDTO.java", "snippet": "@Getter\n@Setter\npublic class SendNewEmailDTO {\n\n @NotNull\n @NotBlank\n @NotEmpty\n @Email\n private String userMail;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String title;\n\n @NotNull\n @NotBlank\n @NotEmpty\n private String content;\n}" }, { "identifier": "SendEmailServiceSimpleDTO", "path": "src/main/java/com/mail/icaro/shared/sendEmail/dtos/SendEmailServiceSimpleDTO.java", "snippet": "@Getter\n@Setter\npublic class SendEmailServiceSimpleDTO {\n\n @NotNull @NotBlank @NotEmpty\n private String userMail;\n\n @NotNull @NotBlank @NotEmpty\n private String title;\n\n @NotNull @NotBlank @NotEmpty\n private String content;\n\n}" }, { "identifier": "SendMailServiceSimple", "path": "src/main/java/com/mail/icaro/shared/sendEmail/service/SendMailServiceSimple.java", "snippet": "@Log4j2\n\n@Service\npublic class SendMailServiceSimple {\n\n @Autowired\n private JavaMailSender javaMailSender;\n\n public boolean execute(SendEmailServiceSimpleDTO data){\n try{\n MimeMessage message = javaMailSender.createMimeMessage();\n MimeMessageHelper helper = new MimeMessageHelper(message, true);\n\n helper.setTo(data.getUserMail());\n helper.setSubject(data.getTitle());\n helper.setText(data.getContent(), true);\n\n javaMailSender.send(message);\n\n log.info(\"Email enviado com sucesso\");\n return true;\n }catch (Exception e){\n log.error(\"Error when sending simple email\",e);\n return false;\n }\n }\n}" } ]
import com.mail.icaro.modules.email.service.sendNewEmailSync.dto.SendNewEmailSyncRequestDTO; import com.mail.icaro.modules.email.service.sendNewEmailSync.dto.SendNewEmailSyncResponseDTO; import com.mail.icaro.modules.history.entity.ShippingHistory; import com.mail.icaro.modules.history.repository.ShippingHistoryRepository; import com.mail.icaro.modules.email.service.sendNewEmail.dto.SendNewEmailDTO; import com.mail.icaro.shared.sendEmail.dtos.SendEmailServiceSimpleDTO; import com.mail.icaro.shared.sendEmail.service.SendMailServiceSimple; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;
1,069
package com.mail.icaro.modules.email.service.sendNewEmailSync; @Service public class SendNewEmailSyncService { @Autowired ShippingHistoryRepository shippingHistoryRepository; @Autowired SendMailServiceSimple sendMailServiceSimple;
package com.mail.icaro.modules.email.service.sendNewEmailSync; @Service public class SendNewEmailSyncService { @Autowired ShippingHistoryRepository shippingHistoryRepository; @Autowired SendMailServiceSimple sendMailServiceSimple;
public SendNewEmailSyncResponseDTO execute(SendNewEmailSyncRequestDTO data){
0
2023-11-12 21:58:03+00:00
2k
GoogleCloudPlatform/dataproc-trino-autoscaler
src/main/java/com/google/cloud/solutions/trinoscaler/scaler/ClusterScaleLogic.java
[ { "identifier": "emptyOrImmutableList", "path": "src/main/java/com/google/cloud/solutions/trinoscaler/Utils.java", "snippet": "public static <T> ImmutableList<T> emptyOrImmutableList(List<T> list) {\n return (list == null) ? ImmutableList.of() : ImmutableList.copyOf(list);\n}" }, { "identifier": "ClusterMetrics", "path": "src/main/java/com/google/cloud/solutions/trinoscaler/ClusterMetrics.java", "snippet": "@AutoValue\npublic abstract class ClusterMetrics {\n\n public abstract ClusterInformation clusterInformation();\n\n public abstract Double avgCpuUtilization();\n\n public abstract ImmutableList<WorkerMetrics> workerMetrics();\n\n public static ClusterMetrics create(\n ClusterInformation clusterInformation,\n Double avgCpuUtilization,\n List<WorkerMetrics> workerMetrics) {\n return new AutoValue_ClusterMetrics(\n clusterInformation, avgCpuUtilization, emptyOrImmutableList(workerMetrics));\n }\n\n /** Record class for a single worker's CPU utilization metric. */\n @AutoValue\n public abstract static class WorkerMetrics {\n public abstract String workerName();\n\n public abstract Double avgCpuUtilization();\n\n public static WorkerMetrics create(String workerName, Double avgCpuUtilization) {\n return new AutoValue_ClusterMetrics_WorkerMetrics(workerName, avgCpuUtilization);\n }\n }\n}" } ]
import static com.google.cloud.solutions.trinoscaler.Utils.emptyOrImmutableList; import com.google.auto.value.AutoValue; import com.google.cloud.solutions.trinoscaler.ClusterMetrics; import com.google.cloud.solutions.trinoscaler.proto.Clusters.RepairClusterRequest.NodePoolType; import com.google.cloud.solutions.trinoscaler.proto.TrinoAutoscaler.ClusterScalingSpec; import com.google.cloud.solutions.trinoscaler.proto.TrinoAutoscaler.ScalingAlgorithm; import com.google.cloud.solutions.trinoscaler.proto.TrinoAutoscaler.WorkerScalingLogic; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Optional; import org.checkerframework.checker.nullness.qual.Nullable;
955
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.solutions.trinoscaler.scaler; /** * A ClusterScaleLogic provides methods to compute nodes to add or remove. * * <p>An implementation class provides implementation to define the new nodes to add or specific * nodes to remove based on current {@link ClusterMetrics} */ public interface ClusterScaleLogic { /** Returns the {@link ScalingAlgorithm} implemented by the instance of ClusterScaleLogic. */ ScalingAlgorithm scalingAlgorithm(); /** Returns the number of workers the cluster should have based on scaling logic. */ ResizeAction computeNewWorkers(ClusterMetrics clusterMetrics); /** Returns the reduced node count and specific nodes to shutdown. */ ResizeAction computeShrinkWorkers(ClusterMetrics clusterMetrics); /** Factory for ClusterScaleLogic instances. */ interface ClusterScaleLogicFactory { ScalingAlgorithm scalingAlgorithm(); ClusterScaleLogic create(ClusterScalingSpec scalingSpec, WorkerScalingLogic workerScalingLogic); } /** * Model class to encapsulate the nodeGroups that need to be updated as part of the resize * operation. */ @AutoValue abstract class ResizeAction { public abstract ResizeActionType type(); public abstract ImmutableList<NodeGroup> nodeGroups(); public Optional<NodeGroup> getNodeGroupType(NodePoolType type) { return nodeGroups().stream().filter(nodeGroup -> type.equals(nodeGroup.type())).findFirst(); } public ResizeAction withNodeGroups(List<NodeGroup> nodeGroups) { return create(type(), nodeGroups); } public static ResizeAction noAction() { return create(ResizeActionType.NO_ACTION, null); } public static ResizeAction create(ResizeActionType type, @Nullable List<NodeGroup> nodeGroups) {
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.solutions.trinoscaler.scaler; /** * A ClusterScaleLogic provides methods to compute nodes to add or remove. * * <p>An implementation class provides implementation to define the new nodes to add or specific * nodes to remove based on current {@link ClusterMetrics} */ public interface ClusterScaleLogic { /** Returns the {@link ScalingAlgorithm} implemented by the instance of ClusterScaleLogic. */ ScalingAlgorithm scalingAlgorithm(); /** Returns the number of workers the cluster should have based on scaling logic. */ ResizeAction computeNewWorkers(ClusterMetrics clusterMetrics); /** Returns the reduced node count and specific nodes to shutdown. */ ResizeAction computeShrinkWorkers(ClusterMetrics clusterMetrics); /** Factory for ClusterScaleLogic instances. */ interface ClusterScaleLogicFactory { ScalingAlgorithm scalingAlgorithm(); ClusterScaleLogic create(ClusterScalingSpec scalingSpec, WorkerScalingLogic workerScalingLogic); } /** * Model class to encapsulate the nodeGroups that need to be updated as part of the resize * operation. */ @AutoValue abstract class ResizeAction { public abstract ResizeActionType type(); public abstract ImmutableList<NodeGroup> nodeGroups(); public Optional<NodeGroup> getNodeGroupType(NodePoolType type) { return nodeGroups().stream().filter(nodeGroup -> type.equals(nodeGroup.type())).findFirst(); } public ResizeAction withNodeGroups(List<NodeGroup> nodeGroups) { return create(type(), nodeGroups); } public static ResizeAction noAction() { return create(ResizeActionType.NO_ACTION, null); } public static ResizeAction create(ResizeActionType type, @Nullable List<NodeGroup> nodeGroups) {
return new AutoValue_ClusterScaleLogic_ResizeAction(type, emptyOrImmutableList(nodeGroups));
0
2023-11-17 03:39:59+00:00
2k
yoanpetrov02/todo-app
src/main/java/com/tudu/todoapp/rest/controllers/TodoListController.java
[ { "identifier": "TodoList", "path": "src/main/java/com/tudu/todoapp/entities/TodoList.java", "snippet": "@Entity\n@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@Table(name=\"todo_lists\")\npublic class TodoList {\n\n @Id\n @GeneratedValue\n @Column(name = \"list_id\")\n private Long listId;\n @Column(name = \"title\")\n private String title;\n @Column(name = \"description\")\n private String description;\n\n @ManyToOne(cascade = CascadeType.ALL)\n @JoinColumn(name = \"board_id\")\n private Board board;\n\n @OneToMany(mappedBy = \"todoList\", cascade = CascadeType.ALL)\n private List<TodoItem> todoItems;\n}" }, { "identifier": "TodoListServiceImpl", "path": "src/main/java/com/tudu/todoapp/services/implementations/TodoListServiceImpl.java", "snippet": "@RequiredArgsConstructor\n@Service\npublic class TodoListServiceImpl implements TodoListService {\n\n private final TodoListRepository todoListRepository;\n\n @Override\n public List<TodoList> getAllTodoLists() {\n return todoListRepository.findAll();\n }\n\n @Override\n public List<TodoList> getTodoListsPage(int pageNumber, int perPage) {\n int pageIndex = pageNumber - 1;\n Pageable page = PageRequest.of(pageIndex, perPage);\n return todoListRepository.findAll(page).toList();\n }\n\n @Override\n public TodoList getTodoListById(Long todoListId) {\n return todoListRepository.findById(todoListId)\n .orElseThrow(() -> new ResourceNotFoundException(\"The todo list with the specified id was not found.\"));\n }\n\n @Override\n public List<TodoList> filterTodoListsByTitle(String title) {\n return todoListRepository.filterTodoListsByTitle(title);\n }\n\n @Override\n public TodoList createTodoList(TodoList todoList) {\n if (todoList.getListId() != null && todoListRepository.existsById(todoList.getListId())) {\n throw new ResourceConflictException(\"A todo list with the same id already exists.\");\n }\n return todoListRepository.save(todoList);\n }\n\n\n @Override\n public TodoList updateTodoList(Long listId, TodoList newData) {\n try {\n TodoList dbTodoList = todoListRepository.findById(listId)\n .orElseThrow(() -> new ResourceNotFoundException(\"The todo list with the specified id was not found.\"));\n\n dbTodoList.setTitle(newData.getTitle());\n dbTodoList.setDescription(newData.getDescription());\n\n return todoListRepository.save(dbTodoList);\n } catch (DataIntegrityViolationException e) {\n throw new ResourceConflictException(\"A todo list with that title or description already exists.\");\n }\n }\n\n @Override\n public void deleteAllTodoLists() {\n todoListRepository.deleteAll();\n }\n\n @Override\n public void deleteTodoListById(Long listId) {\n if (!todoListRepository.existsById(listId)) {\n throw new ResourceNotFoundException(\"The todo list with the specified id was not found.\");\n }\n todoListRepository.deleteById(listId);\n }\n}" } ]
import com.tudu.todoapp.entities.TodoList; import com.tudu.todoapp.services.implementations.TodoListServiceImpl; import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List;
850
package com.tudu.todoapp.rest.controllers; @RequiredArgsConstructor @RestController @RequestMapping("api/v1/todolists") public class TodoListController { private final TodoListServiceImpl todoListService; @GetMapping
package com.tudu.todoapp.rest.controllers; @RequiredArgsConstructor @RestController @RequestMapping("api/v1/todolists") public class TodoListController { private final TodoListServiceImpl todoListService; @GetMapping
public List<TodoList> getTodoListsPerPage(
0
2023-11-15 09:10:13+00:00
2k
SplitfireUptown/datalinkx
datalinkx-server/src/main/java/com/datalinkx/dataserver/controller/advice/ExceptionControllerAdvice.java
[ { "identifier": "WebResult", "path": "datalinkx-common/src/main/java/com/datalinkx/common/result/WebResult.java", "snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\n@Slf4j\n@Data\npublic class WebResult<T> {\n\tprivate String status;\n\tprivate String errstr;\n\tprivate String traceId;\n\tprivate T result;\n\n\n\tpublic WebResult() {\n\t}\n\n\n\tpublic void setResult(T result) {\n\t\tthis.result = result;\n\t}\n\n\tpublic WebResult<T> setStatus(String status) {\n\t\tthis.status = status;\n\t\tthis.traceId = MDC.get(TRACE_ID);\n\t\treturn this;\n\t}\n\n\tpublic WebResult<T> setErrstr(String errstr) {\n\t\tthis.errstr = errstr;\n\t\treturn this;\n\t}\n\n\tpublic static <T> WebResult<T> of(T result) {\n\t\tif (result instanceof Optional) {\n\t\t\treturn of((Optional<T>) result);\n\t\t}\n\t\tWebResult<T> r = newInstance();\n\t\tr.setResult(result);\n\t\tr.setStatus(\"0\");\n\t\treturn r;\n\t}\n\n\tpublic static <T> WebResult<T> of(Optional<T> result) {\n\t\treturn result.isPresent()\n\t\t\t\t? of(result.get())\n\t\t\t\t: new WebResult<T>().setErrstr(\"object does not exists\").setStatus(\"101\");\n\t}\n\n\tpublic static <T> WebResult<T> fail(Throwable throwable) {\n\t\tlog.error(throwable.getMessage(), throwable);\n\t\tWebResult<T> r = newInstance();\n\t\tr.setStatus(\"500\");\n\t\tr.setErrstr(throwable.getMessage());\n\t\treturn r;\n\t}\n\n\tpublic static <T> WebResult<T> fail(Throwable throwable, T o) {\n\t\tlog.error(throwable.getMessage(), throwable);\n\t\tString msg = Optional.ofNullable(throwable.getCause())\n\t\t\t\t.map(s -> s.getMessage() + \",\")\n\t\t\t\t.orElse(\"\") + throwable.getMessage();\n\t\tWebResult<T> r = newInstance();\n\t\tr.setErrstr(msg);\n\t\tr.setStatus(String.valueOf(StatusCode.API_INTERNAL_ERROR.getValue()));\n\t\tr.setResult(o);\n\t\treturn r;\n\t}\n\n\tpublic static <T> WebResult<T> newInstance() {\n\t\treturn new WebResult<T>();\n\t}\n\n}" }, { "identifier": "DatalinkXServerException", "path": "datalinkx-common/src/main/java/com/datalinkx/common/exception/DatalinkXServerException.java", "snippet": "public class DatalinkXServerException extends RuntimeException {\n\tprivate static final long serialVersionUID = -940285811464169752L;\n\n\tprivate StatusCode status;\n\n\t@JsonProperty(\"err_parameter\")\n\tprivate Map<String, Object> errorParam;\n\n\tpublic DatalinkXServerException(String msg) {\n\t\tsuper(msg);\n\t\tstatus = StatusCode.API_INTERNAL_ERROR;\n\t}\n\n\tpublic DatalinkXServerException(StatusCode status, String msg) {\n\t\tsuper(msg);\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(StatusCode status) {\n\t\tsuper(status.getMsg());\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(Throwable throwable) {\n\t\tsuper(throwable);\n\t\tstatus = StatusCode.API_INTERNAL_ERROR;\n\t}\n\n\tpublic DatalinkXServerException(String msg, Throwable throwable) {\n\t\tsuper(msg, throwable);\n\t\tstatus = StatusCode.API_INTERNAL_ERROR;\n\t}\n\n\tpublic DatalinkXServerException(String msg, Throwable throwable, StatusCode status) {\n\t\tsuper(msg, throwable);\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(Throwable throwable, StatusCode status) {\n\t\tsuper(throwable);\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(StatusCode status, String msg, Map<String, Object> errorParam) {\n\t\tsuper(msg);\n\t\tthis.status = status;\n\t\tthis.errorParam = errorParam;\n\t}\n\n\tpublic StatusCode getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic Map<String, Object> getErrorParam() {\n\t\treturn errorParam;\n\t}\n}" } ]
import java.util.stream.Collectors; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import com.datalinkx.common.result.WebResult; import com.datalinkx.common.exception.DatalinkXServerException; import lombok.extern.slf4j.Slf4j; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus;
1,460
package com.datalinkx.dataserver.controller.advice; @Slf4j @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE) public class ExceptionControllerAdvice { @ResponseBody @ExceptionHandler(value = {IllegalStateException.class, IllegalArgumentException.class}) public WebResult<?> handleException(Exception exception) throws Exception { return WebResult.fail(exception, null); } @ResponseBody @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public WebResult<?> handleException(MethodArgumentNotValidException exception) { return WebResult.fail(exception, ErrorsUtils.compositeValiditionError(exception.getBindingResult())); } @ResponseBody @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public WebResult<?> handleException(MissingServletRequestParameterException exception) throws Exception { return WebResult.fail(exception, exception.getParameterName()); } /** * jpa层的校验 * * @param exception * @return * @throws Exception */ @ExceptionHandler(value = {ConstraintViolationException.class}) public WebResult<?> validationException(ConstraintViolationException exception) throws Exception { return WebResult.fail(exception, exception.getConstraintViolations() .stream() .collect(Collectors.toMap( ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage, (m1, m2) -> m1 + m2)) ); } /** * 统一处理自定义异样,根据状态码返回 */
package com.datalinkx.dataserver.controller.advice; @Slf4j @ControllerAdvice @Order(Ordered.HIGHEST_PRECEDENCE) public class ExceptionControllerAdvice { @ResponseBody @ExceptionHandler(value = {IllegalStateException.class, IllegalArgumentException.class}) public WebResult<?> handleException(Exception exception) throws Exception { return WebResult.fail(exception, null); } @ResponseBody @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public WebResult<?> handleException(MethodArgumentNotValidException exception) { return WebResult.fail(exception, ErrorsUtils.compositeValiditionError(exception.getBindingResult())); } @ResponseBody @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public WebResult<?> handleException(MissingServletRequestParameterException exception) throws Exception { return WebResult.fail(exception, exception.getParameterName()); } /** * jpa层的校验 * * @param exception * @return * @throws Exception */ @ExceptionHandler(value = {ConstraintViolationException.class}) public WebResult<?> validationException(ConstraintViolationException exception) throws Exception { return WebResult.fail(exception, exception.getConstraintViolations() .stream() .collect(Collectors.toMap( ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage, (m1, m2) -> m1 + m2)) ); } /** * 统一处理自定义异样,根据状态码返回 */
@ExceptionHandler({DatalinkXServerException.class})
1
2023-11-16 02:22:52+00:00
2k
bdmarius/jndarray-toolbox
src/main/java/internals/TensorGenerator.java
[ { "identifier": "JNumDataType", "path": "src/main/java/utils/JNumDataType.java", "snippet": "public enum JNumDataType {\n BYTE,\n SHORT,\n INT,\n LONG,\n FLOAT,\n DOUBLE\n}" }, { "identifier": "TypeUtils", "path": "src/main/java/utils/TypeUtils.java", "snippet": "public class TypeUtils {\n\n // First element is the highest type, last element is the lowest type\n private static List<JNumDataType> typePromotions = Arrays.asList(JNumDataType.DOUBLE, JNumDataType.FLOAT, JNumDataType.LONG, JNumDataType.INT, JNumDataType.SHORT, JNumDataType.BYTE);\n\n public static JNumDataType parseDataType(Class dataClass) {\n if (dataClass.equals(Byte.class)) {\n return JNumDataType.BYTE;\n }\n if (dataClass.equals(Short.class)) {\n return JNumDataType.SHORT;\n }\n if (dataClass.equals(Integer.class)) {\n return JNumDataType.INT;\n }\n if (dataClass.equals(Long.class)) {\n return JNumDataType.LONG;\n }\n if (dataClass.equals(Float.class)) {\n return JNumDataType.FLOAT;\n }\n if (dataClass.equals(Double.class)) {\n return JNumDataType.DOUBLE;\n }\n return null;\n }\n\n public static Number getDefaultValue(JNumDataType dataType) {\n switch (dataType) {\n case BYTE:\n return (byte) 0;\n case SHORT:\n return (short) 0;\n case INT:\n return 0;\n case LONG:\n return (long) 0;\n case FLOAT:\n return (float) 0;\n case DOUBLE:\n return (double) 0;\n default:\n return 0;\n }\n }\n\n public static Number getOne(JNumDataType dataType) {\n switch (dataType) {\n case BYTE:\n return (byte) 1;\n case SHORT:\n return (short) 1;\n case INT:\n return 1;\n case LONG:\n return (long) 1;\n case FLOAT:\n return (float) 1;\n case DOUBLE:\n return (double) 1;\n default:\n return 1;\n }\n }\n\n public static Number getNull(JNumDataType dataType) {\n return null;\n }\n\n\n /**\n * Gets the highest data type between 2 options\n */\n public static JNumDataType getHighestDataType(JNumDataType firstDataType, JNumDataType secondDataType) {\n if (typePromotions.indexOf(firstDataType) >= typePromotions.indexOf(secondDataType)) {\n return secondDataType;\n } else {\n return firstDataType;\n }\n }\n}" } ]
import utils.JNumDataType; import utils.TypeUtils;
717
package internals; public class TensorGenerator { /** * Returns a Tensor of a requested type and shape, filled with 0 values cast to the specific type. */ static Tensor zeroes(JNumDataType dataType, int[] shape) {
package internals; public class TensorGenerator { /** * Returns a Tensor of a requested type and shape, filled with 0 values cast to the specific type. */ static Tensor zeroes(JNumDataType dataType, int[] shape) {
return new Tensor(dataType, shape, TypeUtils::getDefaultValue);
1
2023-11-13 19:53:02+00:00
2k
raphael-goetz/betterflowers
src/main/java/com/uroria/betterflowers/listeners/CustomFlowerBrushListener.java
[ { "identifier": "BetterFlowers", "path": "src/main/java/com/uroria/betterflowers/BetterFlowers.java", "snippet": "@Getter\npublic final class BetterFlowers extends JavaPlugin {\n\n private final FlowerManager flowerManager;\n private final LanguageManager languageManager;\n\n public BetterFlowers() {\n this.flowerManager = new FlowerManager();\n this.languageManager = new LanguageManager();\n }\n\n @Override\n public void onEnable() {\n registerCommands();\n registerListener();\n }\n\n private void registerCommands() {\n final var flowerCommand = getCommand(\"flower\");\n if (flowerCommand != null) {\n flowerCommand.setAliases(List.of(\"f\", \"F\"));\n flowerCommand.setExecutor(new Flower(this));\n }\n\n final var flowerBrushCommand = getCommand(\"flowerbrush\");\n if (flowerBrushCommand != null) {\n flowerBrushCommand.setAliases(List.of(\"fb\", \"Fb\", \"fB\", \"FB\"));\n flowerBrushCommand.setExecutor(new FlowerBrush(this));\n }\n\n final var undoFlowerCommand = getCommand(\"undoflower\");\n if (undoFlowerCommand != null) {\n undoFlowerCommand.setAliases(List.of(\"uf\", \"Uf\", \"uF\", \"UF\"));\n undoFlowerCommand.setExecutor(new UndoFlower(this));\n }\n }\n\n private void registerListener() {\n Bukkit.getPluginManager().registerEvents(new CustomFlowerPlaceListener(this), this);\n Bukkit.getPluginManager().registerEvents(new CustomFlowerBrushListener(this), this);\n }\n}" }, { "identifier": "FlowerManager", "path": "src/main/java/com/uroria/betterflowers/managers/FlowerManager.java", "snippet": "@Getter\npublic final class FlowerManager {\n\n private final Map<ItemStack, FlowerGroupData> flowers;\n private final Map<ItemStack, BrushData> brushes;\n private final Map<FlowerGroupData, List<Boolean>> flowerRandomizer;\n private final Map<UUID, List<Operation>> operationHistory;\n\n public FlowerManager() {\n this.flowers = new HashMap<>();\n this.brushes = new HashMap<>();\n this.flowerRandomizer = new HashMap<>();\n this.operationHistory = new HashMap<>();\n }\n}" } ]
import com.uroria.betterflowers.BetterFlowers; import com.uroria.betterflowers.data.FlowerGroupData; import com.uroria.betterflowers.data.Operation; import com.uroria.betterflowers.managers.FlowerManager; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.BlockData; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockPhysicsEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.EquipmentSlot; import org.bukkit.util.Vector; import java.util.*;
714
package com.uroria.betterflowers.listeners; public final class CustomFlowerBrushListener implements Listener { private final FlowerManager flowerManager; private final List<Block> flowerBlocks;
package com.uroria.betterflowers.listeners; public final class CustomFlowerBrushListener implements Listener { private final FlowerManager flowerManager; private final List<Block> flowerBlocks;
public CustomFlowerBrushListener(BetterFlowers betterFlowers) {
0
2023-11-18 16:13:59+00:00
2k
DatCoder464/Malumian-Skies
src/main/java/org/valkyrienskies/malumian_skies/registry/block/MSBlockRegistry.java
[ { "identifier": "CombustionSilo", "path": "src/main/java/org/valkyrienskies/malumian_skies/common/block/CombustionSilo.java", "snippet": "public class CombustionSilo extends Block implements EntityBlock {\n public CombustionSilo(Properties pProperties) {\n super(pProperties);\n }\n\n @Nullable\n @Override\n public BlockEntity newBlockEntity(BlockPos Pos, BlockState State) {\n return BlockEntityRegistry.COMBUSTION_SILO.get().create(Pos,State);\n }\n}" }, { "identifier": "CombustionTank", "path": "src/main/java/org/valkyrienskies/malumian_skies/common/block/CombustionTank.java", "snippet": "public class CombustionTank extends Block implements EntityBlock {\n public CombustionTank(Properties pProperties) {\n super(pProperties);\n }\n\n @Nullable\n @Override\n public BlockEntity newBlockEntity(BlockPos pos, BlockState state) {\n return BlockEntityRegistry.COMBUSTION_TANK.get().create(pos, state);\n }\n}" }, { "identifier": "CombustionThruster", "path": "src/main/java/org/valkyrienskies/malumian_skies/common/block/CombustionThruster.java", "snippet": "public class CombustionThruster extends Block implements EntityBlock {\n public CombustionThruster(Properties pProperties) {\n super(pProperties);\n }\n\n @Nullable\n @Override\n public BlockEntity newBlockEntity(BlockPos pPos, BlockState pState) {\n return null;\n }\n}" }, { "identifier": "MSTabRegistry", "path": "src/main/java/org/valkyrienskies/malumian_skies/registry/tab/MSTabRegistry.java", "snippet": "public class MSTabRegistry {\n public static final MSTab CONTENT = new MSTab(\"basis_of_magic\", MSItemRegistry.HALLOWED_LEAD_INGOT);\n\n public static void register(IEventBus modEventBus) {\n }\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/org/valkyrienskies/malumian_skies/MalumianSkies.java", "snippet": "public static final String MOD_ID = \"malumian_skies\";" }, { "identifier": "HALLOWED_LEAD", "path": "src/main/java/org/valkyrienskies/malumian_skies/registry/block/MSBlockProperties.java", "snippet": "public static LodestoneBlockProperties HALLOWED_LEAD() {\n return new LodestoneBlockProperties(Material.HEAVY_METAL, MaterialColor.COLOR_PURPLE)\n .addTag(BlockTagRegistry.RITE_IMMUNE)\n .sound(SoundType.METAL);\n}" } ]
import net.minecraft.world.item.Item; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.state.BlockBehaviour; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import org.lwjgl.system.CallbackI; import org.valkyrienskies.malumian_skies.common.block.CombustionSilo; import org.valkyrienskies.malumian_skies.common.block.CombustionTank; import org.valkyrienskies.malumian_skies.common.block.CombustionThruster; import org.valkyrienskies.malumian_skies.registry.tab.MSTabRegistry; import static org.valkyrienskies.malumian_skies.MalumianSkies.MOD_ID; import static org.valkyrienskies.malumian_skies.registry.block.MSBlockProperties.HALLOWED_LEAD;
860
package org.valkyrienskies.malumian_skies.registry.block; public class MSBlockRegistry extends Blocks { public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
package org.valkyrienskies.malumian_skies.registry.block; public class MSBlockRegistry extends Blocks { public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MOD_ID);
public static final RegistryObject<CombustionThruster> COMBUSTION_THRUSTER = BLOCKS.register("combustion_thruster", () -> new CombustionThruster(HALLOWED_LEAD()));
2
2023-11-14 20:50:34+00:00
2k
12manel123/tsys-my-food-api-1011
src/main/java/com/myfood/controllers/SlotController.java
[ { "identifier": "Slot", "path": "src/main/java/com/myfood/dto/Slot.java", "snippet": "@Entity\n@Table(name = \"slots\")\npublic class Slot {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"time\", nullable = false)\n private String time;\n\n @Column(name = \"limit_slot\", nullable = false)\n private int limitSlot;\n\n @Column(name = \"actual\", nullable = false)\n private int actual;\n \n @OneToMany(mappedBy = \"slot\")\n @JsonIgnore\n private List<Order> orders;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public int getLimitSlot() {\n return limitSlot;\n }\n\n public void setLimitSlot(int limitSlot) {\n this.limitSlot = limitSlot;\n }\n\n public int getActual() {\n return actual;\n }\n\n public void setActual(int actual) {\n this.actual = actual;\n }\n \n public List<Order> getOrders() {\n return orders;\n }\n\n public void setOrders(List<Order> orders) {\n this.orders = orders;\n }\n\n @Override\n public String toString() {\n return \"Slot{\" +\n \"id=\" + id +\n \", time='\" + time + '\\'' +\n \", limitSlot=\" + limitSlot +\n \", actual=\" + actual +\n '}';\n }\n}" }, { "identifier": "SlotUserDTO", "path": "src/main/java/com/myfood/dto/SlotUserDTO.java", "snippet": "public class SlotUserDTO {\n\t\n\tprivate Long id;\n private String time;\n \n\tpublic SlotUserDTO(Long id, String time) {\n\t\tthis.id = id;\n\t\tthis.time = time;\n\t}\n\t\n\tpublic SlotUserDTO() {\n\t}\n\t\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\t\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\t\n\tpublic String getTime() {\n\t\treturn time;\n\t}\n\t\n\tpublic void setTime(String time) {\n\t\tthis.time = time;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\treturn \"SlotIUserDTO [id=\" + id + \", time=\" + time + \"]\";\n\t}\n\t \n}" }, { "identifier": "SlotServiceImpl", "path": "src/main/java/com/myfood/services/SlotServiceImpl.java", "snippet": "@Service\npublic class SlotServiceImpl implements ISlotService {\n\n @Autowired\n private ISlotDAO slotDAO;\n\n @Override\n public List<Slot> getAllSlots() {\n return slotDAO.findAll();\n }\n\n @Override\n public Optional<Slot> getOneSlot(Long id) {\n return slotDAO.findById(id);\n }\n\n @Override\n public Slot createSlot(Slot entity) {\n return slotDAO.save(entity);\n }\n\n @Override\n public Slot updateSlot(Slot entity) {\n return slotDAO.save(entity);\n }\n\n @Override\n public void deleteSlot(Long id) {\n slotDAO.deleteById(id);\n }\n}" } ]
import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import com.myfood.dto.Slot; import com.myfood.dto.SlotUserDTO; import com.myfood.services.SlotServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement;
1,091
package com.myfood.controllers; @RestController @RequestMapping("api/v1") public class SlotController { @Autowired private SlotServiceImpl slotService; /** * Retrieves a list of all available time slots. It's for ADMIN. * * @return ResponseEntity containing a list of {@link Slot} objects. * @see SlotService#getAllSlots() * @see Slot */ @Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @PreAuthorize("hasRole('ADMIN')") @GetMapping("/slots")
package com.myfood.controllers; @RestController @RequestMapping("api/v1") public class SlotController { @Autowired private SlotServiceImpl slotService; /** * Retrieves a list of all available time slots. It's for ADMIN. * * @return ResponseEntity containing a list of {@link Slot} objects. * @see SlotService#getAllSlots() * @see Slot */ @Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @PreAuthorize("hasRole('ADMIN')") @GetMapping("/slots")
public ResponseEntity<List<Slot>> getAllSlots() {
0
2023-11-10 16:09:43+00:00
2k
huzpsb/LC4J
src/org/eu/huzpsb/unichat/llm/impl/ChatGPT.java
[ { "identifier": "Conversation", "path": "src/org/eu/huzpsb/unichat/conversation/Conversation.java", "snippet": "public class Conversation {\n public List<Entry> entries = new ArrayList<>();\n\n @SuppressWarnings(\"ALL\")\n @Override\n public Conversation clone() {\n // 1, We don't need to clone entries, because they are immutable.\n // 2, We don't need to call super.clone(), because it's an empty method.\n Conversation conversation = new Conversation();\n conversation.entries.addAll(entries);\n return conversation;\n }\n}" }, { "identifier": "Entry", "path": "src/org/eu/huzpsb/unichat/conversation/Entry.java", "snippet": "public class Entry {\n public final EntryOwner owner;\n public final String content;\n\n public Entry(EntryOwner owner, String content) {\n this.owner = owner;\n this.content = content;\n }\n}" }, { "identifier": "EntryOwner", "path": "src/org/eu/huzpsb/unichat/conversation/EntryOwner.java", "snippet": "public enum EntryOwner {\n USER,\n BOT,\n SYSTEM\n}" }, { "identifier": "CredentialType", "path": "src/org/eu/huzpsb/unichat/credential/CredentialType.java", "snippet": "public enum CredentialType {\n COOKIE,\n TOKEN,\n USERNAME_PASSWORD,\n AK_SK,\n NONE\n}" }, { "identifier": "CredentialManager", "path": "src/org/eu/huzpsb/unichat/credential/manager/CredentialManager.java", "snippet": "public interface CredentialManager {\n public Credential getCredential();\n}" }, { "identifier": "LLM", "path": "src/org/eu/huzpsb/unichat/llm/LLM.java", "snippet": "public interface LLM {\n Entry Chat(Conversation c);\n}" }, { "identifier": "JsonUtils", "path": "src/org/eu/huzpsb/unichat/utils/JsonUtils.java", "snippet": "public class JsonUtils {\n public static String escape(String s) {\n return s\n .replace(\"\\\\\", \"\\\\\\\\\")\n .replace(\"\\\"\", \"\\\\\\\"\")\n .replace(\"\\n\", \"\\\\n\")\n .replace(\"\\r\", \"\\\\r\")\n .replace(\"\\t\", \"\\\\t\")\n .replace(\"\\b\", \"\\\\b\");\n }\n}" } ]
import nano.http.d2.json.NanoJSON; import nano.http.d2.utils.Request; import org.eu.huzpsb.unichat.conversation.Conversation; import org.eu.huzpsb.unichat.conversation.Entry; import org.eu.huzpsb.unichat.conversation.EntryOwner; import org.eu.huzpsb.unichat.credential.CredentialType; import org.eu.huzpsb.unichat.credential.manager.CredentialManager; import org.eu.huzpsb.unichat.llm.LLM; import org.eu.huzpsb.unichat.utils.JsonUtils; import java.util.Properties;
819
package org.eu.huzpsb.unichat.llm.impl; public class ChatGPT implements LLM { public static final String endpoint = "https://api.openai.com/v1/chat/completions"; public final CredentialManager credentialManager; public ChatGPT(CredentialManager credentialManager) { this.credentialManager = credentialManager; } @Override public Entry Chat(Conversation c) { StringBuilder sb = new StringBuilder("{\"model\":\"gpt-3.5-turbo\",\"messages\":["); for (Entry e : c.entries) { String owner = null; switch (e.owner) { case USER: owner = "user"; break; case BOT: owner = "assistant"; break; case SYSTEM: owner = "system"; break; } sb.append("{\"role\":\""); sb.append(owner); sb.append("\",\"content\":\"");
package org.eu.huzpsb.unichat.llm.impl; public class ChatGPT implements LLM { public static final String endpoint = "https://api.openai.com/v1/chat/completions"; public final CredentialManager credentialManager; public ChatGPT(CredentialManager credentialManager) { this.credentialManager = credentialManager; } @Override public Entry Chat(Conversation c) { StringBuilder sb = new StringBuilder("{\"model\":\"gpt-3.5-turbo\",\"messages\":["); for (Entry e : c.entries) { String owner = null; switch (e.owner) { case USER: owner = "user"; break; case BOT: owner = "assistant"; break; case SYSTEM: owner = "system"; break; } sb.append("{\"role\":\""); sb.append(owner); sb.append("\",\"content\":\"");
sb.append(JsonUtils.escape(e.content));
6
2023-11-16 11:44:05+00:00
2k
jpdev01/asaasSdk
src/main/java/io/github/jpdev/asaassdk/rest/financialtransaction/FinancialTransactionReader.java
[ { "identifier": "Domain", "path": "src/main/java/io/github/jpdev/asaassdk/http/Domain.java", "snippet": "public enum Domain {\n\n TRANSFER(\"transfers\"),\n PAYMENT(\"payments\"),\n REFUND_PAYMENT(\"payments/$id/refund\"),\n PIX_TRANSACTION(\"pix/transactions\"),\n PIX_TRANSACTION_CANCELLATION(\"pix/transactions/$id/cancel\"),\n PIX_ADDRESS_KEY(\"pix/addressKeys\"),\n STATIC_PIX_QR_CODE(\"pix/qrCodes/static\"),\n DECODE_PIX_QR_CODE(\"pix/qrCodes/decode\"),\n CUSTOMER_ACCOUNT(\"customers\"),\n NOTIFICATION(\"notifications\"),\n CUSTOMER_ACCOUNT_NOTIFICATIONS(\"customers/$id/notifications\"),\n PAYMENT_STATUS(\"payments/$id/status\"),\n PAYMENT_RESTORE(\"payments/$id/restore\"),\n INSTALLMENT(\"installments\"),\n FINANCE_BALANCE(\"finance/balance\"),\n PAYMENT_LINK(\"paymentLinks\"),\n BILL(\"bill\"),\n FINANCIAL_TRANSACTION(\"financialTransactions\"),\n INVOICE(\"invoices\"),\n COMMERCIAL_INFO(\"myAccount/commercialInfo\"),\n ACCOUNT_NUMBER(\"myAccount/accountNumber\"),\n FEE(\"myAccount/fees\"),\n STATUS(\"myAccount/status\"),\n ACCOUNT(\"accounts\");\n\n private final String value;\n\n private Domain(final String value) {\n this.value = value;\n }\n\n public String addPathVariable(String value) {\n return this.toString() + \"/\" + value;\n }\n\n public String addVariableList(String... variables) {\n StringBuilder path = new StringBuilder(this.toString());\n for (String variable : variables) {\n path.append(\"/\").append(variable);\n }\n return path.toString();\n }\n\n public String toString() {\n return value;\n }\n}" }, { "identifier": "Reader", "path": "src/main/java/io/github/jpdev/asaassdk/rest/action/Reader.java", "snippet": "public abstract class Reader<T> {\n\n public Integer limit;\n public Long offset;\n\n public List<FilterVO> activeFilters;\n\n public Integer getLimit() {\n return limit;\n }\n\n public Reader<T> setLimit(Integer limit) {\n this.limit = limit;\n return this;\n }\n\n public Long getOffset() {\n return offset;\n }\n\n public Reader<T> setOffset(Long offset) {\n this.offset = offset;\n return this;\n }\n\n public ResourceSet<T> read() {\n return read(Asaas.getRestClient());\n }\n\n public ResourceSet<T> read(final AsaasRestClient client) {\n Response response = client.get(buildFullPath());\n return ResourceSet.fromJson(\n \"data\",\n response.getContent(),\n getResourceClass(),\n client.getObjectMapper()\n );\n }\n\n public abstract String getResourceUrl();\n public abstract Class<T> getResourceClass();\n\n public void addFilter(String propertyName) {\n if (activeFilters == null) activeFilters = new ArrayList<>();\n activeFilters.add(new FilterVO(\n propertyName\n ));\n }\n\n public void addFilter(String propertyName, String filterName) {\n if (activeFilters == null) activeFilters = new ArrayList<>();\n activeFilters.add(new FilterVO(\n propertyName,\n filterName\n ));\n }\n\n private String buildFullPath() {\n try {\n String path = getResourceUrl();\n if (activeFilters == null || activeFilters.isEmpty()) return path;\n\n String pathParams = \"\";\n for (FilterVO filterVO : activeFilters) {\n pathParams = concatDelimiterFilter(pathParams);\n Field field = this.getClass().getDeclaredField(filterVO.getPropertyName());\n pathParams = pathParams\n .concat(URLEncoder.encode(filterVO.getFilterKey()))\n .concat(\"=\");\n\n Object value = field.get(this);\n if (value instanceof String || value instanceof Enum) {\n pathParams = pathParams\n .concat(value.toString());\n } else if (value instanceof Integer) {\n pathParams = pathParams\n .concat(value.toString());\n } else if (value instanceof Date) {\n pathParams = pathParams\n .concat(CustomDateUtils.toString((Date) value, CustomDateUtils.DATE));\n } else {\n throw new IllegalStateException(\"Filtro não mapeado\");\n }\n }\n\n if (limit != null) {\n pathParams = concatDelimiterFilter(pathParams)\n .concat(\"limit=\")\n .concat(limit.toString());\n }\n\n if (offset != null) {\n pathParams = concatDelimiterFilter(pathParams)\n .concat(\"offset=\")\n .concat(offset.toString());\n }\n\n return path.concat(pathParams);\n } catch (NoSuchFieldException | SecurityException | IllegalArgumentException |\n IllegalAccessException unexpectedException) {\n throw new IllegalStateException(\"Erro ao parsear filtros.\");\n }\n }\n\n private String concatDelimiterFilter(String currentFilter) {\n if (currentFilter.isEmpty()) return currentFilter.concat(\"?\");\n return currentFilter.concat(\"&\");\n }\n}" } ]
import io.github.jpdev.asaassdk.http.Domain; import io.github.jpdev.asaassdk.rest.action.Reader;
1,574
package io.github.jpdev.asaassdk.rest.financialtransaction; public class FinancialTransactionReader extends Reader<FinancialTransaction> { public String paymentId; public String transferId; public String anticipationId; public String billId; public String invoiceId; public String paymentDunningId; public String creditBureauReportId; public FinancialTransactionReader setPaymentId(String paymentId) { addFilter("paymentId"); this.paymentId = paymentId; return this; } public FinancialTransactionReader setTransferId(String transferId) { addFilter("transferId"); this.transferId = transferId; return this; } public FinancialTransactionReader setAnticipationId(String anticipationId) { addFilter("anticipationId"); this.anticipationId = anticipationId; return this; } public FinancialTransactionReader setBillId(String billId) { addFilter("billId"); this.billId = billId; return this; } public FinancialTransactionReader setInvoiceId(String invoiceId) { addFilter("invoiceId"); this.invoiceId = invoiceId; return this; } public FinancialTransactionReader setPaymentDunningId(String paymentDunningId) { addFilter("paymentDunningId"); this.paymentDunningId = paymentDunningId; return this; } public FinancialTransactionReader setCreditBureauReportId(String creditBureauReportId) { addFilter("creditBureauReportId"); this.creditBureauReportId = creditBureauReportId; return this; } @Override public String getResourceUrl() {
package io.github.jpdev.asaassdk.rest.financialtransaction; public class FinancialTransactionReader extends Reader<FinancialTransaction> { public String paymentId; public String transferId; public String anticipationId; public String billId; public String invoiceId; public String paymentDunningId; public String creditBureauReportId; public FinancialTransactionReader setPaymentId(String paymentId) { addFilter("paymentId"); this.paymentId = paymentId; return this; } public FinancialTransactionReader setTransferId(String transferId) { addFilter("transferId"); this.transferId = transferId; return this; } public FinancialTransactionReader setAnticipationId(String anticipationId) { addFilter("anticipationId"); this.anticipationId = anticipationId; return this; } public FinancialTransactionReader setBillId(String billId) { addFilter("billId"); this.billId = billId; return this; } public FinancialTransactionReader setInvoiceId(String invoiceId) { addFilter("invoiceId"); this.invoiceId = invoiceId; return this; } public FinancialTransactionReader setPaymentDunningId(String paymentDunningId) { addFilter("paymentDunningId"); this.paymentDunningId = paymentDunningId; return this; } public FinancialTransactionReader setCreditBureauReportId(String creditBureauReportId) { addFilter("creditBureauReportId"); this.creditBureauReportId = creditBureauReportId; return this; } @Override public String getResourceUrl() {
return Domain.FINANCIAL_TRANSACTION.toString();
0
2023-11-12 01:19:17+00:00
2k
GoldenStack/minestom-ca
src/test/java/dev/goldenstack/minestom_ca/test/parser/RuleParsingTest.java
[ { "identifier": "Neighbors", "path": "src/main/java/dev/goldenstack/minestom_ca/Neighbors.java", "snippet": "public final class Neighbors {\n public static final @NotNull Point SELF = Vec.ZERO;\n\n public static final @NotNull Point UP = new Vec(0, 1, 0);\n\n public static final @NotNull Point DOWN = new Vec(0, -1, 0);\n\n public static final @NotNull Point NORTH = new Vec(0, 0, -1);\n public static final @NotNull Point EAST = new Vec(1, 0, 0);\n public static final @NotNull Point SOUTH = new Vec(0, 0, 1);\n public static final @NotNull Point WEST = new Vec(-1, 0, 0);\n\n public static final @NotNull Point NORTHEAST = NORTH.add(EAST);\n public static final @NotNull Point SOUTHEAST = SOUTH.add(EAST);\n public static final @NotNull Point NORTHWEST = NORTH.add(WEST);\n public static final @NotNull Point SOUTHWEST = SOUTH.add(WEST);\n\n public static final @NotNull List<Point> MOORE_2D_SELF = List.of(SELF, NORTH, EAST, SOUTH, WEST, NORTHEAST, SOUTHEAST, NORTHWEST, SOUTHWEST);\n public static final @NotNull List<Point> MOORE_2D = List.of(NORTH, EAST, SOUTH, WEST, NORTHEAST, SOUTHEAST, NORTHWEST, SOUTHWEST);\n\n public static final @NotNull List<Point> MOORE_3D_SELF;\n public static final @NotNull List<Point> MOORE_3D;\n\n public static final @NotNull List<Point> NEUMANN_2D_SELF = List.of(SELF, NORTH, SOUTH, EAST, WEST);\n public static final @NotNull List<Point> NEUMANN_2D = List.of(NORTH, SOUTH, EAST, WEST);\n\n public static final @NotNull List<Point> NEUMANN_3D_SELF = List.of(SELF, NORTH, SOUTH, EAST, WEST, UP, DOWN);\n public static final @NotNull List<Point> NEUMANN_3D = List.of(NORTH, SOUTH, EAST, WEST, UP, DOWN);\n\n static {\n List<Point> points3d = new ArrayList<>();\n for (int x : new int[]{-1, 0, 1}) {\n for (int y : new int[]{-1, 0, 1}) {\n for (int z : new int[]{-1, 0, 1}) {\n points3d.add(new Vec(x, y, z));\n }\n }\n }\n\n MOORE_3D_SELF = List.copyOf(points3d);\n\n points3d.removeIf(Vec.ZERO::equals);\n MOORE_3D = List.copyOf(points3d);\n }\n\n public static final @NotNull Map<String, List<Point>> NAMED = Map.ofEntries(\n Map.entry(\"up\", List.of(UP)),\n Map.entry(\"down\", List.of(DOWN)),\n Map.entry(\"north\", List.of(NORTH)),\n Map.entry(\"east\", List.of(EAST)),\n Map.entry(\"south\", List.of(SOUTH)),\n Map.entry(\"west\", List.of(WEST)),\n Map.entry(\"northeast\", List.of(NORTHEAST)),\n Map.entry(\"southeast\", List.of(SOUTHEAST)),\n Map.entry(\"northwest\", List.of(NORTHWEST)),\n Map.entry(\"southwest\", List.of(SOUTHWEST)),\n Map.entry(\"moore2dself\", MOORE_2D_SELF),\n Map.entry(\"moore2d\", MOORE_2D),\n Map.entry(\"moore3dself\", MOORE_3D_SELF),\n Map.entry(\"moore3d\", MOORE_3D),\n Map.entry(\"neumann2dself\", NEUMANN_2D_SELF),\n Map.entry(\"neumann2d\", NEUMANN_2D),\n Map.entry(\"neumann3dself\", NEUMANN_3D_SELF),\n Map.entry(\"neumann3d\", NEUMANN_3D)\n );\n}" }, { "identifier": "assertRule", "path": "src/test/java/dev/goldenstack/minestom_ca/test/parser/TestUtils.java", "snippet": "public static void assertRule(@NotNull String rulesString, @NotNull Rule @NotNull ... expected) {\n assertEquals(List.of(expected), parseRules(rulesString));\n}" } ]
import dev.goldenstack.minestom_ca.Rule; import dev.goldenstack.minestom_ca.Rule.Expression; import dev.goldenstack.minestom_ca.Rule.Result.SetIndex; import net.minestom.server.instance.block.Block; import org.junit.jupiter.api.Test; import static dev.goldenstack.minestom_ca.Neighbors.*; import static dev.goldenstack.minestom_ca.Rule.Condition.*; import static dev.goldenstack.minestom_ca.test.parser.TestUtils.assertRule;
1,163
package dev.goldenstack.minestom_ca.test.parser; @SuppressWarnings("DuplicateExpressions") public final class RuleParsingTest { @Test public void testRules() {
package dev.goldenstack.minestom_ca.test.parser; @SuppressWarnings("DuplicateExpressions") public final class RuleParsingTest { @Test public void testRules() {
assertRule("#dirt -> #grass_block",
1
2023-11-18 21:49:11+00:00
2k
spring-projects/spring-rewrite-commons
spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/boot/autoconfigure/ScopeConfiguration.java
[ { "identifier": "ExecutionScope", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/scopes/ExecutionScope.java", "snippet": "public class ExecutionScope extends AbstractBaseScope {\n\n\tpublic final static String SCOPE_NAME = \"executionScope\";\n\n}" }, { "identifier": "ProjectMetadata", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/scopes/ProjectMetadata.java", "snippet": "public class ProjectMetadata {\n\n\tprivate String metadata;\n\n\tprivate MavenSettings mavenSettings;\n\n\tpublic String getMetadata() {\n\t\treturn metadata;\n\t}\n\n\tpublic void setMetadata(String metadata) {\n\t\tthis.metadata = metadata;\n\t}\n\n\tpublic MavenSettings getMavenSettings() {\n\t\treturn mavenSettings;\n\t}\n\n\tpublic void setMavenSettings(MavenSettings mavenSettings) {\n\t\tthis.mavenSettings = mavenSettings;\n\t}\n\n}" }, { "identifier": "ScanScope", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/scopes/ScanScope.java", "snippet": "public class ScanScope extends AbstractBaseScope {\n\n\tpublic final static String SCOPE_NAME = \"scanScope\";\n\n}" } ]
import org.openrewrite.ExecutionContext; import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.maven.cache.MavenPomCache; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.rewrite.scopes.ExecutionScope; import org.springframework.rewrite.scopes.ProjectMetadata; import org.springframework.rewrite.scopes.ScanScope; import java.util.function.Supplier;
697
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.boot.autoconfigure; /** * @author Fabian Krüger */ @AutoConfiguration public class ScopeConfiguration { @Bean ExecutionScope executionScope() { return new ExecutionScope(); } @Bean ScanScope scanScope() { return new ScanScope(); } /** * Register {@link ScanScope} and {@link ExecutionScope}. */ @Bean public static BeanFactoryPostProcessor beanFactoryPostProcessor(ExecutionScope executionScope, ScanScope scanScope) { return beanFactory -> { beanFactory.registerScope(ScanScope.SCOPE_NAME, scanScope); beanFactory.registerScope(ExecutionScope.SCOPE_NAME, executionScope); }; } @Bean @org.springframework.rewrite.scopes.annotations.ScanScope
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.boot.autoconfigure; /** * @author Fabian Krüger */ @AutoConfiguration public class ScopeConfiguration { @Bean ExecutionScope executionScope() { return new ExecutionScope(); } @Bean ScanScope scanScope() { return new ScanScope(); } /** * Register {@link ScanScope} and {@link ExecutionScope}. */ @Bean public static BeanFactoryPostProcessor beanFactoryPostProcessor(ExecutionScope executionScope, ScanScope scanScope) { return beanFactory -> { beanFactory.registerScope(ScanScope.SCOPE_NAME, scanScope); beanFactory.registerScope(ExecutionScope.SCOPE_NAME, executionScope); }; } @Bean @org.springframework.rewrite.scopes.annotations.ScanScope
ProjectMetadata projectMetadata() {
1
2023-11-14 23:02:37+00:00
2k
giftorg/gift
gift-backed/src/main/java/org/giftorg/backed/controller/ProjectController.java
[ { "identifier": "Response", "path": "gift-backed/src/main/java/org/giftorg/backed/entity/Response.java", "snippet": "@Data\npublic class Response {\n private Integer code;\n private String msg;\n private Object data;\n\n public Response() {\n }\n\n public Response(Object data) {\n this.code = 0;\n this.msg = \"success\";\n this.data = data;\n }\n\n public Response(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n public Response(Integer code, String msg, Object data) {\n this.code = code;\n this.msg = msg;\n this.data = data;\n }\n}" }, { "identifier": "Project", "path": "gift-backed/src/main/java/org/giftorg/backed/entity/repository/Project.java", "snippet": "@Data\n@TableName(value = \"projects\")\npublic class Project {\n private Integer id;\n\n private Integer repoId;\n\n private String name;\n\n private String fullName;\n\n private Integer stars;\n\n private String author;\n\n private String url;\n\n private String description;\n\n private Integer size;\n\n private String defaultBranch;\n\n private String readme;\n\n private String readmeCn;\n\n private List<String> tags;\n}" }, { "identifier": "Repository", "path": "gift-backed/src/main/java/org/giftorg/backed/entity/repository/Repository.java", "snippet": "@Data\npublic class Repository {\n private Integer id;\n\n private Integer repoId;\n\n private String name;\n\n private String fullName;\n\n private Integer stars;\n\n private String author;\n\n private String url;\n\n private String description;\n\n private Integer size;\n\n private String defaultBranch;\n\n private String readme;\n\n private String readmeCn;\n\n private List<String> tags;\n\n private String hdfsPath;\n\n private boolean isTranslated = false;\n\n private boolean isTagged = false;\n}" }, { "identifier": "FunctionVo", "path": "gift-backed/src/main/java/org/giftorg/backed/entity/vo/FunctionVo.java", "snippet": "@Data\npublic class FunctionVo {\n private String name; //项目名\n\n private String source; //源代码\n\n private String description; //描述\n\n private Position begin; //表示代码中的位置信息,例如行号和列号\n\n private Position end; //表示代码中的位置信息\n\n private String language; //语言\n\n private Integer repoId; //仓库ID\n\n private String filePath; //URL\n\n private String technologyStack; //所用的技术\n\n private Project project;\n}" }, { "identifier": "ChatService", "path": "gift-backed/src/main/java/org/giftorg/backed/service/ChatService.java", "snippet": "public interface ChatService {\n\n /**\n * GPT接口\n */\n String chat(String question) throws Exception;\n}" }, { "identifier": "CodeService", "path": "gift-backed/src/main/java/org/giftorg/backed/service/CodeService.java", "snippet": "public interface CodeService {\n\n /**\n * 根据代码搜索词来向ES查询\n */\n List<FunctionVo> searchCode(String query);\n}" }, { "identifier": "RepositoryService", "path": "gift-backed/src/main/java/org/giftorg/backed/service/RepositoryService.java", "snippet": "public interface RepositoryService extends IService<Project> {\n\n List<Repository> searchRepository(String text) throws Exception;\n}" } ]
import java.util.List; import lombok.extern.slf4j.Slf4j; import org.giftorg.backed.entity.Response; import org.giftorg.backed.entity.repository.Project; import org.giftorg.backed.entity.repository.Repository; import org.giftorg.backed.entity.vo.FunctionVo; import org.giftorg.backed.service.ChatService; import org.giftorg.backed.service.CodeService; import org.giftorg.backed.service.RepositoryService; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource;
1,154
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.backed.controller; @RestController @RequestMapping("/api") @Slf4j public class ProjectController { @Resource
/** * Copyright 2023 GiftOrg Authors * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.giftorg.backed.controller; @RestController @RequestMapping("/api") @Slf4j public class ProjectController { @Resource
private CodeService codeService;
5
2023-11-15 08:58:35+00:00
2k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/comparison/DiffBlockXPathTest.java
[ { "identifier": "ContentType", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/ContentType.java", "snippet": "@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\n@Getter\npublic enum ContentType {\n\n UNDEFINED {\n @Override\n public boolean matchesMime(String value) {\n return false;\n }\n\n @Override\n boolean matchesExtension(String value) {\n return false;\n }\n },\n\n XML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"xml\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsIgnoreCase(value, \"xml\");\n }\n },\n\n HTML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"html\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"htl\",\n \"html\",\n \"htm\");\n }\n },\n\n TEXT {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"text\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"css\",\n \"csv\",\n \"ecma\",\n \"info\",\n \"java\",\n \"jsp\",\n \"jspx\",\n \"js\",\n \"json\",\n \"log\",\n \"md\",\n \"mf\",\n \"php\",\n \"properties\",\n \"ts\",\n \"txt\");\n }\n };\n\n /**\n * Checks if the given MIME-type is matched by the current content type\n * @param value MIME-type to check\n * @return True or false\n */\n abstract boolean matchesMime(String value);\n\n /**\n * Checks if the given file extension is matched by the current content type\n * @param value File extension to check\n * @return True or false\n */\n abstract boolean matchesExtension(String value);\n\n /**\n * Gets the content type that matches the given MIME type\n * @param value MIME-type\n * @return {@code ContentType} enum value\n */\n public static ContentType fromMimeType(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n String effectiveType = StringUtils.substringBefore(value, \";\");\n for (ContentType contentType : values()) {\n if (contentType.matchesMime(effectiveType)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n\n /**\n * Gets the content type that matches the given file extension\n * @param value File extension\n * @return {@code ContentType} enum value\n */\n public static ContentType fromExtension(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n for (ContentType contentType : values()) {\n if (contentType.matchesExtension(value)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n}" }, { "identifier": "Diff", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Diff.java", "snippet": "public interface Diff extends PrintableEntry, EntryHolder {\n\n /**\n * Gets the \"kind\" of difference. E.g., \"change\", \"insertion\", \"deletion\", etc.\n * @return {@link DiffState} instance\n */\n DiffState getState();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}\n * @return Integer value\n */\n int getCount();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}.\n * Counts only the differences that have not been \"silenced\" (accepted) with a {@link Filter}\n * @return Integer value\n */\n int getPendingCount();\n\n /**\n * Gets the left part of the comparison\n * @return String value\n */\n String getLeft();\n\n /**\n * Gets the right part of the comparison\n * @return String value\n */\n String getRight();\n}" } ]
import com.exadel.etoolbox.anydiff.ContentType; import com.exadel.etoolbox.anydiff.diff.Diff; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets;
1,420
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff.comparison; public class DiffBlockXPathTest { @Test public void shouldReportHtmlPath() throws IOException { try ( InputStream leftInput = getClass().getResourceAsStream("/sample/left/html/file2.html"); InputStream rightInput = getClass().getResourceAsStream("/sample/right/html/file2.html") ) { Assert.assertNotNull(leftInput); Assert.assertNotNull(rightInput); String left = IOUtils.toString(leftInput, StandardCharsets.UTF_8); String right = IOUtils.toString(rightInput, StandardCharsets.UTF_8); right = right.replace("<head>", "<head><meta value=\"Additional 1\"/>"); right = right.replace("<body class=\"body\">", "<body class=\"body\"><p>Additional 2</p>"); right = right.replace("</body>", "<p>Additional 3</p></body>");
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff.comparison; public class DiffBlockXPathTest { @Test public void shouldReportHtmlPath() throws IOException { try ( InputStream leftInput = getClass().getResourceAsStream("/sample/left/html/file2.html"); InputStream rightInput = getClass().getResourceAsStream("/sample/right/html/file2.html") ) { Assert.assertNotNull(leftInput); Assert.assertNotNull(rightInput); String left = IOUtils.toString(leftInput, StandardCharsets.UTF_8); String right = IOUtils.toString(rightInput, StandardCharsets.UTF_8); right = right.replace("<head>", "<head><meta value=\"Additional 1\"/>"); right = right.replace("<body class=\"body\">", "<body class=\"body\"><p>Additional 2</p>"); right = right.replace("</body>", "<p>Additional 3</p></body>");
Diff diff = DiffTask
1
2023-11-16 14:29:45+00:00
2k
jimbro1000/DriveWire4Rebuild
src/main/java/org/thelair/dw4/drivewire/ports/tcp/DWTcpPort.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": "public interface DWIPort {\n /**\n * Open target port with given definition and register with port handler.\n * @param port definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void openWith(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Modify port from definition.\n * @param port revised definition record\n * @throws InvalidPortTypeDefinition on invalid definition type.\n */\n void setPortDef(BasePortDef port) throws InvalidPortTypeDefinition;\n\n /**\n * Identify port type.\n * @return port type id.\n */\n int identifyPort();\n\n /**\n * Close port and deregister with port handler.\n */\n void closePort();\n\n /**\n * Serialise port definition as String.\n *\n * @return port definition values\n */\n String getPortDefinition();\n}" }, { "identifier": "DWIPortType", "path": "src/main/java/org/thelair/dw4/drivewire/ports/DWIPortType.java", "snippet": "public interface DWIPortType {\n /**\n * Port type enum.\n * Implements a conversion to int\n */\n enum DWPortTypeIdentity {\n /**\n * null port.\n */\n NULL_PORT(0),\n /**\n * RS232 serial port.\n */\n SERIAL_PORT(1),\n /**\n * TCP port.\n */\n TCP_PORT(2);\n /**\n * int equivalent of port type.\n */\n private final int type;\n DWPortTypeIdentity(final int portType) {\n this.type = portType;\n }\n\n /**\n * Get enum port type as int.\n * @return port type as int\n */\n public int getPortType() {\n return type;\n }\n }\n\n /**\n * Identify type of port.\n * @return port type\n */\n DWPortTypeIdentity identify();\n\n /**\n * Get map of port definition.\n * @return port definition\n */\n Map<String, Integer> getPortDetail();\n}" }, { "identifier": "InvalidPortTypeDefinition", "path": "src/main/java/org/thelair/dw4/drivewire/ports/InvalidPortTypeDefinition.java", "snippet": "@Getter\npublic class InvalidPortTypeDefinition extends InvalidObjectException {\n /**\n * Port definition causing the exception.\n */\n private final BasePortDef sourcePortDef;\n /**\n * Constructs an {@code InvalidObjectException}.\n *\n * @param reason Detailed message explaining the reason for the failure.\n * @param portDef Causing port definition object\n * @see ObjectInputValidation\n */\n public InvalidPortTypeDefinition(final String reason,\n final BasePortDef portDef) {\n super(reason);\n sourcePortDef = portDef;\n }\n}" } ]
import org.thelair.dw4.drivewire.ports.BasePortDef; import org.thelair.dw4.drivewire.ports.DWIPort; import org.thelair.dw4.drivewire.ports.DWIPortType; import org.thelair.dw4.drivewire.ports.InvalidPortTypeDefinition;
959
package org.thelair.dw4.drivewire.ports.tcp; /** * Drivewire TCP port record. */ public final class DWTcpPort implements DWIPort { /** * TCP port definition. */ private TcpPortDef portDef; @Override public void openWith(final BasePortDef port) throws InvalidPortTypeDefinition { portDef = validatePortDef(port); //register } @Override public void setPortDef(final BasePortDef port) throws InvalidPortTypeDefinition { portDef = validatePortDef(port); } @Override public int identifyPort() {
package org.thelair.dw4.drivewire.ports.tcp; /** * Drivewire TCP port record. */ public final class DWTcpPort implements DWIPort { /** * TCP port definition. */ private TcpPortDef portDef; @Override public void openWith(final BasePortDef port) throws InvalidPortTypeDefinition { portDef = validatePortDef(port); //register } @Override public void setPortDef(final BasePortDef port) throws InvalidPortTypeDefinition { portDef = validatePortDef(port); } @Override public int identifyPort() {
return DWIPortType.DWPortTypeIdentity.TCP_PORT.getPortType();
2
2023-11-18 11:35:16+00:00
2k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/render/bulletShell/BulletShellRenderer.java
[ { "identifier": "IAnimation", "path": "src/main/java/sheridan/gunscraft/animation/IAnimation.java", "snippet": "public interface IAnimation {\n void play(float delta, MatrixStack matrixStackIn, ItemCameraTransforms.TransformType transformType);\n void play(long beginTime, MatrixStack matrixStackIn, ItemCameraTransforms.TransformType transformType);\n float getProgress();\n void setProgress(float progress);\n boolean isCompleted();\n void reset();\n}" }, { "identifier": "Curve", "path": "src/main/java/sheridan/gunscraft/animation/curve/Curve.java", "snippet": "public abstract class Curve {\n public float minXVal, maxXVal;\n private float dis = 1;\n\n\n\n public Curve setBound(float minXVal, float maxXVal) {\n this.maxXVal = maxXVal;\n this.minXVal = minXVal;\n if (minXVal < maxXVal) {\n dis = maxXVal - minXVal;\n }\n return this;\n }\n\n public float play(float progress) {\n float xVal = minXVal + dis * progress;\n xVal = Math.min(xVal, maxXVal);\n return getVal(xVal);\n }\n\n public abstract float getVal(float xVal);\n\n}" }, { "identifier": "CurveAnimation", "path": "src/main/java/sheridan/gunscraft/animation/curve/CurveAnimation.java", "snippet": "public class CurveAnimation implements IAnimation {\n private float progress;\n public float length;\n public float timer;\n public boolean completed;\n\n public Curve[] curves;\n public float tempTX, tempTY,tempTZ, tempRX, tempRY, tempRZ, tempSX, tempSY, tempSZ;\n public ICurveAnimationProxy animationProxy;\n\n public CurveAnimation(Curve[] ICurves, float length) {\n this.curves = ICurves;\n this.length = length;\n }\n\n @Override\n public void play(float delta, MatrixStack matrixStackIn, ItemCameraTransforms.TransformType transformType) {\n update(delta);\n if (!completed) {\n computing(matrixStackIn, transformType);\n }\n }\n\n @Override\n public void play(long beginTime, MatrixStack matrixStackIn, ItemCameraTransforms.TransformType transformType) {\n long dis = System.currentTimeMillis() - beginTime;\n float delta = (float) dis / 1000f;\n reset();\n update(delta);\n if (!completed) {\n computing(matrixStackIn, transformType);\n }\n }\n\n private void update(float delta) {\n timer += delta;\n progress = timer / length;\n completed = false;\n if (progress >= 1) {\n progress = 0;\n timer = 0;\n completed = true;\n }\n }\n\n private void computing(MatrixStack matrixStack, ItemCameraTransforms.TransformType transformType) {\n\n tempTX = curves.length > 0 && curves[0] != null ? curves[0].play(progress) : 0;\n tempTY = curves.length > 1 && curves[1] != null ? curves[1].play(progress) : 0;\n tempTZ = curves.length > 2 && curves[2] != null ? curves[2].play(progress) : 0;\n\n tempRX = curves.length > 3 && curves[3] != null ? curves[3].play(progress) : 0;\n tempRY = curves.length > 4 && curves[4] != null ? curves[4].play(progress) : 0;\n tempRZ = curves.length > 5 && curves[5] != null ? curves[5].play(progress) : 0;\n\n tempSX = curves.length > 6 && curves[6] != null ? curves[6].play(progress) : 1;\n tempSY = curves.length > 7 && curves[7] != null ? curves[7].play(progress) : 1;\n tempSZ = curves.length > 8 && curves[8] != null ? curves[8].play(progress) : 1;\n\n if (animationProxy != null) {\n animationProxy.beforeApplyTransform(this, transformType);\n }\n applyTransform(matrixStack);\n }\n\n private void applyTransform(MatrixStack matrixStack) {\n if (tempTX != 0 || tempTY != 0 || tempTZ != 0) {\n matrixStack.translate(tempTX, tempTY, tempTZ);\n }\n\n if (tempRX != 0 || tempRY != 0 || tempRZ != 0) {\n matrixStack.rotate(new Quaternion(tempRX, tempRY, tempRZ, true));\n }\n\n if (tempSX != 1 || tempSY != 1 || tempSZ != 1) {\n matrixStack.scale(tempSX, tempSY, tempSZ);\n }\n }\n\n @Override\n public float getProgress() {\n return progress;\n }\n\n @Override\n public void setProgress(float progress) {\n this.progress = progress;\n }\n\n @Override\n public boolean isCompleted() {\n return completed;\n }\n\n @Override\n public void reset() {\n completed = false;\n progress = 0f;\n timer = 0f;\n }\n\n}" } ]
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.*; import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.vector.Quaternion; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.model.TransformationHelper; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import sheridan.gunscraft.animation.IAnimation; import sheridan.gunscraft.animation.curve.Curve; import sheridan.gunscraft.animation.curve.CurveAnimation; import java.util.*; import java.util.concurrent.LinkedBlockingDeque;
1,547
package sheridan.gunscraft.render.bulletShell; public class BulletShellRenderer { private static ModelBulletShell MODEL_BASIC = new ModelBulletShell(); public static final int MAX_BULLET_MUN = 5; private static Deque<AnimationContext> animations = new LinkedList<>(); private static PlayerEntity player; public static void push(MatrixStack matrixStack, float xSpeed, float ySpeed, float zSpeed, int rSpeed, float drop, float random, float length, String modelType, boolean mainHand) { float seed = (float) (random * Math.random());
package sheridan.gunscraft.render.bulletShell; public class BulletShellRenderer { private static ModelBulletShell MODEL_BASIC = new ModelBulletShell(); public static final int MAX_BULLET_MUN = 5; private static Deque<AnimationContext> animations = new LinkedList<>(); private static PlayerEntity player; public static void push(MatrixStack matrixStack, float xSpeed, float ySpeed, float zSpeed, int rSpeed, float drop, float random, float length, String modelType, boolean mainHand) { float seed = (float) (random * Math.random());
IAnimation animation = new CurveAnimation(new Curve[]{
2
2023-11-14 14:00:55+00:00
2k
zpascual/5419-Arm-Example
src/main/java/com/team254/lib/geometry/Rotation2d.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 input to the given magnitude.\n */\n public static double limit(double v, double maxMagnitude) {\n return limit(v, -maxMagnitude, maxMagnitude);\n }\n\n public static double limit(double v, double min, double max) {\n return Math.min(max, Math.max(min, v));\n }\n \n public static boolean inRange(double v, double maxMagnitude) {\n return inRange(v, -maxMagnitude, maxMagnitude);\n }\n\n /**\n * Checks if the given input is within the range (min, max), both exclusive.\n */\n public static boolean inRange(double v, double min, double max) {\n return v > min && v < max;\n }\n\n public static double interpolate(double a, double b, double x) {\n x = limit(x, 0.0, 1.0);\n return a + (b - a) * x;\n }\n\n public static String joinStrings(final String delim, final List<?> strings) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < strings.size(); ++i) {\n sb.append(strings.get(i).toString());\n if (i < strings.size() - 1) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n public static boolean epsilonEquals(double a, double b, double epsilon) {\n return (a - epsilon <= b) && (a + epsilon >= b);\n }\n\n public static boolean epsilonEquals(double a, double b) {\n return epsilonEquals(a, b, kEpsilon);\n }\n\n public static boolean epsilonEquals(int a, int b, int epsilon) {\n return (a - epsilon <= b) && (a + epsilon >= b);\n }\n\n public static boolean allCloseTo(final List<Double> list, double value, double epsilon) {\n boolean result = true;\n for (Double value_in : list) {\n result &= epsilonEquals(value_in, value, epsilon);\n }\n return result;\n }\n}" }, { "identifier": "kEpsilon", "path": "src/main/java/com/team254/lib/util/Util.java", "snippet": "public static final double kEpsilon = 1e-12;" } ]
import com.team254.lib.util.Util; import java.text.DecimalFormat; import static com.team254.lib.util.Util.kEpsilon;
881
package com.team254.lib.geometry; /** * A rotation in a 2d coordinate frame represented a point on the unit circle (cosine and sine). * <p> * Inspired by Sophus (https://github.com/strasdat/Sophus/tree/master/sophus) */ public class Rotation2d implements IRotation2d<Rotation2d> { protected static final Rotation2d kIdentity = new Rotation2d(); public static final Rotation2d identity() { return kIdentity; } protected final double cos_angle_; protected final double sin_angle_; protected double theta_degrees = 0; protected double theta_radians = 0; public Rotation2d() { this(1, 0, false); } public Rotation2d(double x, double y, boolean normalize) { if (normalize) { // From trig, we know that sin^2 + cos^2 == 1, but as we do math on this object we might accumulate rounding errors. // Normalizing forces us to re-scale the sin and cos to reset rounding errors. double magnitude = Math.hypot(x, y);
package com.team254.lib.geometry; /** * A rotation in a 2d coordinate frame represented a point on the unit circle (cosine and sine). * <p> * Inspired by Sophus (https://github.com/strasdat/Sophus/tree/master/sophus) */ public class Rotation2d implements IRotation2d<Rotation2d> { protected static final Rotation2d kIdentity = new Rotation2d(); public static final Rotation2d identity() { return kIdentity; } protected final double cos_angle_; protected final double sin_angle_; protected double theta_degrees = 0; protected double theta_radians = 0; public Rotation2d() { this(1, 0, false); } public Rotation2d(double x, double y, boolean normalize) { if (normalize) { // From trig, we know that sin^2 + cos^2 == 1, but as we do math on this object we might accumulate rounding errors. // Normalizing forces us to re-scale the sin and cos to reset rounding errors. double magnitude = Math.hypot(x, y);
if (magnitude > kEpsilon) {
1
2023-11-14 06:44:40+00:00
2k
Ouest-France/querydsl-postgrest
src/test/java/fr/ouestfrance/querydsl/postgrest/mappers/ContainedMapperTest.java
[ { "identifier": "PostgrestFilterOperation", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/PostgrestFilterOperation.java", "snippet": "public interface PostgrestFilterOperation {\n /**\n * Case-insensitive like\n */\n @ValidatedBy(StringValidator.class)\n class ILIKE implements FilterOperation {\n }\n\n /**\n * Contains for JSON/Range datatype\n */\n @ValidatedBy(StringValidator.class)\n class CS implements FilterOperation {\n }\n\n /**\n * Contained for JSON/Range datatype\n */\n @ValidatedBy(StringValidator.class)\n class CD implements FilterOperation {\n }\n}" }, { "identifier": "QueryFilterVisitor", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/builders/QueryFilterVisitor.java", "snippet": "public final class QueryFilterVisitor {\n\n private static final String DOT = \".\";\n private static final String OPEN_PARENTHESIS = \"(\";\n private static final String CLOSE_PARENTHESIS = \")\";\n private static final String COMA = \",\";\n private static final String EMPTY_STRING = \"\";\n\n /**\n * StringBuilder\n */\n private final StringBuilder builder = new StringBuilder();\n\n /**\n * Transform SimpleFilter to Query\n *\n * @param filter simple filter\n */\n public void visit(QueryFilter filter) {\n builder.append(filter.getOperator()).append(QueryFilterVisitor.DOT).append(filter.getValue());\n }\n\n /**\n * Transform OrderFilter to Query\n *\n * @param filter order filter\n */\n public void visit(OrderFilter filter) {\n builder.append(filter.getSort().getOrders().stream().map(\n x -> x.getProperty()\n + (Sort.Direction.ASC.equals(x.getDirection()) ? EMPTY_STRING : DOT + \"desc\")\n + (switch (x.getNullHandling()) {\n case NATIVE -> EMPTY_STRING;\n case NULLS_FIRST -> DOT + \"nullsfirst\";\n case NULLS_LAST -> DOT + \"nullslast\";\n })).collect(Collectors.joining(COMA)));\n }\n\n /**\n * Transform a Select filter to Query\n *\n * @param filter select filter\n */\n public void visit(SelectFilter filter) {\n builder.append(\"*,\");\n builder.append(filter.getSelectAttributes().stream().map(\n x -> x.getAlias().isEmpty() ? x.getValue() : x.getAlias() + \":\" + x.getValue())\n .collect(Collectors.joining(\",\")));\n }\n\n /**\n * Transform a Composite filter to Query\n *\n * @param filter composite filter\n */\n public void visit(CompositeFilter filter) {\n // Check items aliases\n Filter lastElement = getLastElement(filter.getFilters());\n\n builder.append(OPEN_PARENTHESIS);\n filter.getFilters().forEach(item -> {\n builder.append(item.getKey());\n if (item instanceof QueryFilter) {\n builder.append(DOT);\n }\n item.accept(this);\n if (!item.equals(lastElement)) {\n builder.append(COMA);\n }\n });\n builder.append(CLOSE_PARENTHESIS);\n }\n\n /**\n * Return the last element of a list\n *\n * @param filters list of filters\n * @return last element\n */\n private Filter getLastElement(List<Filter> filters) {\n return filters.get(filters.size() - 1);\n }\n\n /**\n * Return string representation of the queryString\n *\n * @return string representation of the queryString\n */\n public String getValue() {\n return builder.toString();\n }\n}" }, { "identifier": "Filter", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/Filter.java", "snippet": "public interface Filter extends FilterVisitor {\n\n /**\n * Get the filter key\n * @return filter key\n */\n String getKey();\n\n}" } ]
import fr.ouestfrance.querydsl.model.SimpleFilter; import fr.ouestfrance.querydsl.postgrest.PostgrestFilterOperation; import fr.ouestfrance.querydsl.postgrest.builders.QueryFilterVisitor; import fr.ouestfrance.querydsl.postgrest.model.Filter; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull;
1,056
package fr.ouestfrance.querydsl.postgrest.mappers; class ContainedMapperTest { @Test void shouldMapCaseInsensitive(){ ContainedMapper mapper = new ContainedMapper(); assertNotNull(mapper.operation());
package fr.ouestfrance.querydsl.postgrest.mappers; class ContainedMapperTest { @Test void shouldMapCaseInsensitive(){ ContainedMapper mapper = new ContainedMapper(); assertNotNull(mapper.operation());
Filter result = mapper.map(new SimpleFilter("name", PostgrestFilterOperation.CD.class, false, null), "John");
0
2023-11-14 10:45:54+00:00
2k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/utils/Projects.java
[ { "identifier": "EditTextInterface", "path": "app/src/main/java/com/threethan/questpatcher/interfaces/EditTextInterface.java", "snippet": "public abstract class EditTextInterface {\n\n private final Context mContext;\n private final MaterialAlertDialogBuilder mDialogBuilder;\n private final String mText, mTitle;\n\n public EditTextInterface(String text, String title, Context context) {\n this.mText = text;\n this.mTitle = title;\n this.mContext = context;\n this.mDialogBuilder = new MaterialAlertDialogBuilder(context);\n }\n\n private void startDialog() {\n LinearLayout layout = new LinearLayout(mContext);\n layout.setPadding(75, 75, 75, 75);\n final AppCompatEditText editText = new AppCompatEditText(mContext);\n editText.setGravity(Gravity.CENTER);\n editText.setLayoutParams(new LinearLayout.LayoutParams(\n ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));\n if (mText != null) {\n editText.append(mText);\n }\n editText.setSingleLine(true);\n editText.requestFocus();\n layout.addView(editText);\n\n if (mTitle != null) {\n mDialogBuilder.setTitle(mTitle);\n mDialogBuilder.setIcon(R.mipmap.ic_launcher);\n }\n mDialogBuilder.setView(layout);\n mDialogBuilder.setIcon(R.mipmap.ic_launcher);\n mDialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> {\n });\n mDialogBuilder.setPositiveButton(R.string.ok, (dialog, id) ->\n positiveButtonLister(editText.getText())\n ).show();\n }\n\n public void show() {\n startDialog();\n }\n\n public abstract void positiveButtonLister(Editable s);\n\n}" }, { "identifier": "ExportProject", "path": "app/src/main/java/com/threethan/questpatcher/utils/tasks/ExportProject.java", "snippet": "public class ExportProject extends sExecutor {\n\n private final Context mContext;\n private final File mFile;\n private ProgressDialog mProgressDialog;\n private final String mName;\n\n public ExportProject(File file, String name, Context context) {\n mFile = file;\n mName = name;\n mContext = context;\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void onPreExecute() {\n mProgressDialog = new ProgressDialog(mContext);\n mProgressDialog.setMessage(mContext.getString(R.string.exporting, mFile.getName()));\n mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);\n mProgressDialog.setIcon(R.mipmap.ic_launcher);\n mProgressDialog.setTitle(R.string.app_name);\n mProgressDialog.setIndeterminate(true);\n mProgressDialog.setCancelable(false);\n mProgressDialog.show();\n if (sFileUtils.exist(new File(Projects.getExportPath(mContext), mName))) {\n sFileUtils.delete(new File(Projects.getExportPath(mContext), mName));\n }\n }\n\n @Override\n public void doInBackground() {\n sFileUtils.copyDir(mFile, new File(Projects.getExportPath(mContext), mName));\n }\n\n @Override\n public void onPostExecute() {\n try {\n mProgressDialog.dismiss();\n } catch (IllegalArgumentException ignored) {\n }\n }\n\n}" } ]
import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.os.Environment; import android.text.Editable; import com.threethan.questpatcher.R; import com.threethan.questpatcher.interfaces.EditTextInterface; import com.threethan.questpatcher.utils.tasks.ExportProject; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils;
1,149
package com.threethan.questpatcher.utils; /* * Created by APK Explorer & Editor <[email protected]> on March 04, 2021 */ public class Projects { public static List<String> getData(Context context) { List<String> mData = new ArrayList<>(); for (File mFile : Objects.requireNonNull(new File(context.getCacheDir().toString()).listFiles())) { if (mFile.exists() && mFile.isDirectory() && new File(mFile, ".aeeBackup/appData").exists()) { if (Common.getSearchWord() == null) { mData.add(mFile.getAbsolutePath()); } else if (Common.isTextMatched(mFile.getName(), Common.getSearchWord())) { mData.add(mFile.getAbsolutePath()); } } } Collections.sort(mData); if (!sCommonUtils.getBoolean("az_order", true, context)) { Collections.reverse(mData); } return mData; } public static String getExportPath(Context context) { if (Build.VERSION.SDK_INT < 29 && sCommonUtils.getString("exportPath", null, context) != null) { return sCommonUtils.getString("exportPath", null, context); } else { return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); } } public static void exportProject(File file, Context context) {
package com.threethan.questpatcher.utils; /* * Created by APK Explorer & Editor <[email protected]> on March 04, 2021 */ public class Projects { public static List<String> getData(Context context) { List<String> mData = new ArrayList<>(); for (File mFile : Objects.requireNonNull(new File(context.getCacheDir().toString()).listFiles())) { if (mFile.exists() && mFile.isDirectory() && new File(mFile, ".aeeBackup/appData").exists()) { if (Common.getSearchWord() == null) { mData.add(mFile.getAbsolutePath()); } else if (Common.isTextMatched(mFile.getName(), Common.getSearchWord())) { mData.add(mFile.getAbsolutePath()); } } } Collections.sort(mData); if (!sCommonUtils.getBoolean("az_order", true, context)) { Collections.reverse(mData); } return mData; } public static String getExportPath(Context context) { if (Build.VERSION.SDK_INT < 29 && sCommonUtils.getString("exportPath", null, context) != null) { return sCommonUtils.getString("exportPath", null, context); } else { return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString(); } } public static void exportProject(File file, Context context) {
new EditTextInterface(null, context.getString(R.string.app_name), context) {
0
2023-11-18 15:13:30+00:00
2k
wangxianhui111/xuechengzaixian
xuecheng-plus-generator/src/main/java/com/xuecheng/content/service/impl/CoursePublishPreServiceImpl.java
[ { "identifier": "CoursePublishPre", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublishPre.java", "snippet": "@Data\n@TableName(\"course_publish_pre\")\npublic class CoursePublishPre implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 提交时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 审核时间\n */\n private LocalDateTime auditDate;\n\n /**\n * 状态\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}" }, { "identifier": "CoursePublishPreMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CoursePublishPreMapper.java", "snippet": "public interface CoursePublishPreMapper extends BaseMapper<CoursePublishPre> {\n\n}" }, { "identifier": "CoursePublishPreService", "path": "xuecheng-plus-generator/src/main/java/com/xuecheng/content/service/CoursePublishPreService.java", "snippet": "public interface CoursePublishPreService extends IService<CoursePublishPre> {\n\n}" } ]
import com.xuecheng.content.model.po.CoursePublishPre; import com.xuecheng.content.mapper.CoursePublishPreMapper; import com.xuecheng.content.service.CoursePublishPreService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.beans.factory.annotation.Autowired;
935
package com.xuecheng.content.service.impl; /** * <p> * 课程发布 服务实现类 * </p> * * @author itcast */ @Slf4j @Service
package com.xuecheng.content.service.impl; /** * <p> * 课程发布 服务实现类 * </p> * * @author itcast */ @Slf4j @Service
public class CoursePublishPreServiceImpl extends ServiceImpl<CoursePublishPreMapper, CoursePublishPre> implements CoursePublishPreService {
0
2023-11-13 11:39:35+00:00
2k
dynatrace-research/ShuffleBench
shuffle-flink/src/main/java/com/dynatrace/research/shufflebench/AggregateFunction.java
[ { "identifier": "ConsumerEvent", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/ConsumerEvent.java", "snippet": "public class ConsumerEvent {\n private byte[] data;\n\n public ConsumerEvent() {\n }\n\n public ConsumerEvent(byte[] data) {\n this.data = data;\n }\n\n public byte[] getData() {\n return data;\n }\n\n public void setData(byte[] data) {\n this.data = data;\n }\n}" }, { "identifier": "ConsumerResult", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/ConsumerResult.java", "snippet": "public class ConsumerResult {\n\n private final State state;\n\n private final ConsumerEvent event; // May be null\n\n public ConsumerResult(final State state) {\n this.state = requireNonNull(state);\n this.event = null;\n }\n\n public ConsumerResult(final State state, final ConsumerEvent event) {\n this.state = requireNonNull(state);\n this.event = event;\n }\n\n public State getState() {\n return this.state;\n }\n\n public Optional<ConsumerEvent> getEvent() {\n return Optional.ofNullable(this.event);\n }\n}" }, { "identifier": "State", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/State.java", "snippet": "public class State {\n private byte[] data;\n\n public State() {\n }\n\n public State(byte[] data) {\n this.data = data;\n }\n\n public byte[] getData() {\n return data;\n }\n\n public void setData(byte[] data) {\n this.data = data;\n }\n\n}" }, { "identifier": "StatefulConsumer", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/consumer/StatefulConsumer.java", "snippet": "@FunctionalInterface\npublic interface StatefulConsumer extends Serializable {\n\n /**\n * @param record a new data record\n * @param state the current state\n * @return the updated state\n */\n ConsumerResult accept(TimestampedRecord record, State state);\n}" }, { "identifier": "TimestampedRecord", "path": "commons/src/main/java/com/dynatrace/research/shufflebench/record/TimestampedRecord.java", "snippet": "public class TimestampedRecord extends Record {\n\n private final long timestamp;\n\n public TimestampedRecord(final long timestamp, final byte[] data) {\n super(data);\n this.timestamp = timestamp;\n }\n\n public long getTimestamp() {\n return this.timestamp;\n }\n\n @Override\n public String toString() {\n return \"Record{\" + \"timestamp=\"+ this.timestamp + \",\" + \"data=\" + Util.bytesToHex(super.getData(), 0, 16) + \"...}\";\n }\n}" } ]
import com.dynatrace.research.shufflebench.consumer.ConsumerEvent; import com.dynatrace.research.shufflebench.consumer.ConsumerResult; import com.dynatrace.research.shufflebench.consumer.State; import com.dynatrace.research.shufflebench.consumer.StatefulConsumer; import com.dynatrace.research.shufflebench.record.TimestampedRecord; import org.apache.flink.api.common.state.ValueState; import org.apache.flink.api.common.state.ValueStateDescriptor; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.functions.KeyedProcessFunction; import org.apache.flink.util.Collector;
949
package com.dynatrace.research.shufflebench; public class AggregateFunction extends KeyedProcessFunction<String, Tuple2<String, TimestampedRecord>, Tuple2<String, ConsumerEvent>> { private final StatefulConsumer consumer; private ValueState<State> state; public AggregateFunction(StatefulConsumer consumer) { this.consumer = consumer; } @Override public void open(Configuration parameters) throws Exception { state = super.getRuntimeContext().getState(new ValueStateDescriptor<>("state", State.class)); } @Override public void processElement( Tuple2<String, TimestampedRecord> recordWithKey, Context ctx, Collector<Tuple2<String, ConsumerEvent>> out) throws Exception { final State stateValue = this.state.value();
package com.dynatrace.research.shufflebench; public class AggregateFunction extends KeyedProcessFunction<String, Tuple2<String, TimestampedRecord>, Tuple2<String, ConsumerEvent>> { private final StatefulConsumer consumer; private ValueState<State> state; public AggregateFunction(StatefulConsumer consumer) { this.consumer = consumer; } @Override public void open(Configuration parameters) throws Exception { state = super.getRuntimeContext().getState(new ValueStateDescriptor<>("state", State.class)); } @Override public void processElement( Tuple2<String, TimestampedRecord> recordWithKey, Context ctx, Collector<Tuple2<String, ConsumerEvent>> out) throws Exception { final State stateValue = this.state.value();
final ConsumerResult consumerResult = this.consumer.accept(recordWithKey.f1, stateValue);
1
2023-11-17 08:53:15+00:00
2k
KafeinDev/InteractiveNpcs
src/main/java/dev/kafein/interactivenpcs/compatibility/CompatibilityFactory.java
[ { "identifier": "InteractiveNpcs", "path": "src/main/java/dev/kafein/interactivenpcs/InteractiveNpcs.java", "snippet": "public final class InteractiveNpcs extends AbstractBukkitPlugin {\n private ConversationManager conversationManager;\n private CharWidthMap charWidthMap;\n\n public InteractiveNpcs(Plugin plugin) {\n super(plugin);\n }\n\n @Override\n public void onLoad() {}\n\n @Override\n public void onEnable() {\n this.charWidthMap = new CharWidthMap(this);\n this.charWidthMap.initialize();\n\n this.conversationManager = new ConversationManager(this);\n this.conversationManager.initialize();\n\n PluginManager pluginManager = Bukkit.getPluginManager();\n for (CompatibilityType compatibilityType : CompatibilityType.values()) {\n if (!pluginManager.isPluginEnabled(compatibilityType.getPluginName())) {\n continue;\n }\n\n Compatibility compatibility = CompatibilityFactory.createCompatibility(compatibilityType, this);\n if (compatibility != null) {\n compatibility.initialize();\n }\n }\n }\n\n @Override\n public void onDisable() {\n\n }\n\n @Override\n public Set<Command> getCommands() {\n return ImmutableSet.of(\n new InteractionCommand(this)\n );\n }\n\n @Override\n public Set<Class<?>> getListeners() {\n return ImmutableSet.of();\n }\n\n @Override\n public void startTasks() {\n BukkitScheduler scheduler = Bukkit.getScheduler();\n scheduler.scheduleSyncRepeatingTask(getPlugin(), new MovementControlTask(this), 0L, 10L);\n }\n\n @Override\n public void loadConfigs() {\n Config settingsConfig = getConfigManager().register(\"settings\", getClass(), \"/settings.yml\", \"settings.yml\");\n getConfigManager().injectKeys(ConfigVariables.class, settingsConfig);\n }\n\n public ConversationManager getConversationManager() {\n return this.conversationManager;\n }\n\n public CharWidthMap getCharWidthMap() {\n return this.charWidthMap;\n }\n}" }, { "identifier": "CitizensCompatibility", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/implementation/CitizensCompatibility.java", "snippet": "public final class CitizensCompatibility implements Compatibility, Listener {\n private final InteractiveNpcs plugin;\n\n public CitizensCompatibility(InteractiveNpcs plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void initialize() {\n PluginManager pluginManager = Bukkit.getPluginManager();\n pluginManager.registerEvents(this, this.plugin.getPlugin());\n }\n\n @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)\n public void onClick(NPCRightClickEvent event) {\n NPC npc = event.getNPC();\n\n InteractiveEntity interactiveEntity = this.plugin.getConversationManager().getInteractiveEntity(npc.getId());\n if (interactiveEntity == null) {\n return;\n }\n\n /*Location eyeLocation = interactiveNpc.getProperties().getEyeLocation() == null\n ? npc.getEntity().getLocation().clone()\n : interactiveNpc.getProperties().getEyeLocation();\n\n NpcProperties npcProperties = new NpcProperties(npc.getId(), eyeLocation);\n this.plugin.getInteractionManager().interact(event.getClicker(), npcProperties);*/\n }\n}" }, { "identifier": "VaultCompatibility", "path": "src/main/java/dev/kafein/interactivenpcs/compatibility/implementation/VaultCompatibility.java", "snippet": "public final class VaultCompatibility implements Compatibility {\n private static @Nullable Economy economy;\n\n private final InteractiveNpcs plugin;\n\n public VaultCompatibility(InteractiveNpcs plugin) {\n this.plugin = plugin;\n }\n\n @Override\n public void initialize() {\n RegisteredServiceProvider<Economy> serviceProvider = Bukkit.getServicesManager().getRegistration(Economy.class);\n if (serviceProvider == null) {\n this.plugin.getLogger().warning(\"Vault is not installed. Economy features will not be available.\");\n return;\n }\n\n economy = serviceProvider.getProvider();\n }\n\n public static @Nullable Economy getEconomy() {\n return economy;\n }\n}" } ]
import dev.kafein.interactivenpcs.InteractiveNpcs; import dev.kafein.interactivenpcs.compatibility.implementation.CitizensCompatibility; import dev.kafein.interactivenpcs.compatibility.implementation.VaultCompatibility; import org.jetbrains.annotations.NotNull;
1,058
package dev.kafein.interactivenpcs.compatibility; public final class CompatibilityFactory { private CompatibilityFactory() { }
package dev.kafein.interactivenpcs.compatibility; public final class CompatibilityFactory { private CompatibilityFactory() { }
public static Compatibility createCompatibility(@NotNull CompatibilityType type, @NotNull InteractiveNpcs plugin) {
0
2023-11-18 10:12:16+00:00
2k
jensjeflensje/minecraft_typewriter
src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/component/button/BarTypeWriterButtonComponent.java
[ { "identifier": "TypewriterPlugin", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java", "snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin instance;\n\n @Override\n public void onEnable() {\n instance = this;\n\n getCommand(\"typewriter\").setExecutor(new SpawnCommand());\n getCommand(\"wc\").setExecutor(new CompleteCommand());\n getCommand(\"wr\").setExecutor(new RemoveCommand());\n getCommand(\"w\").setExecutor(new WriteCommand());\n getCommand(\"w\").setTabCompleter(new WriteTabCompleter());\n\n playerWriters = new HashMap<>();\n\n }\n\n @Override\n public void onDisable() {\n playerWriters.values().forEach(TypeWriter::destroy);\n }\n}" }, { "identifier": "Util", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/Util.java", "snippet": "public class Util {\n\n /**\n * Get the location of an offset from a location, rotated by a yaw.\n * @param baseLocation the origin of the rotation\n * @param offset the offset as a vector. Only uses X and Z coordinates\n * @param baseYaw the yaw for the rotation\n * @param pitch pitch value to add to the location\n * @param yaw yaw value to add to the baseYaw after rotation\n * @return the resulting Location\n */\n public static Location getRotatedLocation(\n Location baseLocation,\n Vector offset,\n float baseYaw,\n float pitch,\n float yaw\n ) {\n Location rotatedLocation = baseLocation.clone();\n rotatedLocation.add(getRotatedVector(offset, baseYaw));\n rotatedLocation.setYaw(baseYaw + yaw);\n rotatedLocation.setPitch(pitch);\n return rotatedLocation;\n }\n\n public static Vector getRotatedVector(\n Vector offset,\n float baseYaw\n ) {\n double sinus = Math.sin(baseYaw / 180 * Math.PI);\n double cosinus = Math.cos(baseYaw / 180 * Math.PI);\n double newX = offset.getX() * cosinus - offset.getZ() * sinus;\n double newZ = offset.getZ() * cosinus + offset.getX() * sinus;\n return new Vector(newX, offset.getY(), newZ);\n }\n\n}" } ]
import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin; import dev.jensderuiter.minecrafttypewriter.Util; import lombok.Getter; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.SoundCategory; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.ItemDisplay; import org.bukkit.inventory.ItemStack; import org.bukkit.util.Transformation; import org.bukkit.util.Vector; import java.util.ArrayList; import java.util.List;
823
package dev.jensderuiter.minecrafttypewriter.typewriter.component.button; public class BarTypeWriterButtonComponent extends BaseTypeWriterButtonComponent { private final double Y_VALUE = -0.15; private ItemStack skull; private List<ItemDisplay> skullDisplays; private int amount; @Getter private Location location; public BarTypeWriterButtonComponent(ItemStack skull, int amount) { this.skull = skull; this.amount = amount; this.skullDisplays = new ArrayList<>(); } @Override public void setUp(Location location) { this.location = location; for (int i = 0; i < this.amount; i++) {
package dev.jensderuiter.minecrafttypewriter.typewriter.component.button; public class BarTypeWriterButtonComponent extends BaseTypeWriterButtonComponent { private final double Y_VALUE = -0.15; private ItemStack skull; private List<ItemDisplay> skullDisplays; private int amount; @Getter private Location location; public BarTypeWriterButtonComponent(ItemStack skull, int amount) { this.skull = skull; this.amount = amount; this.skullDisplays = new ArrayList<>(); } @Override public void setUp(Location location) { this.location = location; for (int i = 0; i < this.amount; i++) {
Location displayLocation = Util.getRotatedLocation(
1
2023-11-18 20:44:30+00:00
2k
Nurislom373/SpringMicroservice
Observability/Grafana/src/main/java/og/khasanof/grafana/handler/LastRequestMeterObservationHandler.java
[ { "identifier": "AbstractObservationHandler", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/AbstractObservationHandler.java", "snippet": "public abstract class AbstractObservationHandler implements IObservationHandler {\n\n private AbstractObservationHandler nextObservationHandler;\n\n public AbstractObservationHandler() {\n }\n\n public AbstractObservationHandler(AbstractObservationHandler nextObservationHandler) {\n this.nextObservationHandler = nextObservationHandler;\n }\n\n public AbstractObservationHandler next(AbstractObservationHandler nextObservationHandler) {\n this.nextObservationHandler = nextObservationHandler;\n return this;\n }\n\n @Override\n public void onStart(Observation.Context context, boolean moveToNext) {\n onStart(context);\n nextObservationHandlerOnStart(context, moveToNext);\n }\n\n @Override\n public void onStop(Observation.Context context, boolean moveToNext) {\n onStop(context);\n nextObservationHandlerOnStop(context, moveToNext);\n }\n\n private void nextObservationHandlerOnStart(Observation.Context context, boolean moveToNext) {\n nextObservationHandlerOnRunnable(moveToNext, () -> nextObservationHandlerOnStart(context, moveToNext));\n }\n\n private void nextObservationHandlerOnStop(Observation.Context context, boolean moveToNext) {\n nextObservationHandlerOnRunnable(moveToNext, () -> nextObservationHandlerOnStop(context, moveToNext));\n }\n\n private void nextObservationHandlerOnRunnable(boolean moveToNext, Runnable runnable) {\n if (Objects.nonNull(nextObservationHandler) && moveToNext) {\n runnable.run();\n }\n }\n\n protected final List<Tag> getTags(Observation.Context context) {\n List<Tag> tags = createTags(context);\n tags.add(Tag.of(\"error\", getErrorValue(context)));\n return tags;\n }\n\n}" }, { "identifier": "ObserveType", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/enumeration/ObserveType.java", "snippet": "public enum ObserveType {\n TIMER, LAST_REQUEST\n}" }, { "identifier": "LastRequestStartTimeFactory", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/factories/request/LastRequestStartTimeFactory.java", "snippet": "public interface LastRequestStartTimeFactory {\n\n LastRequestStartTime create(Instant startTime);\n\n}" }, { "identifier": "LastRequestStartTime", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/models/request/LastRequestStartTime.java", "snippet": "public interface LastRequestStartTime {\n\n Instant getStartTime();\n\n}" }, { "identifier": "MeterSuffixes", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/utils/MeterSuffixes.java", "snippet": "public abstract class MeterSuffixes {\n\n public static final String TIMER = \"_timer\";\n public static final String LAST_REQUEST = \"_last_request\";\n\n}" }, { "identifier": "betweenMillisSeconds", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/utils/BaseUtils.java", "snippet": "public static long betweenMillisSeconds(Instant startTime, Instant endTime) {\n return Duration.between(startTime, endTime).toMillis();\n}" }, { "identifier": "concat", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/utils/BaseUtils.java", "snippet": "public static String concat(String var1, String var2) {\n return var1.concat(var2);\n}" } ]
import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.Tag; import io.micrometer.observation.Observation; import io.micrometer.prometheus.PrometheusMeterRegistry; import og.khasanof.grafana.AbstractObservationHandler; import og.khasanof.grafana.enumeration.ObserveType; import og.khasanof.grafana.factories.request.LastRequestStartTimeFactory; import og.khasanof.grafana.models.request.LastRequestStartTime; import og.khasanof.grafana.utils.MeterSuffixes; import org.springframework.stereotype.Component; import java.time.Instant; import java.util.List; import static og.khasanof.grafana.utils.BaseUtils.betweenMillisSeconds; import static og.khasanof.grafana.utils.BaseUtils.concat;
1,214
package og.khasanof.grafana.handler; /** * @author Nurislom * @see og.khasanof.grafana.handler * @since 12/15/2023 2:36 PM */ @Component public class LastRequestMeterObservationHandler extends AbstractObservationHandler { private static final String METER_SUFFIX = MeterSuffixes.LAST_REQUEST; private final PrometheusMeterRegistry meterRegistry; private final LastRequestStartTimeFactory startTimeFactory; public LastRequestMeterObservationHandler(PrometheusMeterRegistry meterRegistry, LastRequestStartTimeFactory startTimeFactory) { this.meterRegistry = meterRegistry; this.startTimeFactory = startTimeFactory; } @Override public void onStart(Observation.Context context) { LastRequestStartTime startTime = startTimeFactory.create(Instant.now()); context.put(LastRequestStartTime.class, startTime); } @Override public void onStop(Observation.Context context) { Instant endTime = Instant.now(); LastRequestStartTime startTime = context.getRequired(LastRequestStartTime.class); gaugeRegistry(context, startTime.getStartTime(), endTime, getTags(context)); } private void gaugeRegistry(Observation.Context context, Instant startTime, Instant endTime, List<Tag> tags) {
package og.khasanof.grafana.handler; /** * @author Nurislom * @see og.khasanof.grafana.handler * @since 12/15/2023 2:36 PM */ @Component public class LastRequestMeterObservationHandler extends AbstractObservationHandler { private static final String METER_SUFFIX = MeterSuffixes.LAST_REQUEST; private final PrometheusMeterRegistry meterRegistry; private final LastRequestStartTimeFactory startTimeFactory; public LastRequestMeterObservationHandler(PrometheusMeterRegistry meterRegistry, LastRequestStartTimeFactory startTimeFactory) { this.meterRegistry = meterRegistry; this.startTimeFactory = startTimeFactory; } @Override public void onStart(Observation.Context context) { LastRequestStartTime startTime = startTimeFactory.create(Instant.now()); context.put(LastRequestStartTime.class, startTime); } @Override public void onStop(Observation.Context context) { Instant endTime = Instant.now(); LastRequestStartTime startTime = context.getRequired(LastRequestStartTime.class); gaugeRegistry(context, startTime.getStartTime(), endTime, getTags(context)); } private void gaugeRegistry(Observation.Context context, Instant startTime, Instant endTime, List<Tag> tags) {
Gauge.builder(concat(context.getName(), METER_SUFFIX), () -> betweenMillisSeconds(startTime, endTime))
6
2023-11-18 07:57:34+00:00
2k
ZhiQinIsZhen/dubbo-springboot3
dubbo-service/dubbo-service-search/search-biz/src/main/java/com/liyz/boot3/service/search/response/EsResponse.java
[ { "identifier": "RemotePage", "path": "dubbo-common/dubbo-common-remote/src/main/java/com/liyz/boot3/common/remote/page/RemotePage.java", "snippet": "public class RemotePage<T> implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n public static <T> RemotePage<T> of() {\n return new RemotePage<>(List.of(), 0, 1, 10);\n }\n\n public static <T> RemotePage<T> of(List<T> list, long total, long pageNum, long pageSize) {\n return new RemotePage<>(list, total, pageNum, pageSize);\n }\n\n public RemotePage(List<T> list, long total, long pageNum, long pageSize) {\n this.list = list;\n this.total = total;\n this.pageNum = pageNum;\n this.pageSize = pageSize;\n }\n\n /**\n * 结果集\n */\n private List<T> list;\n\n /**\n * 总记录数\n */\n private long total;\n\n /**\n * 当前页\n */\n private long pageNum;\n\n /**\n * 每页的数量\n */\n private long pageSize;\n\n public List<T> getList() {\n return list;\n }\n\n public void setList(List<T> list) {\n this.list = list;\n }\n\n public long getTotal() {\n return total;\n }\n\n public void setTotal(long total) {\n this.total = total;\n }\n\n public long getPageNum() {\n return pageNum;\n }\n\n public void setPageNum(long pageNum) {\n this.pageNum = Math.max(1L, pageNum);\n }\n\n public long getPageSize() {\n return pageSize;\n }\n\n public void setPageSize(long pageSize) {\n this.pageSize = Math.max(1L, pageSize);\n }\n\n public long getPages() {\n return this.total % this.pageSize == 0 ? this.total / this.pageSize : this.total / this.pageSize + 1;\n }\n\n public boolean isHasNextPage() {\n return getPages() > pageNum;\n }\n}" }, { "identifier": "AggBO", "path": "dubbo-service/dubbo-service-search/search-remote/src/main/java/com/liyz/boot3/service/search/bo/agg/AggBO.java", "snippet": "@Getter\n@Setter\npublic class AggBO implements Serializable {\n @Serial\n private static final long serialVersionUID = -4672225002891936839L;\n\n private String name;\n\n private long count;\n\n public static AggBO of(String name, long count) {\n AggBO aggBO = new AggBO();\n aggBO.setName(name);\n aggBO.setCount(count);\n return aggBO;\n }\n}" } ]
import com.liyz.boot3.common.remote.page.RemotePage; import com.liyz.boot3.service.search.bo.agg.AggBO; import lombok.Getter; import lombok.Setter; import java.io.Serial; import java.io.Serializable; import java.util.List; import java.util.Map;
835
package com.liyz.boot3.service.search.response; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/11/14 15:54 */ @Getter @Setter public class EsResponse<T> implements Serializable { @Serial private static final long serialVersionUID = 6830405460023653657L;
package com.liyz.boot3.service.search.response; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/11/14 15:54 */ @Getter @Setter public class EsResponse<T> implements Serializable { @Serial private static final long serialVersionUID = 6830405460023653657L;
private RemotePage<T> pageData;
0
2023-11-13 01:28:21+00:00
2k
RaniAgus/java-docker-tutorial
src/main/java/io/github/raniagus/example/controller/LoginController.java
[ { "identifier": "Params", "path": "src/main/java/io/github/raniagus/example/constants/Params.java", "snippet": "public abstract class Params {\n public static final String EMAIL = \"email\";\n public static final String PASSWORD = \"password\";\n public static final String ORIGIN = \"origin\";\n public static final String ERRORS = \"errors\";\n\n private Params() {}\n}" }, { "identifier": "Routes", "path": "src/main/java/io/github/raniagus/example/constants/Routes.java", "snippet": "public abstract class Routes {\n public static final String HOME = \"/\";\n public static final String LOGIN = \"/login\";\n public static final String LOGOUT = \"/logout\";\n\n private Routes() {}\n}" }, { "identifier": "Session", "path": "src/main/java/io/github/raniagus/example/constants/Session.java", "snippet": "public abstract class Session {\n public static final String USER = \"usuario\";\n\n private Session() {}\n}" }, { "identifier": "UserNotAuthorizedException", "path": "src/main/java/io/github/raniagus/example/exception/UserNotAuthorizedException.java", "snippet": "public class UserNotAuthorizedException extends RuntimeException {\n}" }, { "identifier": "ShouldLoginException", "path": "src/main/java/io/github/raniagus/example/exception/ShouldLoginException.java", "snippet": "public class ShouldLoginException extends RuntimeException {\n}" }, { "identifier": "HtmlUtil", "path": "src/main/java/io/github/raniagus/example/helpers/HtmlUtil.java", "snippet": "public enum HtmlUtil {;\n public static String joinParams(String path, String... pairs) {\n return path + \"?\" + String.join(\"&\", pairs);\n }\n\n public static <T extends CharSequence> String encode(String key, Iterable<T> values) {\n return encode(key, String.join(\",\", values));\n }\n\n public static String encode(String key, Object value) {\n return encode(key) + \"=\" + encode(value.toString());\n }\n\n public static String encode(String... strings) {\n return URLEncoder.encode(String.join(\"\", strings), StandardCharsets.UTF_8);\n }\n}" }, { "identifier": "Usuario", "path": "src/main/java/io/github/raniagus/example/model/Usuario.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class Usuario extends Persistible {\n private String nombre;\n private String apellido;\n private String email;\n @Embedded\n private Password password;\n @Enumerated(EnumType.STRING)\n private Rol rol;\n\n public Usuario(String nombre, String apellido, String email, String password, Rol rol) {\n this.nombre = nombre;\n this.apellido = apellido;\n this.email = email;\n this.password = new Password(password);\n this.rol = rol;\n }\n\n protected Usuario() {}\n\n public String getNombre() {\n return nombre;\n }\n\n public String getApellido() {\n return apellido;\n }\n\n public Password getPassword() {\n return password;\n }\n\n public Rol getRol() {\n return rol;\n }\n\n @Override\n public String toString() {\n return \"Usuario{id=%s, nombre=%s, apellido=%s, email=%s, rol=%s}\"\n .formatted(id, nombre, apellido, email, rol);\n }\n}" }, { "identifier": "RepositorioDeUsuarios", "path": "src/main/java/io/github/raniagus/example/repository/RepositorioDeUsuarios.java", "snippet": "public enum RepositorioDeUsuarios implements Repositorio<Usuario> {\n INSTANCE;\n\n public Optional<Usuario> buscarPorEmail(String email) {\n return entityManager()\n .createQuery(\"from Usuario where email = :email\", Usuario.class)\n .setParameter(\"email\", email)\n .getResultList().stream()\n .findAny();\n }\n\n @Override\n public Class<Usuario> getEntityClass() {\n return Usuario.class;\n }\n}" } ]
import io.github.raniagus.example.constants.Params; import io.github.raniagus.example.constants.Routes; import io.github.raniagus.example.constants.Session; import io.github.raniagus.example.exception.UserNotAuthorizedException; import io.github.raniagus.example.exception.ShouldLoginException; import io.github.raniagus.example.helpers.HtmlUtil; import io.github.raniagus.example.model.Usuario; import io.github.raniagus.example.repository.RepositorioDeUsuarios; import io.github.raniagus.example.views.LoginView; import io.javalin.http.Context; import io.javalin.validation.Validation; import io.javalin.validation.ValidationException; import java.util.Set;
1,342
package io.github.raniagus.example.controller; public enum LoginController { INSTANCE; public void handleSession(Context ctx) { if (ctx.routeRoles().isEmpty()) { return; } Usuario usuario = ctx.sessionAttribute(Session.USER); if (usuario == null) { throw new ShouldLoginException(); } else if (!ctx.routeRoles().contains(usuario.getRol())) { throw new UserNotAuthorizedException(); } } public void renderLogin(Context ctx) { var email = ctx.queryParamAsClass(Params.EMAIL, String.class).getOrDefault(""); var origin = ctx.queryParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME); var errors = ctx.queryParamAsClass(Params.ERRORS, String.class).getOrDefault(""); if (ctx.sessionAttribute(Session.USER) != null) { ctx.redirect(origin); return; } new LoginView(email, origin, errors.isEmpty() ? Set.of() : Set.of(errors.split(","))).render(ctx); } public void performLogin(Context ctx) { var email = ctx.formParamAsClass(Params.EMAIL, String.class) .check(s -> s.matches(".+@.+\\..+"), "INVALID_EMAIL"); var password = ctx.formParamAsClass(Params.PASSWORD, String.class) .check(s -> s.length() >= 8, "INVALID_PASSWORD"); var origin = ctx.formParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME); try { RepositorioDeUsuarios.INSTANCE.buscarPorEmail(email.get()) .filter(u -> u.getPassword().matches(password.get())) .ifPresentOrElse(usuario -> { ctx.sessionAttribute(Session.USER, usuario); ctx.redirect(origin); }, () ->
package io.github.raniagus.example.controller; public enum LoginController { INSTANCE; public void handleSession(Context ctx) { if (ctx.routeRoles().isEmpty()) { return; } Usuario usuario = ctx.sessionAttribute(Session.USER); if (usuario == null) { throw new ShouldLoginException(); } else if (!ctx.routeRoles().contains(usuario.getRol())) { throw new UserNotAuthorizedException(); } } public void renderLogin(Context ctx) { var email = ctx.queryParamAsClass(Params.EMAIL, String.class).getOrDefault(""); var origin = ctx.queryParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME); var errors = ctx.queryParamAsClass(Params.ERRORS, String.class).getOrDefault(""); if (ctx.sessionAttribute(Session.USER) != null) { ctx.redirect(origin); return; } new LoginView(email, origin, errors.isEmpty() ? Set.of() : Set.of(errors.split(","))).render(ctx); } public void performLogin(Context ctx) { var email = ctx.formParamAsClass(Params.EMAIL, String.class) .check(s -> s.matches(".+@.+\\..+"), "INVALID_EMAIL"); var password = ctx.formParamAsClass(Params.PASSWORD, String.class) .check(s -> s.length() >= 8, "INVALID_PASSWORD"); var origin = ctx.formParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME); try { RepositorioDeUsuarios.INSTANCE.buscarPorEmail(email.get()) .filter(u -> u.getPassword().matches(password.get())) .ifPresentOrElse(usuario -> { ctx.sessionAttribute(Session.USER, usuario); ctx.redirect(origin); }, () ->
ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,
5
2023-11-12 15:14:24+00:00
2k
heldermartins4/RPG_Pokemon
src/main/java/interfaces/start/Start.java
[ { "identifier": "Trainer", "path": "src/main/java/controllers/combat/Trainer.java", "snippet": "public class Trainer {\n \n private String nome;\n private int dinheiro;\n private Pokemon pokemon;\n private String character;\n\n public Trainer(String nome, String character) {\n this.nome = nome;\n this.dinheiro = 200;\n this.character = character;\n }\n\n public String getNome() {\n return this.nome;\n }\n\n public Pokemon getPokemon() {\n return this.pokemon;\n }\n\n public int getDinheiro() {\n return this.dinheiro;\n }\n\n public String getCharater() {\n return this.character;\n }\n\n public void setCharacter(String character) {\n this.character = character;\n }\n\n public void setNome(String nome) {\n this.nome = nome;\n }\n\n public void setPokemon(Pokemon pokemon) {\n this.pokemon = pokemon;\n } \n \n public void setDinheiro(int valor) {\n this.dinheiro += valor;\n }\n}" }, { "identifier": "GamePanel", "path": "src/main/java/interfaces/GamePanel.java", "snippet": "public class GamePanel extends JPanel implements Runnable {\n \n Map map = new Map(\"map_1\");\n public KeyHandler key = new KeyHandler();\n Player player;\n\n Start start_panel;\n\n Thread game_thread;\n\n\n int player_x = map.tile_size * 2;\n int player_y = map.tile_size * 2;\n int player_speed = 4;\n\n int fps = 60;\n private long last_update_time = System.nanoTime();\n\n public enum GameState {\n START_SCREEN,\n MAP_SCREEN,\n COMBAT_SCREEN\n }\n\n private GameState currentState;\n\n public GameState getCurrentState() {\n return currentState;\n }\n\n public void setCurrentState(GameState currentState) {\n this.currentState = currentState;\n }\n \n public GamePanel() {\n this.setPreferredSize(new Dimension(map.screen_width, map.screen_height));\n\n this.setDoubleBuffered(true);\n\n this.start_panel = new Start(this);\n\n currentState = GameState.START_SCREEN;\n\n start_panel.runStartSequence();\n \n // this.mapPanel = new Map(this, startPanel.getPlayer(), startPanel.getRival());\n\n this.map = new Map(\"map_1\");\n\n this.player = new Player(this, key);\n\n currentState = GameState.MAP_SCREEN;\n \n player.setDefaultValues(player_x, player_y, map.tile_size, map.tile_size, player_speed);\n player.setMapToPlayer(map);\n }\n\n public void startGameThread() {\n game_thread = new Thread(this);\n game_thread.start();\n }\n\n @Override\n public void run() {\n double delta = 0;\n double draw_interval = 1_000_000_000 / fps;\n\n while (game_thread != null) {\n long now = System.nanoTime();\n delta += (now - last_update_time) / draw_interval;\n last_update_time = now;\n\n while (delta >= 1) {\n update();\n delta--;\n }\n\n repaint();\n\n try {\n double remaining_time = (last_update_time - now + draw_interval) / 1_000_000_000;\n remaining_time = remaining_time < 0 ? 0 : remaining_time;\n\n Thread.sleep((long)remaining_time);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n\n public void update() {\n \n player.update();\n }\n\n public void paintComponent(Graphics g) {\n \n super.paintComponent(g);\n\n Graphics2D g2d = (Graphics2D) g;\n\n map.loadMap(g2d);\n \n player.draw(g2d);\n\n g2d.dispose();\n }\n\n public Start getStartPanel() {\n return this.start_panel;\n }\n}" } ]
import javax.swing.JOptionPane; import javax.swing.JPanel; import controllers.combat.Trainer; import interfaces.GamePanel;
1,018
package interfaces.start; public class Start extends JPanel { private GamePanel screen;
package interfaces.start; public class Start extends JPanel { private GamePanel screen;
private Trainer player;
0
2023-11-12 16:44:00+00:00
2k
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", "path": "src/main/java/com/kit/iotdb/common/utils/Rst.java", "snippet": "public class Rst extends LinkedHashMap<String, Object> implements Serializable {\n\n private static final long serialVersionUID = 1L; // 序列化版本号\n public static final int CODE_SUCCESS = 200;\n public static final int CODE_ERROR = 500;\n\n public Rst() {\n }\n\n public Rst(int code, String msg, Object data) {\n this.setCode(code);\n this.setMsg(msg);\n this.setData(data);\n }\n\n /**\n * 获取code\n *\n * @return code\n */\n public Integer getCode() {\n return (Integer) this.get(\"code\");\n }\n\n /**\n * 获取msg\n *\n * @return msg\n */\n public String getMsg() {\n return (String) this.get(\"msg\");\n }\n\n /**\n * 获取data\n *\n * @return data\n */\n public Object getData() {\n return (Object) this.get(\"data\");\n }\n\n /**\n * 给code赋值,连缀风格\n *\n * @param code code\n * @return 对象自身\n */\n public Rst setCode(int code) {\n this.put(\"code\", code);\n return this;\n }\n\n /**\n * 给msg赋值,连缀风格\n *\n * @param msg msg\n * @return 对象自身\n */\n public Rst setMsg(String msg) {\n this.put(\"msg\", msg);\n return this;\n }\n\n /**\n * 给data赋值,连缀风格\n *\n * @param data data\n * @return 对象自身\n */\n public Rst setData(Object data) {\n this.put(\"data\", data);\n return this;\n }\n\n // 构建成功\n public static Rst ok() {\n return new Rst(CODE_SUCCESS, \"ok\", null);\n }\n\n public static Rst ok(String msg) {\n return new Rst(CODE_SUCCESS, msg, null);\n }\n\n public static Rst code(int code) {\n return new Rst(code, null, null);\n }\n\n public static Rst data(Object data) {\n return new Rst(CODE_SUCCESS, \"ok\", data);\n }\n\n // 构建失败\n public static Rst error() {\n return new Rst(CODE_ERROR, \"error\", null);\n }\n\n public static Rst error(String msg) {\n return new Rst(CODE_ERROR, msg, null);\n }\n\n @Override\n public String toString() {\n return \"{\"\n + \"\\\"code\\\": \" + this.getCode()\n + \", \\\"msg\\\": \" + transValue(this.getMsg())\n + \", \\\"data\\\": \" + transValue(this.getData())\n + \"}\";\n }\n\n private String transValue(Object value) {\n if (value instanceof String) {\n return \"\\\"\" + value + \"\\\"\";\n }\n return String.valueOf(value);\n }\n}" }, { "identifier": "WeatherEntity", "path": "src/main/java/com/kit/iotdb/entity/WeatherEntity.java", "snippet": "@Data\n@Builder\npublic class WeatherEntity {\n /**\n * 固定对应Time字段\n */\n private long timestamp;\n\n /**\n * 采样时间时间戳\n */\n private long samplingTime;\n\n /**\n * 采样时间字符\n */\n private String samplingTimeStr;\n\n /**\n * 城市编码\n */\n private Integer cityKey;\n\n /**\n * 城市\n */\n private String city;\n\n /**\n * 温度 ℃\n */\n private float temperature;\n\n /**\n * 湿度 %\n */\n private float humidity;\n\n /**\n * pm10\n */\n private float pm10;\n\n /**\n * pm10\n */\n private float pm25;\n\n /**\n * 空气质量\n */\n private String quality;\n\n /**\n * 天气描述\n */\n private String remark;\n}" }, { "identifier": "WeatherService", "path": "src/main/java/com/kit/iotdb/service/WeatherService.java", "snippet": "public interface WeatherService {\n\n Integer addWeather(WeatherEntity weatherEntity);\n\n List<WeatherEntity> pageWeather(Integer page, Integer pageSize);\n\n Integer deleteWeather(String startTime, String endTime);\n}" } ]
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,514
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字段
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()
2
2023-11-15 06:04:04+00:00
2k
penyoofficial/HerbMS
src/main/java/com/penyo/herbms/controller/GenericController.java
[ { "identifier": "GenericBean", "path": "src/main/java/com/penyo/herbms/pojo/GenericBean.java", "snippet": "public abstract class GenericBean implements AbstractBean {\n @Override\n public String toString() {\n try {\n return new ObjectMapper().writeValueAsString(this);\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getId());\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) return true;\n if (!(obj instanceof GenericBean safeObj)) return false;\n return safeObj.getId() == this.getId();\n }\n}" }, { "identifier": "ReturnDataPack", "path": "src/main/java/com/penyo/herbms/pojo/ReturnDataPack.java", "snippet": "public class ReturnDataPack<T> extends GenericBean {\n /**\n * 影响行数\n */\n private int affectedRows = -114514;\n /**\n * 结果\n */\n private List<T> objs;\n\n public ReturnDataPack() {\n }\n\n public ReturnDataPack(List<T> objs) {\n this.objs = objs;\n }\n\n public ReturnDataPack(int affectedRows, List<T> objs) {\n this.affectedRows = affectedRows;\n this.objs = objs;\n }\n\n public int getAffectedRows() {\n return affectedRows;\n }\n\n public void setAffectedRows(int affectedRows) {\n this.affectedRows = affectedRows;\n }\n\n public List<T> getObjs() {\n return objs;\n }\n\n public void setObjs(List<T> objs) {\n this.objs = objs;\n }\n}" }, { "identifier": "GenericService", "path": "src/main/java/com/penyo/herbms/service/GenericService.java", "snippet": "public abstract class GenericService<UnknownBean extends GenericBean> implements AbstractService<UnknownBean> {\n @Autowired\n protected HerbDAO herbDAO;\n @Autowired\n protected ExperienceDAO experienceDAO;\n @Autowired\n protected PrescriptionInfoDAO prescriptionInfoDAO;\n @Autowired\n protected PrescriptionDAO prescriptionDAO;\n @Autowired\n protected ItemDifferentiationInfoDAO itemDifferentiationInfoDAO;\n @Autowired\n protected ItemDifferentiationDAO itemDifferentiationDAO;\n}" } ]
import com.penyo.herbms.pojo.GenericBean; import com.penyo.herbms.pojo.ReturnDataPack; import com.penyo.herbms.service.GenericService; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.springframework.web.bind.annotation.CrossOrigin;
712
package com.penyo.herbms.controller; /** * 通用控制器代理 * * @author Penyo * @see GenericBean * @see AbstractController */ @CrossOrigin("*") public abstract class GenericController<UnknownBean extends GenericBean> implements AbstractController<UnknownBean> { /** * 通用处理主要请求。 */
package com.penyo.herbms.controller; /** * 通用控制器代理 * * @author Penyo * @see GenericBean * @see AbstractController */ @CrossOrigin("*") public abstract class GenericController<UnknownBean extends GenericBean> implements AbstractController<UnknownBean> { /** * 通用处理主要请求。 */
public ReturnDataPack<UnknownBean> requestMain(Map<String, String> params, GenericService<UnknownBean> serv) {
1
2023-11-13 16:40:05+00:00
2k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/system/rest/DictController.java
[ { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) {\n super(msg);\n }\n\n public BadRequestException(HttpStatus status, String msg) {\n super(msg);\n this.status = status.value();\n }\n}" }, { "identifier": "Dict", "path": "dimple-system/src/main/java/com/dimple/modules/system/domain/Dict.java", "snippet": "@Entity\n@Getter\n@Setter\n@Table(name = \"sys_dict\")\npublic class Dict extends BaseEntity implements Serializable {\n\n @Id\n @Column(name = \"dict_id\")\n @NotNull(groups = Update.class)\n @ApiModelProperty(value = \"ID\", hidden = true)\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @OneToMany(mappedBy = \"dict\", cascade = {CascadeType.PERSIST, CascadeType.REMOVE})\n private List<DictDetail> dictDetails;\n\n @NotBlank\n @ApiModelProperty(value = \"名称\")\n private String name;\n\n @ApiModelProperty(value = \"描述\")\n private String description;\n}" }, { "identifier": "DictService", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/DictService.java", "snippet": "public interface DictService {\n\n /**\n * 分页查询\n *\n * @param criteria 条件\n * @param pageable 分页参数\n * @return /\n */\n Map<String, Object> queryAll(DictQueryCriteria criteria, Pageable pageable);\n\n /**\n * 查询全部数据\n *\n * @param dict /\n * @return /\n */\n List<DictDTO> queryAll(DictQueryCriteria dict);\n\n /**\n * 创建\n *\n * @param resources /\n * @return /\n */\n void create(Dict resources);\n\n /**\n * 编辑\n *\n * @param resources /\n */\n void update(Dict resources);\n\n /**\n * 删除\n *\n * @param ids /\n */\n void delete(Set<Long> ids);\n\n /**\n * 导出数据\n *\n * @param queryAll 待导出的数据\n * @param response /\n * @throws IOException /\n */\n void download(List<DictDTO> queryAll, HttpServletResponse response) throws IOException;\n}" }, { "identifier": "DictQueryCriteria", "path": "dimple-system/src/main/java/com/dimple/modules/system/service/dto/DictQueryCriteria.java", "snippet": "@Data\npublic class DictQueryCriteria {\n\n @Query(blurry = \"name,description\")\n private String blurry;\n}" } ]
import com.dimple.annotation.OLog; import com.dimple.exception.BadRequestException; import com.dimple.modules.system.domain.Dict; import com.dimple.modules.system.service.DictService; import com.dimple.modules.system.service.dto.DictQueryCriteria; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; 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.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Set;
909
package com.dimple.modules.system.rest; /** * @className: DictController * @description: * @author: Dimple * @date: 06/17/20 */ @RestController @RequiredArgsConstructor @Api(tags = "系统:字典管理") @RequestMapping("/api/dict") public class DictController { private static final String ENTITY_NAME = "dict";
package com.dimple.modules.system.rest; /** * @className: DictController * @description: * @author: Dimple * @date: 06/17/20 */ @RestController @RequiredArgsConstructor @Api(tags = "系统:字典管理") @RequestMapping("/api/dict") public class DictController { private static final String ENTITY_NAME = "dict";
private final DictService dictService;
2
2023-11-10 03:30:36+00:00
2k
LazyCoder0101/LazyCoder
service/src/main/java/com/lazycoder/service/vo/element/lable/CorrespondingAdditionalDefaultFileElement.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 final String CONTENT_CHOOSE = \"contentChoose\";\n\n\t/**\n\t * 功能拓展 m !\n\t */\n\tpublic static final String FUNCTION_ADD = \"functionAdd\";\n\n\t/**\n\t * 自定义变量 x\n\t */\n\tpublic static final String CUSTOM_VARIABLE = \"customVariable\";\n\n\t/**\n\t * 变量 v\n\t */\n\tpublic static final String VARIABLE = \"variable\";\n\n\t/**\n\t * 常量 s !\n\t */\n\tpublic static final String CONSTANT = \"constant\";\n\n\t/**\n\t * 文件 f !\n\t */\n\tpublic static final String FILE_SELECTOR = \"fileSelector\";\n\n\t/**\n\t * 注释 n (控制面板才有)!\n\t */\n\tpublic static final String NOTE = \"note\";\n\n\t/**\n\t * 图片 p(控制面板才有) !\n\t */\n\tpublic static final String PICTURE = \"picture\";\n\n\t/**\n\t * 代码输入 i !\n\t */\n\tpublic static final String CODE_INPUT = \"codeInput\";\n\n\t/**\n\t * 不常用设置 u !(控制面板才可能有)\n\t */\n\tpublic static final String INFREQUENTLY_USED_SETTING = \"infrequentlyUsedSetting\";\n\n\t/**\n\t * 方法名 d\n\t */\n\tpublic static final String CUSTOM_METHOD_NAME = \"customMethodName\";\n\n\t/**\n\t * 方法选择 y\n\t */\n\tpublic static final String METHOD_CHOOSE = \"methodChoose\";\n\n\t/**\n\t * 自己文件名(只有代码模板才有)\n\t */\n\tpublic static final String THIS_FILE_NAME = \"thisFileName\";\n\n\t/**\n\t * 对应的可选模板所添加的格式文件\n\t */\n\tpublic static final String CORRESPONDING_ADDITIONAL_DEFAULT_FILE = \"correspondingAdditionalDefaultFile\";\n\n}" }, { "identifier": "BaseModel", "path": "database/src/main/java/com/lazycoder/database/model/BaseModel.java", "snippet": "public interface BaseModel {\n\n\tpublic static final int TRUE_ = 1;\n\n\tpublic static final int FALSE_ = 0;\n\n}" } ]
import com.lazycoder.database.common.LabelElementName; import com.lazycoder.database.model.BaseModel; import lombok.Data;
730
package com.lazycoder.service.vo.element.lable; /** * 对应添加的可选模板格式的默认文件名 * * @author Administrator */ @Data public class CorrespondingAdditionalDefaultFileElement extends BaseLableElement implements BaseModel { public CorrespondingAdditionalDefaultFileElement() { // TODO Auto-generated constructor stub super();
package com.lazycoder.service.vo.element.lable; /** * 对应添加的可选模板格式的默认文件名 * * @author Administrator */ @Data public class CorrespondingAdditionalDefaultFileElement extends BaseLableElement implements BaseModel { public CorrespondingAdditionalDefaultFileElement() { // TODO Auto-generated constructor stub super();
this.setLabelType(LabelElementName.CORRESPONDING_ADDITIONAL_DEFAULT_FILE);
0
2023-11-16 11:55:06+00:00
2k
hardingadonis/miu-shop
src/main/java/io/hardingadonis/miu/controller/admin/OrderAdmin.java
[ { "identifier": "OrderStatus", "path": "src/main/java/io/hardingadonis/miu/model/detail/OrderStatus.java", "snippet": "public enum OrderStatus {\n PROCESSING(\"processing\"),\n SHIPPING(\"shipping\"),\n DONE(\"done\"),\n CANCELED(\"canceled\");\n\n private final String label;\n\n private OrderStatus(String label) {\n this.label = label;\n }\n\n public static OrderStatus create(String status) {\n switch (status) {\n case \"processing\":\n return PROCESSING;\n case \"shipping\":\n return SHIPPING;\n case \"done\":\n return DONE;\n case \"canceled\":\n default:\n return CANCELED;\n }\n }\n\n @Override\n public String toString() {\n return label;\n }\n}" }, { "identifier": "Singleton", "path": "src/main/java/io/hardingadonis/miu/services/Singleton.java", "snippet": "public class Singleton {\n\n public static DBContext dbContext;\n\n public static Email email;\n \n public static AdminDAO adminDAO;\n \n public static CategoryDAO categoryDAO;\n \n public static OrderDAO orderDAO;\n \n public static OrderDataDAO orderDataDAO;\n \n public static ProductDAO productDAO;\n \n public static UserDAO userDAO;\n\n static {\n dbContext = new DBContextMySQLImpl();\n\n email = new EmailGmailImpl();\n \n adminDAO = new AdminDAOMySQLImpl();\n \n categoryDAO = new CategoryDAOMySQLImpl();\n \n orderDAO = new OrderDAOMySQLImpl();\n \n orderDataDAO = new OrderDataDAOMySQLImpl();\n \n productDAO = new ProductDAOMySQLImpl();\n \n userDAO = new UserDAOMySQLImpl();\n }\n}" } ]
import io.hardingadonis.miu.model.*; import io.hardingadonis.miu.model.detail.OrderStatus; import io.hardingadonis.miu.services.Singleton; import java.io.IOException; import javax.servlet.*; import javax.servlet.annotation.*; import javax.servlet.http.*; import org.json.simple.JSONObject;
674
package io.hardingadonis.miu.controller.admin; @WebServlet(name = "OrderAdmin", urlPatterns = {"/admin/order"}) public class OrderAdmin extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); HttpSession session = request.getSession(); Admin admin = (Admin) session.getAttribute("admin"); if (admin == null) { response.sendRedirect(request.getContextPath() + "/admin/login"); return; } request.getRequestDispatcher("/view/admin/order-admin.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");
package io.hardingadonis.miu.controller.admin; @WebServlet(name = "OrderAdmin", urlPatterns = {"/admin/order"}) public class OrderAdmin extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); HttpSession session = request.getSession(); Admin admin = (Admin) session.getAttribute("admin"); if (admin == null) { response.sendRedirect(request.getContextPath() + "/admin/login"); return; } request.getRequestDispatcher("/view/admin/order-admin.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");
OrderStatus orderStatus = OrderStatus.create(request.getParameter("status"));
0
2023-11-16 07:15:44+00:00
2k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/device/CurtainTest.java
[ { "identifier": "PROP_CUR_OPEN_ANGLE", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Integer.class)\npublic static final String PROP_CUR_OPEN_ANGLE = PROP_PREFIX + \"open_angle.cur\";" }, { "identifier": "PROP_CUR_OPEN_LEVEL", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Integer.class)\npublic static final String PROP_CUR_OPEN_LEVEL = PROP_PREFIX + \"open_level.cur\";" }, { "identifier": "PROP_MAX_OPEN_ANGLE", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Integer.class, defValueI=10)\npublic static final String PROP_MAX_OPEN_ANGLE = PROP_PREFIX + \"open_angle.max\";" }, { "identifier": "PROP_MAX_OPEN_LEVEL", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Integer.class, defValueI=10)\npublic static final String PROP_MAX_OPEN_LEVEL = PROP_PREFIX + \"open_level.max\";" }, { "identifier": "PROP_MIN_OPEN_ANGLE", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Integer.class)\npublic static final String PROP_MIN_OPEN_ANGLE = PROP_PREFIX + \"open_angle.min\";" }, { "identifier": "PROP_MIN_OPEN_LEVEL", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Integer.class)\npublic static final String PROP_MIN_OPEN_LEVEL = PROP_PREFIX + \"open_level.min\";" }, { "identifier": "PROP_OPERATION", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Operation.class)\npublic static final String PROP_OPERATION = PROP_PREFIX + \"requested_operation\";" }, { "identifier": "PROP_STATE", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=OpState.class)\npublic static final String PROP_STATE = PROP_PREFIX + \"operation.state\";" }, { "identifier": "PROP_SUPPORTS", "path": "app/src/main/java/kr/or/kashi/hde/device/Curtain.java", "snippet": "@PropertyDef(valueClass=Support.class)\npublic static final String PROP_SUPPORTS = PROP_PREFIX + \"supports\";" }, { "identifier": "DeviceTestCase", "path": "app/src/main/java/kr/or/kashi/hde/test/DeviceTestCase.java", "snippet": "public class DeviceTestCase<T> extends TestCase implements HomeDevice.Callback {\n private HomeDevice mDevice;\n private boolean mWaitForCallback;\n\n public void setDevice(HomeDevice device) {\n mDevice = device;\n }\n\n public HomeDevice device() {\n return mDevice;\n }\n\n @Override\n protected void setUp() throws Exception {\n super.setUp();\n mDevice.addCallback(this);\n }\n\n @Override\n protected void tearDown() throws Exception {\n super.tearDown();\n mDevice.removeCallback(this);\n }\n\n @Override\n public void onPropertyChanged(HomeDevice device, PropertyMap props) {\n synchronized (mDevice) {\n mWaitForCallback = false;\n mDevice.notifyAll();\n }\n }\n\n @Override\n public void onErrorOccurred(HomeDevice device, @HomeDevice.Error int error) {\n synchronized (mDevice) {\n mDevice.notifyAll();\n }\n }\n\n public void assertSupported(String propName, int supportMask) throws Exception {\n final long supports = mDevice.getProperty(propName, Integer.class);\n if ((supports & supportMask) != supportMask) {\n throw new UnsupportedOperationException();\n }\n }\n\n public void assertSupported(String propName, long supportMask) throws Exception {\n final long supports = mDevice.getProperty(propName, Long.class);\n if ((supports & supportMask) != supportMask) {\n throw new UnsupportedOperationException();\n }\n }\n\n public <E> void assertEquals(String propName, Class<E> valueClass, E expectedValue) throws Exception {\n final E value = mDevice.getProperty(propName, valueClass);\n assertEquals(value, expectedValue);\n }\n\n public <E> void assertMasked(String propName, Class<E> valueClass, E maskedValue) throws Exception {\n final E value = mDevice.getProperty(propName, valueClass);\n assertEquals(value, ((long)value & (long)maskedValue) == (long)maskedValue);\n }\n\n public <E> void assertPropertyChanaged(String propName, Class<E> valueClass, E fromValue, E toValue) throws Exception {\n mDevice.setProperty(propName, valueClass, fromValue);\n wait_();\n mDevice.setProperty(propName, valueClass, toValue);\n waitForPropertyChanged();\n assertEquals(toValue, mDevice.getProperty(propName, valueClass));\n }\n\n protected void waitForPropertyChanged() throws Exception {\n mWaitForCallback = true;\n wait_();\n if (mWaitForCallback) {\n throw new Exception();\n }\n }\n\n private void wait_() throws Exception {\n synchronized (mDevice) {\n mDevice.wait(2000);\n }\n }\n\n protected void waitFor(long timeout) throws Exception {\n synchronized (mDevice) {\n mDevice.wait(timeout);\n }\n }\n\n public void test_OnOff() throws Exception {\n assertPropertyChanaged(HomeDevice.PROP_ONOFF, Boolean.class, false, true);\n }\n}" } ]
import static kr.or.kashi.hde.device.Curtain.PROP_CUR_OPEN_ANGLE; import static kr.or.kashi.hde.device.Curtain.PROP_CUR_OPEN_LEVEL; import static kr.or.kashi.hde.device.Curtain.PROP_MAX_OPEN_ANGLE; import static kr.or.kashi.hde.device.Curtain.PROP_MAX_OPEN_LEVEL; import static kr.or.kashi.hde.device.Curtain.PROP_MIN_OPEN_ANGLE; import static kr.or.kashi.hde.device.Curtain.PROP_MIN_OPEN_LEVEL; import static kr.or.kashi.hde.device.Curtain.PROP_OPERATION; import static kr.or.kashi.hde.device.Curtain.PROP_STATE; import static kr.or.kashi.hde.device.Curtain.PROP_SUPPORTS; import kr.or.kashi.hde.test.DeviceTestCase;
1,562
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.device; public class CurtainTest extends DeviceTestCase { public void test_StateCheck() throws Exception { assertSupported(PROP_SUPPORTS, Curtain.Support.STATE);
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.device; public class CurtainTest extends DeviceTestCase { public void test_StateCheck() throws Exception { assertSupported(PROP_SUPPORTS, Curtain.Support.STATE);
device().setProperty(PROP_OPERATION, Integer.class, Curtain.Operation.STOP);
6
2023-11-10 01:19:44+00:00
2k
zizai-Shen/young-im
young-im-gateway/src/main/java/cn/young/im/gateway/repository/ConfigServerRouteDefinitionRepository.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 YoungImException(final Throwable e) {\n super(e);\n }\n}" }, { "identifier": "RouteProperties", "path": "young-im-gateway/src/main/java/cn/young/im/gateway/config/RouteProperties.java", "snippet": "@Data\n@Component\n@ConfigServerConfigurationProperties\n (configKey = \"router\", groupId = \"young_im\", type = ConfigType.JSON,\n callbackClazz = DynamicRouteService.class)\npublic class RouteProperties {\n private List<RouteDefinition> route;\n}" }, { "identifier": "ConfigServerRepository", "path": "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/repository/ConfigServerRepository.java", "snippet": "public interface ConfigServerRepository {\n\n String getConfig(String configKey, String groupId);\n\n\n ConfigService getConfigService();\n}" } ]
import cn.young.im.common.exception.YoungImException; import cn.young.im.gateway.config.RouteProperties; import cn.young.im.springboot.starter.adapter.config.repository.ConfigServerRepository; import com.alibaba.fastjson2.JSON; import org.springframework.cloud.gateway.route.RouteDefinition; import org.springframework.cloud.gateway.route.RouteDefinitionRepository; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.util.LinkedHashMap; import java.util.Map; import static java.util.Collections.synchronizedMap;
757
package cn.young.im.gateway.repository; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description 内部路由定义初始化 * @date 2023/12/4 */ @Component public class ConfigServerRouteDefinitionRepository implements RouteDefinitionRepository { /** * 路由库 */ public static final Map<String, RouteDefinition> routes = synchronizedMap(new LinkedHashMap<>()); // /** // * 配置仓储 // */ // @Resource // private ConfigServerRepository configServerRepository; // /** // * 初始化路由 // */ // @PostConstruct // public void initRoutes() { // String configJson = configServerRepository.getConfig("router", "young_im"); // RouteProperties routeProperties = JSON.parseObject(configJson, RouteProperties.class); // for (RouteDefinition route : routeProperties.getRoute()) { // routes.put(route.getId(), route); // } // } /** * 获取路由 */ @Override public Flux<RouteDefinition> getRouteDefinitions() { return Flux.fromIterable(routes.values()); } /** * 保存路由 */ @Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(r -> { routes.put(r.getId(), r); return Mono.empty(); }); } /** * 删除路由 */ @Override public Mono<Void> delete(Mono<String> routeId) { return routeId.flatMap(id -> { if (routes.containsKey(id)) { routes.remove(id); return Mono.empty(); }
package cn.young.im.gateway.repository; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description 内部路由定义初始化 * @date 2023/12/4 */ @Component public class ConfigServerRouteDefinitionRepository implements RouteDefinitionRepository { /** * 路由库 */ public static final Map<String, RouteDefinition> routes = synchronizedMap(new LinkedHashMap<>()); // /** // * 配置仓储 // */ // @Resource // private ConfigServerRepository configServerRepository; // /** // * 初始化路由 // */ // @PostConstruct // public void initRoutes() { // String configJson = configServerRepository.getConfig("router", "young_im"); // RouteProperties routeProperties = JSON.parseObject(configJson, RouteProperties.class); // for (RouteDefinition route : routeProperties.getRoute()) { // routes.put(route.getId(), route); // } // } /** * 获取路由 */ @Override public Flux<RouteDefinition> getRouteDefinitions() { return Flux.fromIterable(routes.values()); } /** * 保存路由 */ @Override public Mono<Void> save(Mono<RouteDefinition> route) { return route.flatMap(r -> { routes.put(r.getId(), r); return Mono.empty(); }); } /** * 删除路由 */ @Override public Mono<Void> delete(Mono<String> routeId) { return routeId.flatMap(id -> { if (routes.containsKey(id)) { routes.remove(id); return Mono.empty(); }
return Mono.defer(() -> Mono.error(new YoungImException("RouteDefinition not found: " + routeId)));
0
2023-11-10 06:21:17+00:00
2k
Ouest-France/querydsl
src/main/java/fr/ouestfrance/querydsl/service/scanner/FilterFieldAnnotationScanner.java
[ { "identifier": "Filter", "path": "src/main/java/fr/ouestfrance/querydsl/model/Filter.java", "snippet": "public interface Filter {\n}" }, { "identifier": "FilterFieldConstraintException", "path": "src/main/java/fr/ouestfrance/querydsl/service/validators/FilterFieldConstraintException.java", "snippet": "@Getter\npublic class FilterFieldConstraintException extends RuntimeException {\n\n /**\n * List of violations\n */\n private final transient List<FilterFieldViolation> violations;\n /**\n * Class of the bean scanned\n */\n private final Class<?> clazz;\n\n /**\n * Constructor\n * @param clazz clazz of bean scanned\n * @param violations list of violations\n */\n public FilterFieldConstraintException(Class<?> clazz, List<FilterFieldViolation> violations) {\n super(\"Class \" + clazz + \" can't be validated cause violations : \" + String.join(\",\", violations.stream().map(FilterFieldViolation::toString).toList()));\n this.violations = violations;\n this.clazz = clazz;\n }\n}" }, { "identifier": "FilterFieldValidatorService", "path": "src/main/java/fr/ouestfrance/querydsl/service/validators/FilterFieldValidatorService.java", "snippet": "public class FilterFieldValidatorService {\n\n /**\n * Map of validators\n */\n private static final Map<Class<? extends FilterFieldValidator>, FilterFieldValidator> VALIDATOR_MAP = new HashMap<>();\n\n /**\n * Check each filter and build a filter of violations\n *\n * @param filter filter to check\n * @return empty filter if everything is ok, otherwise it returns filter of {@link FilterFieldViolation}\n */\n public Optional<FilterFieldViolation> validate(SimpleFilter filter) {\n FilterFieldValidator validator = getValidator(filter.operation());\n if (validator.validate(filter.field().getType())) {\n return Optional.empty();\n } else {\n return Optional.of(new FilterFieldViolation(filter.field().getName(), \"Operation \" + filter.operation() + \" \" + validator.message()));\n }\n }\n\n /**\n * Retrieve the validator from the operation\n *\n * @param operation operation in the FilterField annotation\n * @return Validator for this field\n */\n private FilterFieldValidator getValidator(Class<? extends FilterOperation> operation) {\n ValidatedBy validator = operation.getAnnotation(ValidatedBy.class);\n if (validator == null) {\n throw new IllegalStateException(\"Operation \" + operation + \" should be annotated with @ValidatedBy\");\n }\n return VALIDATOR_MAP.computeIfAbsent(validator.value(), x -> {\n try {\n return x.getConstructor().newInstance();\n } catch (InstantiationException | IllegalAccessException | NoSuchMethodException |\n InvocationTargetException e) {\n throw new IllegalStateException(\"Validator \" + x + \" should have a default constructor\", e);\n }\n });\n }\n}" } ]
import fr.ouestfrance.querydsl.FilterField; import fr.ouestfrance.querydsl.FilterFields; import fr.ouestfrance.querydsl.model.Filter; import fr.ouestfrance.querydsl.model.GroupFilter; import fr.ouestfrance.querydsl.model.SimpleFilter; import fr.ouestfrance.querydsl.service.validators.FilterFieldConstraintException; import fr.ouestfrance.querydsl.service.validators.FilterFieldValidatorService; import fr.ouestfrance.querydsl.service.validators.FilterFieldViolation; import java.lang.reflect.Field; import java.util.*;
1,354
package fr.ouestfrance.querydsl.service.scanner; /** * Class that allow to scan a clazz and return object representation of FilterFieldModel * This class also validate using {@link FilterFieldValidatorService} that the annotations operations are supported * by the {@link java.lang.reflect.Type} of the field */ public class FilterFieldAnnotationScanner { private final FilterFieldValidatorService validatorService = new FilterFieldValidatorService(); /** * Check if field present annotations like FilterField or FilterFields * * @return <code>true</code> if one of the annotations is present, otherwise <code>false</code> */ private boolean hasFilterFieldAnnotation(Field field) { return field.isAnnotationPresent(FilterField.class) || field.isAnnotationPresent(FilterFields.class); } /** * Scan a specific clazz * * @param clazz class to scan * @return List of FilterFieldModel * @throws FilterFieldConstraintException raise an exception if field annotation is not supported by field type or if clazz don't provide getter function for the type */ public List<Filter> scan(Class<?> clazz) { GroupFilter rootGroup = new GroupFilter("$root#", new ArrayList<>(), GroupFilter.Operand.AND); List<FilterFieldViolation> violations = new ArrayList<>(); Arrays.stream(clazz.getDeclaredFields()) .filter(this::hasFilterFieldAnnotation) .forEach( field -> { FilterFields filterFields = field.getAnnotation(FilterFields.class); List<FilterField> groupFilters = new ArrayList<>(); if (filterFields!= null && !filterFields.groupName().isEmpty()) { groupFilters.addAll(Arrays.stream(filterFields.value()).toList()); GroupFilter filterAndGroup = new GroupFilter(UUID.randomUUID().toString(), new ArrayList<>(), GroupFilter.Operand.AND); Arrays.stream(filterFields.value()) .forEach(filterField -> { SimpleFilter filter = new SimpleFilter(firstNotEmpty(filterField.key(), field.getName()), filterField.operation(), filterField.orNull(), field); validatorService.validate(filter).ifPresent(violations::add); filterAndGroup.filters().add(filter); }); appendToGroup(rootGroup, filterFields.groupName(), filterAndGroup); } // On filterField Arrays.stream(field.getAnnotationsByType(FilterField.class)) .filter(x-> !groupFilters.contains(x)) .forEach( filterField -> { SimpleFilter filter = new SimpleFilter(firstNotEmpty(filterField.key(), field.getName()), filterField.operation(), filterField.orNull(), field); validatorService.validate(filter).ifPresent(violations::add); appendToGroup(rootGroup, filterField.groupName(), filter); } ); } ); // Check for violations if (!violations.isEmpty()) {
package fr.ouestfrance.querydsl.service.scanner; /** * Class that allow to scan a clazz and return object representation of FilterFieldModel * This class also validate using {@link FilterFieldValidatorService} that the annotations operations are supported * by the {@link java.lang.reflect.Type} of the field */ public class FilterFieldAnnotationScanner { private final FilterFieldValidatorService validatorService = new FilterFieldValidatorService(); /** * Check if field present annotations like FilterField or FilterFields * * @return <code>true</code> if one of the annotations is present, otherwise <code>false</code> */ private boolean hasFilterFieldAnnotation(Field field) { return field.isAnnotationPresent(FilterField.class) || field.isAnnotationPresent(FilterFields.class); } /** * Scan a specific clazz * * @param clazz class to scan * @return List of FilterFieldModel * @throws FilterFieldConstraintException raise an exception if field annotation is not supported by field type or if clazz don't provide getter function for the type */ public List<Filter> scan(Class<?> clazz) { GroupFilter rootGroup = new GroupFilter("$root#", new ArrayList<>(), GroupFilter.Operand.AND); List<FilterFieldViolation> violations = new ArrayList<>(); Arrays.stream(clazz.getDeclaredFields()) .filter(this::hasFilterFieldAnnotation) .forEach( field -> { FilterFields filterFields = field.getAnnotation(FilterFields.class); List<FilterField> groupFilters = new ArrayList<>(); if (filterFields!= null && !filterFields.groupName().isEmpty()) { groupFilters.addAll(Arrays.stream(filterFields.value()).toList()); GroupFilter filterAndGroup = new GroupFilter(UUID.randomUUID().toString(), new ArrayList<>(), GroupFilter.Operand.AND); Arrays.stream(filterFields.value()) .forEach(filterField -> { SimpleFilter filter = new SimpleFilter(firstNotEmpty(filterField.key(), field.getName()), filterField.operation(), filterField.orNull(), field); validatorService.validate(filter).ifPresent(violations::add); filterAndGroup.filters().add(filter); }); appendToGroup(rootGroup, filterFields.groupName(), filterAndGroup); } // On filterField Arrays.stream(field.getAnnotationsByType(FilterField.class)) .filter(x-> !groupFilters.contains(x)) .forEach( filterField -> { SimpleFilter filter = new SimpleFilter(firstNotEmpty(filterField.key(), field.getName()), filterField.operation(), filterField.orNull(), field); validatorService.validate(filter).ifPresent(violations::add); appendToGroup(rootGroup, filterField.groupName(), filter); } ); } ); // Check for violations if (!violations.isEmpty()) {
throw new FilterFieldConstraintException(clazz, violations);
1
2023-11-14 10:50:02+00:00
2k
backend-source/ecommerce-microservice-architecture
proxy-client/src/main/java/com/hoangtien2k3/proxyclient/business/orderItem/service/OrderItemClientService.java
[ { "identifier": "OrderItemDto", "path": "proxy-client/src/main/java/com/hoangtien2k3/proxyclient/business/orderItem/model/OrderItemDto.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class OrderItemDto implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer productId;\n private Integer orderId;\n private Integer orderedQuantity;\n\n @JsonProperty(\"product\")\n @JsonInclude(Include.NON_NULL)\n private ProductDto productDto;\n\n @JsonProperty(\"order\")\n @JsonInclude(Include.NON_NULL)\n private OrderDto orderDto;\n\n}" }, { "identifier": "OrderItemId", "path": "proxy-client/src/main/java/com/hoangtien2k3/proxyclient/business/orderItem/model/OrderItemId.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\npublic class OrderItemId implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer productId;\n private Integer orderId;\n\n}" }, { "identifier": "OrderItemOrderItemServiceDtoCollectionResponse", "path": "proxy-client/src/main/java/com/hoangtien2k3/proxyclient/business/orderItem/model/response/OrderItemOrderItemServiceDtoCollectionResponse.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class OrderItemOrderItemServiceDtoCollectionResponse implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Collection<OrderItemDto> collection;\n\n}" } ]
import javax.validation.Valid; import javax.validation.constraints.NotNull; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; 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 com.hoangtien2k3.proxyclient.business.orderItem.model.OrderItemDto; import com.hoangtien2k3.proxyclient.business.orderItem.model.OrderItemId; import com.hoangtien2k3.proxyclient.business.orderItem.model.response.OrderItemOrderItemServiceDtoCollectionResponse;
661
package com.hoangtien2k3.proxyclient.business.orderItem.service; @FeignClient(name = "SHIPPING-SERVICE", contextId = "shippingClientService", path = "/shipping-service/api/shippings" ) @Service public interface OrderItemClientService { @GetMapping ResponseEntity<OrderItemOrderItemServiceDtoCollectionResponse> findAll(); @GetMapping("/{orderId}/{productId}") ResponseEntity<OrderItemDto> findById(@PathVariable("orderId") final String orderId, @PathVariable("productId") final String productId); @GetMapping("/find") ResponseEntity<OrderItemDto> findById(@RequestBody @NotNull(message = "Input must not be NULL")
package com.hoangtien2k3.proxyclient.business.orderItem.service; @FeignClient(name = "SHIPPING-SERVICE", contextId = "shippingClientService", path = "/shipping-service/api/shippings" ) @Service public interface OrderItemClientService { @GetMapping ResponseEntity<OrderItemOrderItemServiceDtoCollectionResponse> findAll(); @GetMapping("/{orderId}/{productId}") ResponseEntity<OrderItemDto> findById(@PathVariable("orderId") final String orderId, @PathVariable("productId") final String productId); @GetMapping("/find") ResponseEntity<OrderItemDto> findById(@RequestBody @NotNull(message = "Input must not be NULL")
@Valid final OrderItemId orderItemId);
1
2023-11-13 04:24:52+00:00
2k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/enchants/impl/Power.java
[ { "identifier": "Enchantment", "path": "src/main/java/com/sweattypalms/skyblock/core/enchants/builder/Enchantment.java", "snippet": "@Getter\npublic abstract class Enchantment {\n private final String id;\n private final int maxLevel;\n\n /**\n * Create a new enchantment\n * Defaults to max level 5\n * @param id The id of the enchantment\n */\n public Enchantment(String id) {\n this.id = id;\n this.maxLevel = 5;\n }\n\n /**\n * Create a new enchantment\n * @param id The id of the enchantment\n * @param maxLevel The max level of the enchantment\n */\n public Enchantment(String id, int maxLevel) {\n this.id = id;\n this.maxLevel = maxLevel;\n }\n\n /**\n * Get the name of the enchantment\n * @return The name of the enchantment\n */\n public abstract String getName();\n\n /**\n * Get the description of the enchantment\n * @param level The level of the enchantment\n * @return The description of the enchantment\n */\n public abstract List<String> getDescription(int level);\n\n /**\n * Get the list of item types that the enchantment can be applied to\n * @return The applicable item types for the enchantment\n */\n public abstract List<SkyblockItemType> getApplicableItems();\n\n public static int getLevel(ItemStack itemStack, Enchantment enchantment) {\n Optional<Integer> level = EnchantManager.getEnchantment(itemStack, enchantment.getId());\n return level.orElse(0);\n }\n}" }, { "identifier": "ITriggerableEnchant", "path": "src/main/java/com/sweattypalms/skyblock/core/enchants/builder/ITriggerableEnchant.java", "snippet": "public interface ITriggerableEnchant {\n boolean should(Event event);\n void execute(int level, Event event);\n}" }, { "identifier": "SkyblockItemType", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/SkyblockItemType.java", "snippet": "@Getter\npublic enum SkyblockItemType {\n SWORD,\n BOW,\n HELMET(EquipmentSlot.HEAD),\n CHESTPLATE(EquipmentSlot.CHEST),\n LEGGINGS(EquipmentSlot.LEGS),\n BOOTS(EquipmentSlot.FEET),\n ACCESSORY(null),\n WAND,\n PICKAXE,\n DRILL,\n AXE,\n NONE(null);\n\n @Nullable\n private final EquipmentSlot slot;\n SkyblockItemType(@Nullable EquipmentSlot slot) {\n this.slot = slot;\n }\n SkyblockItemType() {\n this.slot = EquipmentSlot.HAND;\n }\n\n public static List<SkyblockItemType> getHandheld() {\n return Arrays.stream(SkyblockItemType.values()).filter(type -> type.getSlot() == EquipmentSlot.HAND).toList();\n }\n\n public static List<SkyblockItemType> getArmor() {\n return Arrays.stream(SkyblockItemType.values()).filter(type -> type.getSlot() != EquipmentSlot.HAND && type.getSlot() != null).toList();\n }\n}" } ]
import com.sweattypalms.skyblock.core.enchants.builder.Enchantment; import com.sweattypalms.skyblock.core.enchants.builder.ITriggerableEnchant; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import org.bukkit.event.Event; import java.util.List;
933
package com.sweattypalms.skyblock.core.enchants.impl; public class Power extends Enchantment implements ITriggerableEnchant { public Power() { super("power", 7); } @Override public String getName() { return "Power"; } @Override public List<String> getDescription(int level) { return List.of( "Increases bow damage by $a" + getMultiplier(level) + "%$7." ); } @Override
package com.sweattypalms.skyblock.core.enchants.impl; public class Power extends Enchantment implements ITriggerableEnchant { public Power() { super("power", 7); } @Override public String getName() { return "Power"; } @Override public List<String> getDescription(int level) { return List.of( "Increases bow damage by $a" + getMultiplier(level) + "%$7." ); } @Override
public List<SkyblockItemType> getApplicableItems() {
2
2023-11-15 15:05:58+00:00
2k
microsphere-projects/microsphere-i18n
microsphere-i18n-core/src/main/java/io/microsphere/i18n/util/I18nUtils.java
[ { "identifier": "EmptyServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/EmptyServiceMessageSource.java", "snippet": "public class EmptyServiceMessageSource implements ServiceMessageSource {\n\n public static final EmptyServiceMessageSource INSTANCE = new EmptyServiceMessageSource();\n\n private EmptyServiceMessageSource() {\n }\n\n @Override\n public void init() {\n }\n\n @Override\n public void destroy() {\n }\n\n @Override\n public String getMessage(String code, Locale locale, Object... args) {\n return null;\n }\n\n @Override\n public String getSource() {\n return \"Empty\";\n }\n}" }, { "identifier": "ServiceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/ServiceMessageSource.java", "snippet": "public interface ServiceMessageSource {\n\n /**\n * Common internationalizing message sources\n */\n String COMMON_SOURCE = \"common\";\n\n /**\n * Initialize the life cycle\n */\n void init();\n\n /**\n * Destruction life cycle\n */\n void destroy();\n\n /**\n * Getting international Messages\n *\n * @param code message Code\n * @param locale {@link Locale}\n * @param args the argument of message pattern\n * @return 如果获取到,返回器内容,获取不到,返回 <code>null</code>\n */\n @Nullable\n String getMessage(String code, Locale locale, Object... args);\n\n default String getMessage(String code, Object... args) {\n return getMessage(code, getLocale(), args);\n }\n\n /**\n * Get the runtime {@link Locale}\n *\n * @return {@link Locale}\n */\n @NonNull\n default Locale getLocale() {\n Locale locale = LocaleContextHolder.getLocale();\n return locale == null ? getDefaultLocale() : locale;\n }\n\n /**\n * Get the default {@link Locale}\n *\n * @return {@link Locale#SIMPLIFIED_CHINESE} as default\n */\n @NonNull\n default Locale getDefaultLocale() {\n return Locale.SIMPLIFIED_CHINESE;\n }\n\n /**\n * Gets a list of supported {@link Locale}\n *\n * @return Non-null {@link List}, simplified Chinese and English by default\n */\n @NonNull\n default List<Locale> getSupportedLocales() {\n return asList(getDefaultLocale(), Locale.ENGLISH);\n }\n\n /**\n * Message service source\n *\n * @return The application name or {@link #COMMON_SOURCE}\n */\n default String getSource() {\n return COMMON_SOURCE;\n }\n}" } ]
import io.microsphere.i18n.EmptyServiceMessageSource; import io.microsphere.i18n.ServiceMessageSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
830
package io.microsphere.i18n.util; /** * Internationalization Utilities class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public class I18nUtils { private static final Logger logger = LoggerFactory.getLogger(I18nUtils.class); private static volatile ServiceMessageSource serviceMessageSource; public static ServiceMessageSource serviceMessageSource() { if (serviceMessageSource == null) { logger.warn("serviceMessageSource is not initialized, EmptyServiceMessageSource will be used");
package io.microsphere.i18n.util; /** * Internationalization Utilities class * * @author <a href="mailto:[email protected]">Mercy<a/> * @since 1.0.0 */ public class I18nUtils { private static final Logger logger = LoggerFactory.getLogger(I18nUtils.class); private static volatile ServiceMessageSource serviceMessageSource; public static ServiceMessageSource serviceMessageSource() { if (serviceMessageSource == null) { logger.warn("serviceMessageSource is not initialized, EmptyServiceMessageSource will be used");
return EmptyServiceMessageSource.INSTANCE;
0
2023-11-17 11:35:59+00:00
2k
issavior/savior
savior-event/src/main/java/cn/sunjinxin/savior/event/convert/EventCommon.java
[ { "identifier": "SpringHelper", "path": "savior-core/src/main/java/cn/sunjinxin/savior/core/helper/SpringHelper.java", "snippet": "@FieldDefaults(level = AccessLevel.PRIVATE)\npublic class SpringHelper implements BeanFactoryPostProcessor, ApplicationContextAware, PriorityOrdered {\n\n static ApplicationContext applicationContext;\n\n public static <T> T getBean(Class<T> clazz) {\n return applicationContext.getBean(clazz);\n }\n\n public static Object getBean(String beanName) {\n return applicationContext.getBean(beanName);\n }\n\n public static <T> T getBean(String beanName, Class<T> clazz) {\n return applicationContext.getBean(beanName, clazz);\n }\n\n public static List<String> getAllBeanName() {\n return Arrays.asList(applicationContext.getBeanDefinitionNames());\n }\n\n public static void publish(Object event) {\n applicationContext.publishEvent(event);\n }\n\n @Override\n public void postProcessBeanFactory(@Nonnull ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {\n // ignore\n }\n\n @Override\n public void setApplicationContext(@Nonnull ApplicationContext applicationContext) throws BeansException {\n SpringHelper.applicationContext = applicationContext;\n }\n\n @Override\n public int getOrder() {\n return 0;\n }\n}" }, { "identifier": "EventRun", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/EventRun.java", "snippet": "public class EventRun {\n}" }, { "identifier": "EventProperties", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/configuration/EventProperties.java", "snippet": "@Data\n@FieldDefaults(level = AccessLevel.PRIVATE)\n@ConfigurationProperties(prefix = \"savior.event\")\npublic class EventProperties {\n\n /**\n * @see EventStrategy\n */\n EventStrategy strategy = EventStrategy.DEFAULT;\n\n /**\n * @see ThreadPoolProperties\n */\n ThreadPoolProperties asyncThreadPool = new ThreadPoolProperties();\n\n}" }, { "identifier": "ThreadPoolProperties", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/configuration/ThreadPoolProperties.java", "snippet": "@Data\n@FieldDefaults(level = AccessLevel.PRIVATE)\npublic class ThreadPoolProperties {\n\n Integer corePoolSize = 20;\n\n Integer maxPoolSize = 50;\n\n Integer queueCapacity = 1000;\n\n String threadNamePrefix = \"thread-pool-savior-async-event-\";\n\n}" }, { "identifier": "EventException", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/exception/EventException.java", "snippet": "@StandardException\npublic class EventException extends RuntimeException{\n}" }, { "identifier": "EventHandler", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/handler/EventHandler.java", "snippet": "public interface EventHandler {\n\n List<EventStrategy> strategy();\n\n Eventer event();\n\n void register(Object eventListener);\n\n void post(Object eventContext);\n\n void unregister(Object eventClass);\n}" } ]
import cn.hutool.core.lang.Assert; import cn.sunjinxin.savior.core.helper.SpringHelper; import cn.sunjinxin.savior.event.EventRun; import cn.sunjinxin.savior.event.configuration.EventProperties; import cn.sunjinxin.savior.event.configuration.ThreadPoolProperties; import cn.sunjinxin.savior.event.exception.EventException; import cn.sunjinxin.savior.event.handler.EventHandler; import com.google.common.collect.Sets; import org.reflections.Reflections; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.lang.reflect.Modifier; import java.util.List; import java.util.Optional; import java.util.concurrent.ThreadPoolExecutor; import java.util.stream.Collectors;
1,146
package cn.sunjinxin.savior.event.convert; /** * common * * @author issavior */ public class EventCommon { /** * Properties to ThreadPoolTaskExecutor * * @return / */ public static ThreadPoolTaskExecutor buildThreadPoolTaskExecutor() { ThreadPoolProperties properties = SpringHelper.getBean(EventProperties.class).getAsyncThreadPool(); checkThreadPoolProperties(properties); ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(properties.getCorePoolSize()); threadPoolTaskExecutor.setMaxPoolSize(properties.getMaxPoolSize()); threadPoolTaskExecutor.setQueueCapacity(properties.getQueueCapacity()); threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); threadPoolTaskExecutor.setThreadNamePrefix(properties.getThreadNamePrefix()); threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true); threadPoolTaskExecutor.setAwaitTerminationSeconds(5); threadPoolTaskExecutor.initialize(); return threadPoolTaskExecutor; } /** * check * * @param properties / */ private static void checkThreadPoolProperties(ThreadPoolProperties properties) { Assert.isFalse(properties.getCorePoolSize() > properties.getMaxPoolSize() , () -> new EventException("savior-event`s ThreadPoolProperties has exception:[CorePoolSize > MaxPoolSize]")); } /** * build * * @return / */ public static List<EventHandler> buildEventHandlers() {
package cn.sunjinxin.savior.event.convert; /** * common * * @author issavior */ public class EventCommon { /** * Properties to ThreadPoolTaskExecutor * * @return / */ public static ThreadPoolTaskExecutor buildThreadPoolTaskExecutor() { ThreadPoolProperties properties = SpringHelper.getBean(EventProperties.class).getAsyncThreadPool(); checkThreadPoolProperties(properties); ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); threadPoolTaskExecutor.setCorePoolSize(properties.getCorePoolSize()); threadPoolTaskExecutor.setMaxPoolSize(properties.getMaxPoolSize()); threadPoolTaskExecutor.setQueueCapacity(properties.getQueueCapacity()); threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); threadPoolTaskExecutor.setThreadNamePrefix(properties.getThreadNamePrefix()); threadPoolTaskExecutor.setWaitForTasksToCompleteOnShutdown(true); threadPoolTaskExecutor.setAwaitTerminationSeconds(5); threadPoolTaskExecutor.initialize(); return threadPoolTaskExecutor; } /** * check * * @param properties / */ private static void checkThreadPoolProperties(ThreadPoolProperties properties) { Assert.isFalse(properties.getCorePoolSize() > properties.getMaxPoolSize() , () -> new EventException("savior-event`s ThreadPoolProperties has exception:[CorePoolSize > MaxPoolSize]")); } /** * build * * @return / */ public static List<EventHandler> buildEventHandlers() {
return Optional.of(new Reflections(EventRun.class.getPackage().getName()))
1
2023-11-16 15:34:22+00:00
2k
Viola-Siemens/Advanced-Enchantments
src/main/java/com/hexagram2021/advanced_enchantments/AdvancedEnchantments.java
[ { "identifier": "AEContent", "path": "src/main/java/com/hexagram2021/advanced_enchantments/common/AEContent.java", "snippet": "public class AEContent {\n\tpublic static void modConstruction(IEventBus bus) {\n\t\tAEEnchantments.init(bus);\n\t}\n}" }, { "identifier": "AECommonConfig", "path": "src/main/java/com/hexagram2021/advanced_enchantments/common/config/AECommonConfig.java", "snippet": "public final class AECommonConfig {\n\tprivate static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n\tprivate static final ForgeConfigSpec SPEC;\n\n\tpublic static final ForgeConfigSpec.BooleanValue CHANNELING;\n\tpublic static final ForgeConfigSpec.BooleanValue SILK_TOUCH;\n\tpublic static final ForgeConfigSpec.BooleanValue SILK_TOUCH_WITH_NBT;\n\tpublic static final ForgeConfigSpec.BooleanValue FLAME;\n\tpublic static final ForgeConfigSpec.BooleanValue INFINITY;\n\tpublic static final ForgeConfigSpec.BooleanValue KEEP_ONLY_OPS_SET_NBT;\n\n\tprivate AECommonConfig() {\n\t}\n\n\tstatic {\n\t\tBUILDER.push(\"advanced_enchantments-common-config\");\n\t\t\tBUILDER.comment(\"You can determine each enchantment enabled or disabled.\");\n\t\t\tBUILDER.push(\"enchantments\");\n\t\t\t\tCHANNELING = BUILDER.define(\"CHANNELING\", true);\n\t\t\t\tSILK_TOUCH = BUILDER.define(\"SILK_TOUCH\", true);\n\t\t\t\tSILK_TOUCH_WITH_NBT = BUILDER.define(\"SILK_TOUCH_WITH_NBT\", false);\n\t\t\t\tFLAME = BUILDER.define(\"FLAME\", true);\n\t\t\t\tINFINITY = BUILDER.define(\"INFINITY\", true);\n\t\t\tBUILDER.pop();\n\t\t\tBUILDER.push(\"miscs\");\n\t\t\t\tKEEP_ONLY_OPS_SET_NBT = BUILDER.comment(\"If true, some block entities (eg. spawner, lectern) can not be placed from itemstack with nbt. If false, this feature from vanilla will be disabled.\").define(\"KEEP_ONLY_OPS_SET_NBT\", true);\n\t\t\tBUILDER.pop();\n\t\tBUILDER.pop();\n\n\t\tSPEC = BUILDER.build();\n\t}\n\n\tpublic static ForgeConfigSpec getConfig() {\n\t\treturn SPEC;\n\t}\n}" } ]
import com.hexagram2021.advanced_enchantments.common.AEContent; import com.hexagram2021.advanced_enchantments.common.config.AECommonConfig; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.ModList; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
709
package com.hexagram2021.advanced_enchantments; @SuppressWarnings("unused") @Mod(AdvancedEnchantments.MODID) public class AdvancedEnchantments { public static final String MODID = "advanced_enchantments"; public static final String MODNAME = "Advanced Enchantments"; public static final String VERSION = ModList.get().getModFileById(MODID).versionString(); public AdvancedEnchantments() { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
package com.hexagram2021.advanced_enchantments; @SuppressWarnings("unused") @Mod(AdvancedEnchantments.MODID) public class AdvancedEnchantments { public static final String MODID = "advanced_enchantments"; public static final String MODNAME = "Advanced Enchantments"; public static final String VERSION = ModList.get().getModFileById(MODID).versionString(); public AdvancedEnchantments() { IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus();
AEContent.modConstruction(bus);
0
2023-11-12 12:23:21+00:00
2k
pyzpre/Create-Bicycles-Bitterballen
src/main/java/createbicyclesbitterballen/index/BlockRegistry.java
[ { "identifier": "MechanicalFryer", "path": "src/main/java/createbicyclesbitterballen/block/mechanicalfryer/MechanicalFryer.java", "snippet": "public class MechanicalFryer extends HorizontalKineticBlock implements IBE<MechanicalFryerEntity> {\n public MechanicalFryer(Properties properties) {\n super(properties);\n }\n\n\n @Override\n public boolean canSurvive(BlockState state, LevelReader worldIn, BlockPos pos) {\n return !AllBlocks.BASIN.has(worldIn.getBlockState(pos.below()));\n }\n\n @Override\n public VoxelShape getShape(BlockState state, BlockGetter worldIn, BlockPos pos, CollisionContext context) {\n if (context instanceof EntityCollisionContext\n && ((EntityCollisionContext) context).getEntity() instanceof Player)\n return AllShapes.CASING_14PX.get(Direction.DOWN);\n\n return AllShapes.MECHANICAL_PROCESSOR_SHAPE;\n }\n\n @Override\n public BlockState getStateForPlacement(BlockPlaceContext context) {\n Direction prefferedSide = getPreferredHorizontalFacing(context);\n if (prefferedSide != null)\n return defaultBlockState().setValue(HORIZONTAL_FACING, prefferedSide);\n return super.getStateForPlacement(context);\n }\n\n\n @Override\n public boolean hasShaftTowards(LevelReader world, BlockPos pos, BlockState state, Direction face) {\n return face.getAxis() == state.getValue(HORIZONTAL_FACING)\n .getAxis();\n }\n\n @Override\n public Axis getRotationAxis(BlockState state) {\n return state.getValue(HORIZONTAL_FACING)\n .getAxis();\n }\n\n @Override\n public BlockEntityType<? extends MechanicalFryerEntity> getBlockEntityType() {\n return BlockEntityRegistry.MECHANICAL_FRYER.get();\n }\n\n @Override\n public Class<MechanicalFryerEntity> getBlockEntityClass() {\n return MechanicalFryerEntity.class;\n }\n\n\n @Override\n public boolean isPathfindable(BlockState state, BlockGetter reader, BlockPos pos, PathComputationType type) {\n return false;\n }\n\n}" }, { "identifier": "REGISTRATE", "path": "src/main/java/createbicyclesbitterballen/CreateBicBitMod.java", "snippet": "public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(MODID);" } ]
import com.simibubi.create.content.kinetics.BlockStressDefaults; import com.simibubi.create.foundation.data.BlockStateGen; import com.simibubi.create.foundation.data.SharedProperties; import com.tterrag.registrate.util.entry.BlockEntry; import createbicyclesbitterballen.block.mechanicalfryer.MechanicalFryer; import com.simibubi.create.content.processing.AssemblyOperatorBlockItem; import static com.simibubi.create.foundation.data.TagGen.pickaxeOnly; import static createbicyclesbitterballen.CreateBicBitMod.REGISTRATE; import static com.simibubi.create.foundation.data.ModelGen.customItemModel;
742
package createbicyclesbitterballen.index; public class BlockRegistry { public static final BlockEntry<MechanicalFryer> MECHANICAL_FRYER =
package createbicyclesbitterballen.index; public class BlockRegistry { public static final BlockEntry<MechanicalFryer> MECHANICAL_FRYER =
REGISTRATE.block("mechanical_fryer", MechanicalFryer::new)
1
2023-11-12 13:05:18+00:00
2k
cometcake575/Origins-Reborn
src/main/java/com/starshootercity/Origin.java
[ { "identifier": "Ability", "path": "src/main/java/com/starshootercity/abilities/Ability.java", "snippet": "public interface Ability {\n @NotNull Key getKey();\n}" }, { "identifier": "VisibleAbility", "path": "src/main/java/com/starshootercity/abilities/VisibleAbility.java", "snippet": "public interface VisibleAbility extends Ability {\n @NotNull List<OriginSwapper.LineData.LineComponent> getDescription();\n @NotNull List<OriginSwapper.LineData.LineComponent> getTitle();\n}" }, { "identifier": "AbilityRegister", "path": "src/main/java/com/starshootercity/abilities/AbilityRegister.java", "snippet": "public class AbilityRegister {\n public static Map<Key, Ability> abilityMap = new HashMap<>();\n public static Map<Key, DependencyAbility> dependencyAbilityMap = new HashMap<>();\n public static void registerAbility(Ability ability) {\n abilityMap.put(ability.getKey(), ability);\n if (ability instanceof DependencyAbility dependencyAbility) {\n dependencyAbilityMap.put(ability.getKey(), dependencyAbility);\n }\n if (ability instanceof Listener listener) {\n Bukkit.getPluginManager().registerEvents(listener, OriginsReborn.getInstance());\n }\n }\n\n public static void runForAbility(Entity entity, Key key, Runnable runnable) {\n runForAbility(entity, key, runnable, () -> {});\n }\n\n public static boolean hasAbility(Player player, Key key) {\n Origin origin = OriginSwapper.getOrigin(player);\n if (origin == null) {\n return false;\n }\n if (abilityMap.get(key) instanceof DependantAbility dependantAbility) {\n return origin.hasAbility(key) && ((dependantAbility.getDependencyType() == DependantAbility.DependencyType.REGULAR) == dependantAbility.getDependency().isEnabled(player));\n }\n return origin.hasAbility(key);\n }\n\n public static void runForAbility(Entity entity, Key key, Runnable runnable, Runnable other) {\n if (entity instanceof Player player) {\n if (hasAbility(player, key)) {\n runnable.run();\n return;\n }\n }\n other.run();\n }\n\n public static void runWithoutAbility(Entity entity, Key key, Runnable runnable) {\n runForAbility(entity, key, () -> {}, runnable);\n }\n\n\n public static boolean canFly(Player player) {\n if (player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR) return true;\n Origin origin = OriginSwapper.getOrigin(player);\n if (origin == null) return false;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof FlightAllowingAbility flightAllowingAbility) {\n if (flightAllowingAbility.canFly(player)) return true;\n }\n }\n return false;\n }\n\n\n public static boolean isInvisible(Player player) {\n if (player.hasPotionEffect(PotionEffectType.INVISIBILITY)) return true;\n Origin origin = OriginSwapper.getOrigin(player);\n if (origin == null) return false;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof VisibilityChangingAbility visibilityChangingAbility) {\n if (visibilityChangingAbility.isInvisible(player)) return true;\n }\n }\n return false;\n }\n\n public static float getFlySpeed(Player player) {\n if (player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR) return 0.2f;\n Origin origin = OriginSwapper.getOrigin(player);\n if (origin == null) return 1f;\n float speed = 1f;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof FlightAllowingAbility flightAllowingAbility) {\n if (flightAllowingAbility.canFly(player)) {\n speed = Math.min(speed, flightAllowingAbility.getFlightSpeed(player));\n }\n }\n }\n return speed;\n }\n\n public static void updateEntity(Player player, Entity target) {\n byte data = 0;\n if (target.getFireTicks() > 0) {\n data += 0x01;\n }\n if (target.isSneaking()) {\n data += 0x02;\n }\n if (target.isGlowing()) {\n data += 0x40;\n }\n if (target instanceof Player targetPlayer) {\n if (targetPlayer.isSprinting()) {\n data += 0x08;\n }\n if (targetPlayer.isSwimming()) {\n data += 0x10;\n }\n if (targetPlayer.isInvisible()) {\n data += 0x20;\n }\n if (targetPlayer.isGliding()) {\n data += 0x80;\n }\n for (EquipmentSlot equipmentSlot : EquipmentSlot.values()) {\n player.sendEquipmentChange(targetPlayer, equipmentSlot, targetPlayer.getInventory().getItem(equipmentSlot));\n }\n }\n List<SynchedEntityData.DataValue<?>> eData = new ArrayList<>();\n eData.add(SynchedEntityData.DataValue.create(new EntityDataAccessor<>(0, EntityDataSerializers.BYTE), data));\n ClientboundSetEntityDataPacket metadata = new ClientboundSetEntityDataPacket(((CraftEntity) target).getHandle().getId(), eData);\n ((CraftPlayer) player).getHandle().connection.send(metadata);\n }\n}" } ]
import com.starshootercity.abilities.Ability; import com.starshootercity.abilities.VisibleAbility; import com.starshootercity.abilities.AbilityRegister; import net.kyori.adventure.key.Key; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.Range; import java.util.ArrayList; import java.util.List;
1,594
package com.starshootercity; public class Origin { private final ItemStack icon; private final int position; private final char impact; private final String name; private final List<Key> abilities; private final List<OriginSwapper.LineData.LineComponent> lineComponent; public List<OriginSwapper.LineData.LineComponent> getLineData() { return lineComponent; } public Origin(String name, ItemStack icon, int position, @Range(from = 0, to = 3) int impact, List<Key> abilities, String description) { this.lineComponent = OriginSwapper.LineData.makeLineFor(description, OriginSwapper.LineData.LineComponent.LineType.DESCRIPTION); this.name = name; this.abilities = abilities; this.icon = icon; this.position = position; this.impact = switch (impact) { case 0 -> '\uE002'; case 1 -> '\uE003'; case 2 -> '\uE004'; default -> '\uE005'; }; } public List<VisibleAbility> getVisibleAbilities() { List<VisibleAbility> result = new ArrayList<>(); for (Key key : abilities) { if (AbilityRegister.abilityMap.get(key) instanceof VisibleAbility visibleAbility) { result.add(visibleAbility); } } return result; }
package com.starshootercity; public class Origin { private final ItemStack icon; private final int position; private final char impact; private final String name; private final List<Key> abilities; private final List<OriginSwapper.LineData.LineComponent> lineComponent; public List<OriginSwapper.LineData.LineComponent> getLineData() { return lineComponent; } public Origin(String name, ItemStack icon, int position, @Range(from = 0, to = 3) int impact, List<Key> abilities, String description) { this.lineComponent = OriginSwapper.LineData.makeLineFor(description, OriginSwapper.LineData.LineComponent.LineType.DESCRIPTION); this.name = name; this.abilities = abilities; this.icon = icon; this.position = position; this.impact = switch (impact) { case 0 -> '\uE002'; case 1 -> '\uE003'; case 2 -> '\uE004'; default -> '\uE005'; }; } public List<VisibleAbility> getVisibleAbilities() { List<VisibleAbility> result = new ArrayList<>(); for (Key key : abilities) { if (AbilityRegister.abilityMap.get(key) instanceof VisibleAbility visibleAbility) { result.add(visibleAbility); } } return result; }
public List<Ability> getAbilities() {
0
2023-11-10 21:39:16+00:00
2k
vadremix/journee
services/user-management-service/src/test/java/com/worldjournee/usermanagementservice/unit/UserServiceTest.java
[ { "identifier": "User", "path": "services/user-management-service/src/main/java/com/worldjournee/usermanagementservice/model/User.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class User implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private int id;\n\n @NotEmpty(message = \"Username cannot be empty\")\n @Column(nullable = false, unique = true)\n private String username;\n\n @Email(message = \"Email should be valid\")\n @NotEmpty(message = \"Email cannot be empty\")\n @Column(nullable = false, unique = true)\n private String email;\n\n @Size(min = 12, message = \"Password should be at least 12 characters long\")\n @NotEmpty(message = \"Password cannot be empty\")\n @Column(nullable = false)\n private String password;\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return false;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return false;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return false;\n }\n\n @Override\n public boolean isEnabled() {\n return false;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return null;\n }\n}" }, { "identifier": "UserRepository", "path": "services/user-management-service/src/main/java/com/worldjournee/usermanagementservice/repository/UserRepository.java", "snippet": "public interface UserRepository extends JpaRepository<User, Long> {\n\n}" }, { "identifier": "UserService", "path": "services/user-management-service/src/main/java/com/worldjournee/usermanagementservice/service/UserService.java", "snippet": "@Service\npublic class UserService {\n private final UserRepository userRepository;\n\n private final PasswordEncoder passwordEncoder;\n\n @Autowired\n public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {\n this.userRepository = userRepository;\n this.passwordEncoder = passwordEncoder;\n }\n\n public User saveUser(User user) {\n user.setPassword(encodePassword(user.getPassword()));\n\n try {\n return userRepository.save(user);\n } catch (Exception|Error e) {\n throw new RuntimeException(\"Username or email already exists\");\n }\n }\n\n private String encodePassword(String password) {\n return passwordEncoder.encode(password);\n }\n}" } ]
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import com.worldjournee.usermanagementservice.model.User; import com.worldjournee.usermanagementservice.repository.UserRepository; import com.worldjournee.usermanagementservice.service.UserService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.crypto.password.PasswordEncoder;
821
package com.worldjournee.usermanagementservice.unit; @ExtendWith(MockitoExtension.class) class UserServiceTest { @Mock private UserRepository userRepository; @Mock private PasswordEncoder passwordEncoder; @InjectMocks
package com.worldjournee.usermanagementservice.unit; @ExtendWith(MockitoExtension.class) class UserServiceTest { @Mock private UserRepository userRepository; @Mock private PasswordEncoder passwordEncoder; @InjectMocks
private UserService userService;
2
2023-11-13 21:40:58+00:00
2k
daobab-projects/orm-performance-comparator
src/main/java/io/daobab/performance/daobab/table/enhanced/CountryCity.java
[ { "identifier": "City", "path": "src/main/java/io/daobab/performance/daobab/table/City.java", "snippet": "@SuppressWarnings(\"rawtypes\")\n@TableInformation(name = \"CITY\")\npublic class City extends Table<City> implements\n CityId<City, Integer>,\n io.daobab.performance.daobab.column.City<City, String>,\n CountryId<City, Integer>,\n LastUpdate<City, LocalDateTime>,\n\n PrimaryKey<City, Integer, CityId> {\n\n\n public City() {\n super();\n }\n\n public City(Map<String, Object> parameters) {\n super(parameters);\n }\n\n @Override\n public List<TableColumn> columns() {\n return Arrays.asList(\n new TableColumn(colCityId()).primaryKey().size(16),\n new TableColumn(colCity()).size(50),\n new TableColumn(colCountryId()).size(16),\n new TableColumn(colLastUpdate()).size(26).scale(6)\n );\n }\n\n @Override\n public Column<City, Integer, CityId> colID() {\n return colCityId();\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(getId());\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass()) return false;\n PrimaryKey<?, ?, ?> other = (PrimaryKey<?, ?, ?>) obj;\n return Objects.equals(getId(), other.getId());\n }\n\n\n}" }, { "identifier": "Country", "path": "src/main/java/io/daobab/performance/daobab/table/Country.java", "snippet": "@SuppressWarnings(\"rawtypes\")\n@TableInformation(name = \"COUNTRY\")\npublic class Country extends Table<Country> implements\n CountryId<Country, Integer>,\n io.daobab.performance.daobab.column.Country<Country, String>,\n LastUpdate<Country, LocalDateTime>,\n\n PrimaryKey<Country, Integer, CountryId> {\n\n\n public Country() {\n super();\n }\n\n public Country(Map<String, Object> parameters) {\n super(parameters);\n }\n\n @Override\n public List<TableColumn> columns() {\n return Arrays.asList(\n new TableColumn(colCountryId()).primaryKey().size(16),\n new TableColumn(colCountry()).size(50),\n new TableColumn(colLastUpdate()).size(26).scale(6)\n );\n }\n\n @Override\n public Column<Country, Integer, CountryId> colID() {\n return colCountryId();\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(getId());\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) return true;\n if (obj == null) return false;\n if (getClass() != obj.getClass()) return false;\n PrimaryKey<?, ?, ?> other = (PrimaryKey<?, ?, ?>) obj;\n return Objects.equals(getId(), other.getId());\n }\n\n\n}" } ]
import io.daobab.model.Column; import io.daobab.model.EnhancedEntity; import io.daobab.model.TableInformation; import io.daobab.performance.daobab.table.City; import io.daobab.performance.daobab.table.Country; import io.daobab.query.base.Query; import io.daobab.query.base.QueryJoin; import java.util.Collections; import java.util.List; import java.util.Map;
872
package io.daobab.performance.daobab.table.enhanced; @TableInformation(name = "CITY") public class CountryCity extends City implements
package io.daobab.performance.daobab.table.enhanced; @TableInformation(name = "CITY") public class CountryCity extends City implements
io.daobab.performance.daobab.column.Country<City, Integer>,
1
2023-11-12 21:43:51+00:00
2k
lastnightinparis/tinkoff-investement-bot
orchestrator-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/service/order/OrderServiceImpl.java
[ { "identifier": "TinkoffUserRepository", "path": "orchestrator-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/repository/TinkoffUserRepository.java", "snippet": "@Repository\npublic interface TinkoffUserRepository extends JpaRepository<TinkoffUser, Long> {\n\n @Transactional\n default TinkoffUser get(Long id) {\n var user = this.getReferenceById(id);\n if (isNull(user.accountId())) {\n var api = InvestApi.createSandbox(user.token());\n var sandboxAccountId = api.getSandboxService().getAccountsSync().stream().findFirst();\n var accountId = sandboxAccountId.map(Account::getId).orElseGet(() -> api.getSandboxService().openAccountSync());\n user.accountId(accountId);\n this.save(user);\n }\n return user;\n }\n\n}" }, { "identifier": "TradeOrderRepository", "path": "orchestrator-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/repository/TradeOrderRepository.java", "snippet": "@Repository\npublic interface TradeOrderRepository extends JpaRepository<TradeOrder, String> {\n\n @Transactional\n default TradeOrder save(OrderResult orderResult, TinkoffUser tinkoffUser) {\n return this.save(TradeOrder.builder()\n .id(orderResult.id())\n .status(orderResult.status())\n .tinkoffUser(tinkoffUser)\n .build());\n }\n\n @Query(value = \"select o from TradeOrder o where o.status = 'CREATED'\")\n List<TradeOrder> getNewOrders();\n}" }, { "identifier": "OrderNotificationServiceClient", "path": "orchestrator-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/service/client/OrderNotificationServiceClient.java", "snippet": "@Slf4j\n@Service\n@RequiredArgsConstructor\npublic class OrderNotificationServiceClient {\n\n private final RestConfig restConfig;\n private final RestTemplate restTemplate = new RestTemplate();\n\n public void notify(TinkoffUser user, OrderStatus orderStatus, OrderState orderState) {\n val notification = new NotificationDto(user.id(), createMessage(orderStatus, orderState));\n log.info(\"Отправляем сообщение \\\"{}\\\"\", notification.message());\n\n val resourceUrl = String.join(\"/\", restConfig.getBotUrl(), \"event/trading\");\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n val entity = new HttpEntity<>(notification, headers);\n restTemplate.postForLocation(resourceUrl, entity);\n }\n\n private String getDirection(OrderState orderState) {\n return orderState.getDirection() == OrderDirection.ORDER_DIRECTION_BUY\n ? \"покупку\"\n : \"продажу\";\n }\n\n private String createMessage(OrderStatus orderStatus, OrderState order) {\n val direction = getDirection(order);\n var message = switch (orderStatus) {\n case CREATED ->\n String.format(\"Отправили брокеру поручение на %s бумаги %s.\\nСумма: %s.\\nКоличество лотов: %s\",\n direction,\n order.getFigi(),\n convertMoneyValue(order.getInitialOrderPrice()),\n order.getLotsRequested());\n case COMPLETED -> String.format(\"Поручение на %s бумаги %s исполнено.\\nСумма: %s.\\nКоличество лотов: %s\",\n direction,\n order.getFigi(),\n convertMoneyValue(order.getExecutedOrderPrice()),\n order.getLotsExecuted());\n case PARTIALLY_COMPLETED ->\n String.format(\"Поручение на %s бумаги %s исполнено частично.\\nСумма: %s.\\nКоличество лотов: %s из %s\",\n direction,\n order.getFigi(),\n convertMoneyValue(order.getExecutedOrderPrice()),\n order.getLotsExecuted(),\n order.getLotsRequested());\n case REJECTED -> \"Поручение отклонили на стороне биржи\";\n default -> \"Не смогли подать поручение. Свяжитесь с нашим специалистом по горячей линии 8-800-555-35-35\";\n };\n\n return message.replace(\".\", \"\\\\.\");\n }\n}" } ]
import com.itmo.tinkoffinvestementbot.repository.TinkoffUserRepository; import com.itmo.tinkoffinvestementbot.repository.TradeOrderRepository; import com.itmo.tinkoffinvestementbot.service.client.OrderNotificationServiceClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import ru.tinkoff.piapi.contract.v1.OrderDirection; import ru.tinkoff.piapi.contract.v1.OrderType; import ru.tinkoff.piapi.contract.v1.PostOrderResponse; import ru.tinkoff.piapi.contract.v1.Quotation; import ru.tinkoff.piapi.core.InvestApi;
1,182
package com.itmo.tinkoffinvestementbot.service.order; @Service @Profile("!dev") public class OrderServiceImpl extends AbstractOrderServiceImpl { @Autowired public OrderServiceImpl(PostOrderConverter postOrderConverter, TinkoffUserRepository tinkoffUserRepository,
package com.itmo.tinkoffinvestementbot.service.order; @Service @Profile("!dev") public class OrderServiceImpl extends AbstractOrderServiceImpl { @Autowired public OrderServiceImpl(PostOrderConverter postOrderConverter, TinkoffUserRepository tinkoffUserRepository,
TradeOrderRepository tradeOrderRepository,
1
2023-11-13 09:28:00+00:00
2k
toxicity188/InventoryAPI
plugin/src/main/java/kor/toxicity/inventory/manager/ImageManagerImpl.java
[ { "identifier": "ImageManager", "path": "api/src/main/java/kor/toxicity/inventory/api/manager/ImageManager.java", "snippet": "public interface ImageManager extends InventoryManager, RegistrySupplier<BufferedImage> {\n}" }, { "identifier": "Registry", "path": "api/src/main/java/kor/toxicity/inventory/api/registry/Registry.java", "snippet": "public interface Registry<T> {\n @Nullable T getByName(@NotNull String name);\n @NotNull Collection<@NotNull T> getAllValues();\n @NotNull Set<@NotNull String> getAllKeys();\n void register(@NotNull String name, @NotNull T t);\n}" }, { "identifier": "ImageRegistryImpl", "path": "plugin/src/main/java/kor/toxicity/inventory/registry/ImageRegistryImpl.java", "snippet": "public class ImageRegistryImpl implements Registry<BufferedImage> {\n private final Map<String, BufferedImage> fontMap = new HashMap<>();\n @Override\n public @Nullable BufferedImage getByName(@NotNull String name) {\n return fontMap.get(name);\n }\n\n @Override\n public @NotNull Collection<@NotNull BufferedImage> getAllValues() {\n return fontMap.values();\n }\n\n @Override\n public @NotNull Set<@NotNull String> getAllKeys() {\n return fontMap.keySet();\n }\n\n @Override\n public void register(@NotNull String name, @NotNull BufferedImage bufferedImage) {\n fontMap.put(name, bufferedImage);\n }\n\n public void clear() {\n fontMap.clear();\n }\n}" }, { "identifier": "PluginUtil", "path": "plugin/src/main/java/kor/toxicity/inventory/util/PluginUtil.java", "snippet": "@SuppressWarnings(\"ResultOfMethodCallIgnored\")\npublic class PluginUtil {\n private PluginUtil() {\n throw new SecurityException();\n }\n\n public static void loadFolder(String dir, Consumer<File> fileConsumer) {\n var dataFolder = InventoryAPI.getInstance().getDataFolder();\n if (!dataFolder.exists()) dataFolder.mkdir();\n var folder = new File(dataFolder, dir);\n if (!folder.exists()) folder.mkdir();\n var listFiles = folder.listFiles();\n if (listFiles != null) for (File listFile : listFiles) {\n fileConsumer.accept(listFile);\n }\n }\n\n public static FileName getFileName(File file) {\n var name = file.getName().split(\"\\\\.\");\n return new FileName(name[0], name.length > 1 ? name[1] : \"\");\n }\n\n public static void warn(String message) {\n InventoryAPI.getInstance().getLogger().warning(message);\n }\n\n public record FileName(String name, String extension) {\n }\n}" } ]
import kor.toxicity.inventory.api.manager.ImageManager; import kor.toxicity.inventory.api.registry.Registry; import kor.toxicity.inventory.registry.ImageRegistryImpl; import kor.toxicity.inventory.util.PluginUtil; import org.jetbrains.annotations.NotNull; import javax.imageio.ImageIO; import java.awt.image.BufferedImage;
706
package kor.toxicity.inventory.manager; public class ImageManagerImpl implements ImageManager { private final ImageRegistryImpl imageRegistry = new ImageRegistryImpl(); @Override public void reload() { imageRegistry.clear();
package kor.toxicity.inventory.manager; public class ImageManagerImpl implements ImageManager { private final ImageRegistryImpl imageRegistry = new ImageRegistryImpl(); @Override public void reload() { imageRegistry.clear();
PluginUtil.loadFolder("images", f -> {
3
2023-11-13 00:19:46+00:00
2k
ryosoraa/E-Rapor
src/main/java/com/erapor/erapor/service/StudentsService.java
[ { "identifier": "StudentsDAO", "path": "src/main/java/com/erapor/erapor/model/DAO/StudentsDAO.java", "snippet": "@Data\n@Entity\n@Table(name = \"students\")\npublic class StudentsDAO {\n\n @Id\n @NotBlank\n @Size(max = 50)\n private String id;\n\n @NotBlank\n @Size(max = 100)\n private String name;\n\n @NotBlank\n private Date dob;\n\n @NotBlank\n @Size(max = 20)\n private String nisn;\n\n @NotBlank\n @Size(max = 20)\n private String major;\n\n @NotBlank\n @Size(max = 50)\n private String gender;\n\n @NotBlank\n @Size(max = 100)\n private String city;\n\n @NotBlank\n @Size(max = 100)\n private String country;\n\n @JsonIgnoreProperties(\"student\")\n @OneToOne(mappedBy = \"student\")\n private ValuesDAO valuesDAO;\n\n @JsonIgnoreProperties(\"student\")\n @OneToOne(mappedBy = \"student\")\n private AccountsDAO accountsDAO;\n}" }, { "identifier": "ValuesDAO", "path": "src/main/java/com/erapor/erapor/model/DAO/ValuesDAO.java", "snippet": "@Data\n@Entity\n@Table(name = \"`values`\")\npublic class ValuesDAO {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Integer id;\n private Integer IPA;\n private Integer IPS;\n private Integer MTK;\n private Integer TOTAL;\n\n @JsonIgnore\n @OneToOne\n @JoinColumn(name = \"student_id\", nullable = false, updatable = false)\n private StudentsDAO student;\n}" }, { "identifier": "RankingDTO", "path": "src/main/java/com/erapor/erapor/model/DTO/RankingDTO.java", "snippet": "@Data\npublic class RankingDTO {\n\n\n private Integer ranking;\n private String name;\n private String major;\n private Integer MTK;\n private Integer IPA;\n private Integer IPS;\n private Integer total_value;\n\n public RankingDTO(StudentsDAO studentsDAO) {\n this.name = studentsDAO.getName();\n this.major = studentsDAO.getMajor();\n this.MTK = studentsDAO.getValuesDAO().getMTK();\n this.IPA = studentsDAO.getValuesDAO().getIPA();\n this.IPS = studentsDAO.getValuesDAO().getIPS();\n this.total_value = studentsDAO.getValuesDAO().getTOTAL();\n\n }\n\n public RankingDTO(StudentsDAO studentsDAO, Integer ranking) {\n this.name = studentsDAO.getName();\n this.major = studentsDAO.getMajor();\n this.MTK = studentsDAO.getValuesDAO().getMTK();\n this.IPA = studentsDAO.getValuesDAO().getIPA();\n this.IPS = studentsDAO.getValuesDAO().getIPS();\n this.total_value = studentsDAO.getValuesDAO().getTOTAL();\n this.ranking = ranking;\n\n\n }\n\n}" }, { "identifier": "StudentsDTO", "path": "src/main/java/com/erapor/erapor/model/DTO/StudentsDTO.java", "snippet": "@Data\npublic class StudentsDTO {\n\n private String UUID;\n private String name;\n private Date dob;\n private String NISN;\n private String majors;\n private String gender;\n private String city;\n private String country;\n\n private ValuesDAO values;\n\n public StudentsDTO(StudentsDAO studentsDAO){\n this.UUID = studentsDAO.getId();\n this.name = studentsDAO.getName();\n this.dob = studentsDAO.getDob();\n this.NISN = studentsDAO.getNisn();\n this.majors = studentsDAO.getMajor();\n this.gender = studentsDAO.getGender();\n this.city = studentsDAO.getCity();\n this.country = studentsDAO.getCountry();\n this.values = studentsDAO.getValuesDAO();\n }\n}" }, { "identifier": "StudentsRepository", "path": "src/main/java/com/erapor/erapor/repository/StudentsRepository.java", "snippet": "public interface StudentsRepository extends JpaRepository<StudentsDAO, String> {\n\n @Query(\"SELECT s FROM StudentsDAO s JOIN FETCH s.valuesDAO val ORDER BY val.TOTAL DESC\")\n List<StudentsDAO> findRanking(Pageable pageable);\n\n @Query(\"SELECT s FROM StudentsDAO s JOIN FETCH s.valuesDAO val ORDER BY val.TOTAL DESC\")\n List<StudentsDAO> findRanking();\n\n @Query(\"SELECT s FROM StudentsDAO s JOIN FETCH s.valuesDAO val WHERE s.name LIKE %:name%\")\n StudentsDAO findByName(@Param(\"name\") String name);\n\n\n}" }, { "identifier": "ValuesRepository", "path": "src/main/java/com/erapor/erapor/repository/ValuesRepository.java", "snippet": "public interface ValuesRepository extends JpaRepository<ValuesDAO, String> {\n}" }, { "identifier": "Converter", "path": "src/main/java/com/erapor/erapor/utils/Converter.java", "snippet": "public class Converter {\n\n public List<StudentsDTO> toListStudentsDTO(List<StudentsDAO> studentsDAOS){\n List<StudentsDTO> results = new ArrayList<>();\n\n for (StudentsDAO raw:studentsDAOS) {\n results.add(new StudentsDTO(raw));\n }\n\n return results;\n }\n\n public List<RankingDTO> toListRankingDTO(List<StudentsDAO> studentsDAOS, Integer page, Integer size){\n List<RankingDTO> results = new ArrayList<>();\n\n Integer start = (page * size);\n Integer end = size;\n\n for (StudentsDAO raw:studentsDAOS) {\n start++;\n results.add(new RankingDTO(raw, start));\n }\n\n return results;\n }\n}" } ]
import com.erapor.erapor.model.DAO.StudentsDAO; import com.erapor.erapor.model.DAO.ValuesDAO; import com.erapor.erapor.model.DTO.RankingDTO; import com.erapor.erapor.model.DTO.StudentsDTO; import com.erapor.erapor.repository.StudentsRepository; import com.erapor.erapor.repository.ValuesRepository; import com.erapor.erapor.utils.Converter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.Comparator; import java.util.List;
1,546
package com.erapor.erapor.service; @Service public class StudentsService { @Autowired StudentsRepository studentsRepository; @Autowired ValuesRepository valuesRepository; @Autowired Converter converter; public List<RankingDTO> ranking(Integer page, Integer size){ Pageable pageable = PageRequest.of(page, size); return converter.toListRankingDTO(studentsRepository.findRanking(pageable), page, size); } public RankingDTO byName(String name){
package com.erapor.erapor.service; @Service public class StudentsService { @Autowired StudentsRepository studentsRepository; @Autowired ValuesRepository valuesRepository; @Autowired Converter converter; public List<RankingDTO> ranking(Integer page, Integer size){ Pageable pageable = PageRequest.of(page, size); return converter.toListRankingDTO(studentsRepository.findRanking(pageable), page, size); } public RankingDTO byName(String name){
List<StudentsDAO> students = studentsRepository.findRanking();
0
2023-11-11 19:40:43+00:00
2k
ebandal/jDwgParser
src/structure/sectionpage/HeaderVariables.java
[ { "identifier": "CmColor", "path": "src/structure/CmColor.java", "snippet": "public class CmColor {\n public short colorIndex;\n public int rgbValue;\n public byte colorByte;\n}" }, { "identifier": "HandleRef", "path": "src/structure/HandleRef.java", "snippet": "public class HandleRef {\n byte code;\n byte counter;\n byte[] handle;\n}" } ]
import structure.CmColor; import structure.HandleRef;
1,322
package structure.sectionpage; public class HeaderVariables { public int lSizeInBits; // R2007 Only public long llRequiredVersions; // R2013+ // double dUnknown; default value 412148564080.0 // double dUnknown; defualt value 1.0 // double dUnknown; defualt value 1.0 // double dUnknown; defualt value 1.0 // String tvUnknown; defualt "" // String tvUnknown; defualt "" // String tvUnknown; defualt "" // String tvUnknown; defualt "" // int lUnknown; default value 24L // int lUnknown; default value 0L // short sUnknown; default value 0 // R13-R14 Only public HandleRef hCurrViewportEntityHeader; // Pre-2004 Only: public boolean bDimaso; public boolean bDimsho; public boolean bDimsav; // Undocumented // R13-R14 Only public boolean bPlinegen; public boolean bOrthomode; public boolean bRegenmode; public boolean bFillmode; public boolean bQtextmode; public boolean bPsltscale; public boolean bLimcheck; public boolean bBlipmode; // R13-R14 Only public boolean bUndocumented; // R2004+ public boolean bUsrtimer; public boolean bSkpoly; public boolean bAngdir; public boolean bSplframe; public boolean bAttreq; // R13-R14 Only public boolean bAttdia; // R13-R14 Only public boolean bMirrtext; public boolean bWorldview; public boolean bWireframe; // Undocumented // R13-R14 Only public boolean bTilemode; public boolean bPlimcheck; public boolean bVisretain; public boolean bDelobj; // R13-R14 Only public boolean bDispsilh; public boolean bPellipse; // not present in DXF public short sProxygraphics; public short sDragmode; // R13-R14 Only public short sTreedepth; public short sLunits; public short sLuprec; public short sAunits; public short sAuprec; public short sOsmode; // R13-R14 Only public short sAttmode; public short sCoords; // R13-R14 Only public short sPdmode; public short sPickstyle; // R13-R14 Only // int lUnknown; // R2004+ // int lUnknown; // R2004+ // int lUnknown; // R2004+ public short sUseri1; public short sUseri2; public short sUseri3; public short sUseri4; public short sUseri5; public short sSplinesegs; public short sSurfu; public short sSurfv; public short sSurftype; public short sSurftab1; public short sSurftab2; public short sSplinetype; public short sShadedge; public short sShadedif; public short sUnitmode; public short sMaxactvp; public short sIsolines; public short sCmljust; public short sTextqlty; public double dLtscale; public double dTextsize; public double dTracewid; public double dSketchinc; public double dFilletrad; public double dThickness; public double dAngbase; public double dPdsize; public double dPlinewid; public double dUserr1; public double dUserr2; public double dUserr3; public double dUserr4; public double dUserr5; public double dChamfera; public double dChamferb; public double dChamferc; public double dChamferd; public double dFacetres; public double dCmlscale; public double dCeltscale; public String tMenuname; // R13-R18 public int lTdcreateJD; // Julian day public int lTdcreateMS; // Milliseconds into the day public int lTdupdateJD; // Julian day public int lTdupdateMS; // Milliseconds into the day // int lUnkndown; // R2004+ // int lUnknown // R2004+ // int lUnknown // R2004+ public int lTdindwgD; // Days public int lTdindwgMS; // Milliseconds into the day public int lTdusrtimerD; // Days public int lTdusrtimerMS; // Milliseconds into the day
package structure.sectionpage; public class HeaderVariables { public int lSizeInBits; // R2007 Only public long llRequiredVersions; // R2013+ // double dUnknown; default value 412148564080.0 // double dUnknown; defualt value 1.0 // double dUnknown; defualt value 1.0 // double dUnknown; defualt value 1.0 // String tvUnknown; defualt "" // String tvUnknown; defualt "" // String tvUnknown; defualt "" // String tvUnknown; defualt "" // int lUnknown; default value 24L // int lUnknown; default value 0L // short sUnknown; default value 0 // R13-R14 Only public HandleRef hCurrViewportEntityHeader; // Pre-2004 Only: public boolean bDimaso; public boolean bDimsho; public boolean bDimsav; // Undocumented // R13-R14 Only public boolean bPlinegen; public boolean bOrthomode; public boolean bRegenmode; public boolean bFillmode; public boolean bQtextmode; public boolean bPsltscale; public boolean bLimcheck; public boolean bBlipmode; // R13-R14 Only public boolean bUndocumented; // R2004+ public boolean bUsrtimer; public boolean bSkpoly; public boolean bAngdir; public boolean bSplframe; public boolean bAttreq; // R13-R14 Only public boolean bAttdia; // R13-R14 Only public boolean bMirrtext; public boolean bWorldview; public boolean bWireframe; // Undocumented // R13-R14 Only public boolean bTilemode; public boolean bPlimcheck; public boolean bVisretain; public boolean bDelobj; // R13-R14 Only public boolean bDispsilh; public boolean bPellipse; // not present in DXF public short sProxygraphics; public short sDragmode; // R13-R14 Only public short sTreedepth; public short sLunits; public short sLuprec; public short sAunits; public short sAuprec; public short sOsmode; // R13-R14 Only public short sAttmode; public short sCoords; // R13-R14 Only public short sPdmode; public short sPickstyle; // R13-R14 Only // int lUnknown; // R2004+ // int lUnknown; // R2004+ // int lUnknown; // R2004+ public short sUseri1; public short sUseri2; public short sUseri3; public short sUseri4; public short sUseri5; public short sSplinesegs; public short sSurfu; public short sSurfv; public short sSurftype; public short sSurftab1; public short sSurftab2; public short sSplinetype; public short sShadedge; public short sShadedif; public short sUnitmode; public short sMaxactvp; public short sIsolines; public short sCmljust; public short sTextqlty; public double dLtscale; public double dTextsize; public double dTracewid; public double dSketchinc; public double dFilletrad; public double dThickness; public double dAngbase; public double dPdsize; public double dPlinewid; public double dUserr1; public double dUserr2; public double dUserr3; public double dUserr4; public double dUserr5; public double dChamfera; public double dChamferb; public double dChamferc; public double dChamferd; public double dFacetres; public double dCmlscale; public double dCeltscale; public String tMenuname; // R13-R18 public int lTdcreateJD; // Julian day public int lTdcreateMS; // Milliseconds into the day public int lTdupdateJD; // Julian day public int lTdupdateMS; // Milliseconds into the day // int lUnkndown; // R2004+ // int lUnknown // R2004+ // int lUnknown // R2004+ public int lTdindwgD; // Days public int lTdindwgMS; // Milliseconds into the day public int lTdusrtimerD; // Days public int lTdusrtimerMS; // Milliseconds into the day
public CmColor cmCecolor;
0
2023-11-11 13:57:18+00:00
2k
KomnisEvangelos/GeoApp
app/src/main/java/gr/ihu/geoapp/ui/SplashActivity.java
[ { "identifier": "MainActivity", "path": "app/src/main/java/gr/ihu/geoapp/MainActivity.java", "snippet": "public class MainActivity extends AppCompatActivity {\n\n /**\n * Binding object for the main activity layout.\n */\n private ActivityMainBinding binding;\n\n /**\n * Called when the activity is first created.\n *\n * @param savedInstanceState If the activity is being re-initialized after previously being shut down\n * then this Bundle contains the data it most recently supplied in\n * onSaveInstanceState(Bundle). Otherwise, it is null.\n */\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n binding = ActivityMainBinding.inflate(getLayoutInflater());\n setContentView(binding.getRoot());\n\n BottomNavigationView navView = findViewById(R.id.nav_view);\n // Passing each menu ID as a set of Ids because each\n // menu should be considered as top level destinations.\n AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(\n R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_profile)\n .build();\n NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);\n NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);\n NavigationUI.setupWithNavController(binding.navView, navController);\n }\n\n}" }, { "identifier": "SignInActivity", "path": "app/src/main/java/gr/ihu/geoapp/ui/signin/SignInActivity.java", "snippet": "public class SignInActivity extends AppCompatActivity{\n\n private ActivitySignInBinding binding;\n private EditText emailEditText;\n private EditText passwordEditText;\n\n private SignInViewModel signInViewModel;\n private Validator signInValidator;\n\n /**\n * Initializes the activity.\n * Sets up the click listeners for the sign in and sign up buttons.\n *\n * @param savedInstanceState the saved instance state\n */\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n signInViewModel = new ViewModelProvider(this).get(SignInViewModel.class);\n\n binding = ActivitySignInBinding.inflate(getLayoutInflater());\n View view = binding.getRoot();\n setContentView(view);\n\n\n emailEditText = binding.emailEditText;\n passwordEditText = binding.passwordEditText;\n\n signInValidator = new Validator();\n\n\n Button signinButton = binding.buttonSignin;\n signinButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String email = emailEditText.getText().toString().trim();\n String password = passwordEditText.getText().toString().trim();\n if (signInValidator.isSignInDataValid(emailEditText,passwordEditText)){\n RegularUser user = RegularUser.getInstance();\n user.setEmail(email);\n user.setPassword(password);\n\n signInViewModel.signIn(email, password);\n signInViewModel.getSigninResult().observe(SignInActivity.this, new Observer<Boolean>() {\n @Override\n public void onChanged(Boolean success) {\n if (success){\n Toast.makeText(getApplicationContext(),\"Login Successful\",Toast.LENGTH_SHORT).show();\n navigateToMainActivity();\n }else{\n Toast.makeText(getApplicationContext(),\"Check for errors\",Toast.LENGTH_SHORT).show();\n }\n }\n });\n\n }else{\n Toast.makeText(getApplicationContext(),\"All fields are required\",Toast.LENGTH_SHORT).show();\n\n }\n }\n });\n\n Button signupButton = binding.buttonSignup;\n signupButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n navigateToRegisterActivity();\n }\n });\n }\n\n /**\n * Navigates to the Main Activity.\n */\n private void navigateToMainActivity(){\n Intent intent = new Intent(getApplicationContext(), MainActivity.class);\n startActivity(intent);\n finish();\n }\n\n /**\n * Navigates to the Register Activity.\n */\n private void navigateToRegisterActivity(){\n Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);\n startActivity(intent);\n finish();\n }\n\n}" } ]
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import gr.ihu.geoapp.MainActivity; import gr.ihu.geoapp.R; import gr.ihu.geoapp.ui.signin.SignInActivity;
1,110
package gr.ihu.geoapp.ui; /** * This class represents the Splash Activity in the application. * It displays a splash screen for a short period of time before navigating to the Sign In Activity. */ public class SplashActivity extends AppCompatActivity { Handler handler = new Handler(); /** * Initializes the activity. * Sets up a delay before navigating to the Sign In Activity. * * @param savedInstanceState the saved instance state */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); handler.postDelayed(new Runnable() { @Override public void run() {
package gr.ihu.geoapp.ui; /** * This class represents the Splash Activity in the application. * It displays a splash screen for a short period of time before navigating to the Sign In Activity. */ public class SplashActivity extends AppCompatActivity { Handler handler = new Handler(); /** * Initializes the activity. * Sets up a delay before navigating to the Sign In Activity. * * @param savedInstanceState the saved instance state */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); handler.postDelayed(new Runnable() { @Override public void run() {
Intent intent = new Intent(getApplicationContext(), SignInActivity.class);
1
2023-11-10 17:43:18+00:00
2k
StanCEmpire/Enquestment
src/main/java/stancempire/enquestment/Enquestment.java
[ { "identifier": "ClientSetup", "path": "src/main/java/stancempire/enquestment/client/ClientSetup.java", "snippet": "public class ClientSetup\n{\n\n /**\n * Event for basic client setup tasks\n */\n @SubscribeEvent\n public void onClientSetup(final FMLClientSetupEvent event)\n {\n\n event.enqueueWork(() ->\n {\n\n Enquestment.LOGGER.info(\"Client Setup\");\n //CLIENT SETUP\n\n });\n\n }\n\n //Declare key mappings\n public static final Lazy<KeyMapping> EMENU_KEY = Lazy.of(() -> new KeyMapping(\"key.enquestment.emenu\", KeyConflictContext.IN_GAME, KeyModifier.ALT, InputConstants.Type.KEYSYM, GLFW.GLFW_KEY_E, \"key.categories.misc\"));\n\n /**\n * Event for registering custom keybinds\n */\n @SubscribeEvent\n public void registerKeybinds(RegisterKeyMappingsEvent event)\n {\n\n event.register(EMENU_KEY.get());\n\n }\n\n}" }, { "identifier": "UserEvents", "path": "src/main/java/stancempire/enquestment/events/UserEvents.java", "snippet": "public class UserEvents\n{\n\n /**\n * Checks for custom keybinds\n */\n @SubscribeEvent\n public void onKeyPressed(TickEvent.ClientTickEvent event)\n {\n\n if(event.phase == TickEvent.Phase.END) //Prevent logic from being executed twice\n {\n\n while(ClientSetup.EMENU_KEY.get().consumeClick()) //EMENU key\n {\n\n NetworkManager.NETWORK_INSTANCE.sendToServer(new SBRequestOpenGui(ModScreen.TEST));\n\n }\n\n }\n\n }\n\n}" }, { "identifier": "NetworkManager", "path": "src/main/java/stancempire/enquestment/network/NetworkManager.java", "snippet": "public class NetworkManager\n{\n\n private static final String PROTOCOL_VERSION = \"1\";\n public static final SimpleChannel NETWORK_INSTANCE = NetworkRegistry.newSimpleChannel(new ResourceLocation(Enquestment.MOD_ID, \"network\"), () -> PROTOCOL_VERSION, PROTOCOL_VERSION::equals, PROTOCOL_VERSION::equals);\n\n /**\n * Register packets\n */\n public static void registerMessages()\n {\n\n int id = 0;\n\n NETWORK_INSTANCE.registerMessage(id++, CBOpenGui.class, CBOpenGui::encode, CBOpenGui::new, CBOpenGui::handle);\n NETWORK_INSTANCE.registerMessage(id++, SBRequestOpenGui.class, SBRequestOpenGui::encode, SBRequestOpenGui::new, SBRequestOpenGui::handle);\n\n }\n\n}" } ]
import net.neoforged.bus.api.IEventBus; import net.neoforged.fml.common.Mod; import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent; import net.neoforged.fml.javafmlmod.FMLJavaModLoadingContext; import net.neoforged.fml.loading.FMLEnvironment; import net.neoforged.neoforge.common.NeoForge; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import stancempire.enquestment.client.ClientSetup; import stancempire.enquestment.events.UserEvents; import stancempire.enquestment.network.NetworkManager;
915
package stancempire.enquestment; /** * Mod entry point */ @Mod(Enquestment.MOD_ID) public class Enquestment { /**MOD LOGGER*/ public static final Logger LOGGER = LogManager.getLogger(); /**MOD_ID constant*/ public static final String MOD_ID = "enquestment"; public Enquestment() { //Buses IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus eventBus = NeoForge.EVENT_BUS; //Listen to setup events modBus.addListener(this::onCommonSetup); if(FMLEnvironment.dist.isClient()) //Dist check (client) { modBus.register(new ClientSetup()); } //Register event handlers
package stancempire.enquestment; /** * Mod entry point */ @Mod(Enquestment.MOD_ID) public class Enquestment { /**MOD LOGGER*/ public static final Logger LOGGER = LogManager.getLogger(); /**MOD_ID constant*/ public static final String MOD_ID = "enquestment"; public Enquestment() { //Buses IEventBus modBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus eventBus = NeoForge.EVENT_BUS; //Listen to setup events modBus.addListener(this::onCommonSetup); if(FMLEnvironment.dist.isClient()) //Dist check (client) { modBus.register(new ClientSetup()); } //Register event handlers
eventBus.register(new UserEvents());
1
2023-11-11 13:16:04+00:00
2k
ImShyMike/QuestCompassPlus
src/main/java/shymike/questcompassplus/commands/CommandRegister.java
[ { "identifier": "Config", "path": "src/main/java/shymike/questcompassplus/config/Config.java", "snippet": "public class Config {\n\tpublic static boolean isModEnabled = true;\n public static double x = 0, y = 0, z = 0;\n\tpublic static boolean chatFeedback = false;\n\tpublic static int color = 0;\n\tpublic static boolean waypointCopy = false;\n\tpublic static boolean requireCompass = true;\n\t\n\tstatic public void toggleIsModEnabled() { isModEnabled = !isModEnabled; onUpdate(); }\n\tstatic public void toggleChatFeedback() { chatFeedback = !chatFeedback; onUpdate(); }\n\tstatic public void toggleWaypointCopy() { waypointCopy = !waypointCopy; onUpdate(); }\n\tstatic public void toggleRequireCompass() { requireCompass = !requireCompass; onUpdate(); }\n\tstatic public void setCoordinates(double X, double Y, double Z) { x = X; y = Y; z = Z; onUpdate(); }\n\tstatic public void setColor(int value) { color = value; onUpdate(); }\n\t\n\tstatic private void onUpdate() {\n\t\t// TODO: save configs to file\n\t}\n}" }, { "identifier": "DistanceCalculator", "path": "src/main/java/shymike/questcompassplus/utils/DistanceCalculator.java", "snippet": "public class DistanceCalculator {\n public static double getDistance2D(double X, double Z, double x, double z) {\n return Math.sqrt(Math.pow(x - X, 2) + Math.pow(z - Z, 2));\n }\n \n public static double getDistance3D(double X, double Y, double Z, double x, double y, double z) {\n return Math.sqrt(Math.pow(x - X, 2) + Math.pow(y - Y, 2) + Math.pow(z - Z, 2));\n }\n}" }, { "identifier": "RenderUtils", "path": "src/main/java/shymike/questcompassplus/utils/RenderUtils.java", "snippet": "public class RenderUtils implements HudRenderCallback {\n\tMinecraftClient mc = MinecraftClient.getInstance();\n\tpublic static String line1 = \"Compass Position: 0 0 0\";\n\tpublic static String line2 = \"\";\n\tpublic static double x = 0, y = 0, z = 0;\n\tpublic static String mainHandItem = null;\n\tpublic static boolean isDebugHudEnabled = false;\n\n public static void setCoordinates(double x, double y, double z) {\n \tRenderUtils.x = x;\n \tRenderUtils.y = y;\n \tRenderUtils.z = z;\n }\n \n @Override\n public void onHudRender(MatrixStack matrixStack, float tickDelta) {\n \tif (Config.requireCompass == true) {\n\t\t\tmainHandItem = mc.player.getInventory().getMainHandStack().getItem().toString();\n \t} else { mainHandItem = \"compass\"; }\n \ttry {\n \t\tGameOptions gameOptions = mc.options;\n \t\tRenderUtils.isDebugHudEnabled = gameOptions.debugEnabled;\n \t} catch(Exception e) {\n \t\tRenderUtils.isDebugHudEnabled = false;\n \t}\n \tif (Config.isModEnabled && ServerUtils.isOnMonumenta() && !isDebugHudEnabled && mainHandItem == \"compass\") {\n\t int x = 10, y = 10;\n\t int color = Config.color;\n\t Vec3d playerPos = mc.player.getPos();\n\t \tdouble distance = Math.round(DistanceCalculator.getDistance2D(playerPos.x, playerPos.z, RenderUtils.x, RenderUtils.z));\n\t \tline2 = \"Distance: \" + (int)distance;\n\t \tString[] lines = {line1, line2};\n\t \tfor (String line : lines) {\n\t\t\t\tTextRenderer textRenderer = mc.textRenderer;\n\t \tText formattedText = Text.literal(line).formatted(Formatting.WHITE);;\n\t DrawableHelper.drawTextWithShadow(matrixStack, textRenderer, formattedText, x, y, color);\n\t y += textRenderer.fontHeight;\n\t \t}\n }\n }\n}" }, { "identifier": "ServerUtils", "path": "src/main/java/shymike/questcompassplus/utils/ServerUtils.java", "snippet": "public class ServerUtils {\n\tpublic static boolean bypass = false;\n\tprivate static MinecraftClient mc = MinecraftClient.getInstance();\n\t\n\tpublic static boolean isOnMonumenta() {\n\t if (bypass != true) {\n\t\t if (mc.getNetworkHandler() != null && mc.player != null) {\n\t\t ServerInfo serverInfo = mc.getCurrentServerEntry();\n\t\n\t\t String ServerAddress = \"server.playmonumenta.com\";\n\t\t return serverInfo != null && serverInfo.address.equals(ServerAddress) && !mc.isInSingleplayer();\n\t\t }\n\t } else { return true; }\n\t \n\t return false;\n\t}\n}" } ]
import shymike.questcompassplus.config.Config; import shymike.questcompassplus.utils.DistanceCalculator; import shymike.questcompassplus.utils.RenderUtils; import shymike.questcompassplus.utils.ServerUtils; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.tree.LiteralCommandNode; import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager; import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback; import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource; import net.minecraft.client.MinecraftClient; import net.minecraft.text.ClickEvent; import net.minecraft.text.HoverEvent; import net.minecraft.text.Text; import net.minecraft.util.math.Vec3d;
1,572
package shymike.questcompassplus.commands; //import net.minecraft.command.argument.NumberRangeArgumentType; //import net.minecraft.command.argument.NumberRangeArgumentType.IntRangeArgumentType; public class CommandRegister { static public void run() { MinecraftClient mc = MinecraftClient.getInstance(); ClientCommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> { LiteralCommandNode<FabricClientCommandSource> mainNode = ClientCommandManager .literal("qcp") .executes(context -> { throw new SimpleCommandExceptionType(Text.literal("Invalid usage. Use \"/qcp help\" for more information.")).create(); }) .build(); LiteralCommandNode<FabricClientCommandSource> helpNode = ClientCommandManager .literal("help") .executes(context -> { context.getSource().sendFeedback(Text.literal("Quest Compass Plus commands:")); context.getSource().sendFeedback(Text.literal("/qcp help - Display this help message")); context.getSource().sendFeedback(Text.literal("/qcp toggle - Toggle the mod on/off")); context.getSource().sendFeedback(Text.literal("/qcp get - Get current quest location")); context.getSource().sendFeedback(Text.literal("/qcp settings - Change settings")); context.getSource().sendFeedback(Text.literal("/qcp debug - For debugging")); return 1; }) .build(); LiteralCommandNode<FabricClientCommandSource> toggleNode = ClientCommandManager .literal("toggle") .executes(context -> { Config.toggleIsModEnabled();
package shymike.questcompassplus.commands; //import net.minecraft.command.argument.NumberRangeArgumentType; //import net.minecraft.command.argument.NumberRangeArgumentType.IntRangeArgumentType; public class CommandRegister { static public void run() { MinecraftClient mc = MinecraftClient.getInstance(); ClientCommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> { LiteralCommandNode<FabricClientCommandSource> mainNode = ClientCommandManager .literal("qcp") .executes(context -> { throw new SimpleCommandExceptionType(Text.literal("Invalid usage. Use \"/qcp help\" for more information.")).create(); }) .build(); LiteralCommandNode<FabricClientCommandSource> helpNode = ClientCommandManager .literal("help") .executes(context -> { context.getSource().sendFeedback(Text.literal("Quest Compass Plus commands:")); context.getSource().sendFeedback(Text.literal("/qcp help - Display this help message")); context.getSource().sendFeedback(Text.literal("/qcp toggle - Toggle the mod on/off")); context.getSource().sendFeedback(Text.literal("/qcp get - Get current quest location")); context.getSource().sendFeedback(Text.literal("/qcp settings - Change settings")); context.getSource().sendFeedback(Text.literal("/qcp debug - For debugging")); return 1; }) .build(); LiteralCommandNode<FabricClientCommandSource> toggleNode = ClientCommandManager .literal("toggle") .executes(context -> { Config.toggleIsModEnabled();
if (!Config.isModEnabled) { RenderUtils.line1 = ""; RenderUtils.line2 = ""; } else { RenderUtils.line1 = "Compass Position: " + (int)RenderUtils.x + " " + (int)RenderUtils.y + " " + (int)RenderUtils.z; }
2
2023-11-14 15:56:39+00:00
2k
kawainime/IOT-Smart_Farming
IOT_Farm_V.2/src/UI/Settings.java
[ { "identifier": "Cache_Writer", "path": "IOT_Farm_V.2/src/Core/Background/Cache_Writer.java", "snippet": "public class Cache_Writer\n{\n public static String add_data(String city_name,String db_file) throws IOException\n {\n String file_name = db_file;\n \n FileOutputStream details = new FileOutputStream(file_name);\n\n PrintWriter file = new PrintWriter(details);\n\n BufferedWriter store = new BufferedWriter(file);\n\n store.write(city_name);\n \n store.newLine();\n\n store.close();\n\n file.close();\n\n System.out.print(\"Data Successfully Entered To \"+file_name+\"\\n\");\n \n String message = \"Data Successfully Entered To \"+file_name;\n \n return message;\n\n }\n}" }, { "identifier": "Load_Settings", "path": "IOT_Farm_V.2/src/Core/SQL_Lite3/Load_Settings.java", "snippet": "public class Load_Settings \n{\n public static String load_data(String setting_type)\n {\n String value = null;\n \n String SQL = \"SELECT VALUE FROM MY_SQL WHERE TITLE = '\"+setting_type+\"';\";\n \n Connection connection = Lite_Connector.connect_config();\n \n try\n {\n Statement stmt = connection.createStatement();\n \n ResultSet rs = stmt.executeQuery(SQL);\n \n while(rs.next())\n {\n value = rs.getString(\"VALUE\");\n }\n \n return Decryption.decrypt(value);\n }\n catch(Exception ERROR)\n {\n return \"settings_not_found\";\n }\n }\n \n public static String load_table(String setting_type)\n {\n String value = null;\n \n String SQL = \"SELECT VALUE FROM SETTINGS WHERE SETTING_TYPE = '\"+setting_type+\"';\";\n \n Connection connection = Lite_Connector.connect_config();\n \n try\n {\n Statement stmt = connection.createStatement();\n \n ResultSet rs = stmt.executeQuery(SQL);\n \n while(rs.next())\n {\n value = rs.getString(\"VALUE\");\n }\n \n return Decryption.decrypt(value);\n }\n catch(Exception ERROR)\n {\n return \"settings_not_found\";\n }\n }\n}" }, { "identifier": "Save_SQL", "path": "IOT_Farm_V.2/src/Core/SQL_Lite3/Save_SQL.java", "snippet": "public class Save_SQL \n{\n public static int save_settings(String value_1,String value_2,String value_3,String value_4,String value_5)\n {\n Connection connection = Lite_Connector.connect_config();\n \n String SQL_1 = \"UPDATE MY_SQL SET VALUE = '\"+Encryption.encrypt(value_1)+\"' WHERE TITLE = 'HOST';\";\n \n String SQL_2 = \"UPDATE MY_SQL SET VALUE = '\"+Encryption.encrypt(value_2)+\"' WHERE TITLE = 'PORT';\";\n \n String SQL_3 = \"UPDATE MY_SQL SET VALUE = '\"+Encryption.encrypt(value_3)+\"' WHERE TITLE = 'UNAME';\";\n \n String SQL_4 = \"UPDATE MY_SQL SET VALUE = '\"+Encryption.encrypt(value_4)+\"' WHERE TITLE = 'DBNAME';\";\n \n String SQL_5 = \"UPDATE MY_SQL SET VALUE = '\"+Encryption.encrypt(value_5)+\"' WHERE TITLE = 'PASSWORD';\";\n \n try\n {\n PreparedStatement preparedStatement = connection.prepareStatement(SQL_1);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_1);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_2);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_3);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_4);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_5);\n\n preparedStatement.executeUpdate();\n \n return 1;\n }\n catch(Exception ERROR)\n {\n System.out.println(ERROR);\n \n return 0;\n }\n }\n}" }, { "identifier": "Save_Settings", "path": "IOT_Farm_V.2/src/Core/SQL_Lite3/Save_Settings.java", "snippet": "public class Save_Settings \n{\n public static int save_settings(String value_1,String value_2,String value_3)\n {\n Connection connection = Lite_Connector.connect_config();\n \n String SQL_1 = \"UPDATE SETTINGS SET VALUE = '\"+Encryption.encrypt(value_1)+\"' WHERE SETTING_TYPE = 'LINK1';\";\n \n String SQL_2 = \"UPDATE SETTINGS SET VALUE = '\"+Encryption.encrypt(value_2)+\"' WHERE SETTING_TYPE = 'LINK2';\";\n \n String SQL_3 = \"UPDATE SETTINGS SET VALUE = '\"+Encryption.encrypt(value_3)+\"' WHERE SETTING_TYPE = 'LINK3';\";\n \n try\n {\n PreparedStatement preparedStatement = connection.prepareStatement(SQL_1);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_1);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_2);\n\n preparedStatement.executeUpdate();\n \n preparedStatement = connection.prepareStatement(SQL_3);\n\n preparedStatement.executeUpdate();\n \n return 1;\n }\n catch(Exception ERROR)\n {\n System.out.println(ERROR);\n \n return 0;\n }\n }\n}" } ]
import Core.Background.Cache_Writer; import Core.SQL_Lite3.Load_Settings; import Core.SQL_Lite3.Save_SQL; import Core.SQL_Lite3.Save_Settings; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.plaf.basic.BasicInternalFrameUI;
1,594
/* * 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 Settings extends javax.swing.JInternalFrame { /** * Creates new form Welcome */ public Settings() { initComponents(); this.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); BasicInternalFrameUI bis = (BasicInternalFrameUI) this.getUI(); bis.setNorthPane(null); load_settings(); } public void load_settings() { jTextField5.setText(Load_Settings.load_data("HOST")); jTextField7.setText(Load_Settings.load_data("PORT")); jTextField8.setText(Load_Settings.load_data("DBNAME")); jPasswordField1.setText(Load_Settings.load_data("PASSWORD")); jTextField9.setText(Load_Settings.load_data("UNAME")); jTextField2.setText(Load_Settings.load_table("LINK1")); jTextField3.setText(Load_Settings.load_table("LINK2")); jTextField4.setText(Load_Settings.load_table("LINK3")); try { comboBoxSuggestion1.setSelectedItem(Core.Background.Cache_Reader.data("City.dat")); comboBoxSuggestion2.setSelectedItem(Core.Background.Cache_Reader.data("Crop.dat")); } catch(Exception error) { Core.Background.Bugs_Log.exceptions(String.valueOf(error)); } } public void save_settings() {
/* * 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 Settings extends javax.swing.JInternalFrame { /** * Creates new form Welcome */ public Settings() { initComponents(); this.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0)); BasicInternalFrameUI bis = (BasicInternalFrameUI) this.getUI(); bis.setNorthPane(null); load_settings(); } public void load_settings() { jTextField5.setText(Load_Settings.load_data("HOST")); jTextField7.setText(Load_Settings.load_data("PORT")); jTextField8.setText(Load_Settings.load_data("DBNAME")); jPasswordField1.setText(Load_Settings.load_data("PASSWORD")); jTextField9.setText(Load_Settings.load_data("UNAME")); jTextField2.setText(Load_Settings.load_table("LINK1")); jTextField3.setText(Load_Settings.load_table("LINK2")); jTextField4.setText(Load_Settings.load_table("LINK3")); try { comboBoxSuggestion1.setSelectedItem(Core.Background.Cache_Reader.data("City.dat")); comboBoxSuggestion2.setSelectedItem(Core.Background.Cache_Reader.data("Crop.dat")); } catch(Exception error) { Core.Background.Bugs_Log.exceptions(String.valueOf(error)); } } public void save_settings() {
int val_0 = Save_SQL.save_settings(jTextField5.getText(), jTextField7.getText(), jTextField9.getText(), jTextField8.getText(), jPasswordField1.getText());
2
2023-11-11 08:23:10+00:00
2k
Outer-Fields/item-server
src/main/java/io/mindspice/itemserver/services/AvatarService.java
[ { "identifier": "CustomLogger", "path": "src/main/java/io/mindspice/itemserver/util/CustomLogger.java", "snippet": "public class CustomLogger implements TLogger {\n private static final Logger MINT_LOG = LoggerFactory.getLogger(\"MINT\");\n private static final Logger FAILED_LOG = LoggerFactory.getLogger(\"FAILED\");\n private static final Logger APP_LOG = LoggerFactory.getLogger(\"APP\");\n\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg);\n case INFO -> APP_LOG.info(msg);\n case WARNING -> APP_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> APP_LOG.debug(msg);\n }\n }\n\n public void logApp(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> APP_LOG.error(msg, e);\n case INFO -> APP_LOG.info(msg, e);\n case WARNING -> APP_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> APP_LOG.debug(msg, e);\n }\n }\n\n\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg);\n case INFO -> MINT_LOG.info(msg);\n case WARNING -> MINT_LOG.warn(msg);\n case FAILED -> FAILED_LOG.error(msg);\n case DEBUG -> MINT_LOG.debug(msg);\n }\n }\n\n @Override\n public void log(Class<?> aClass, TLogLevel tLogLevel, String s, Exception e) {\n String msg = String.format(\"%s - %s\", aClass.getName(), s);\n switch (tLogLevel) {\n case ERROR -> MINT_LOG.error(msg, e);\n case INFO -> MINT_LOG.info(msg, e);\n case WARNING -> MINT_LOG.warn(msg, e);\n case FAILED -> FAILED_LOG.error(msg, e);\n case DEBUG -> MINT_LOG.debug(msg, e);\n }\n }\n}" }, { "identifier": "Utils", "path": "src/main/java/io/mindspice/itemserver/util/Utils.java", "snippet": "public class Utils {\n\n public static NftInfo nftGetInfoWrapper(WalletAPI walletAPI, String coinId) throws RPCException, InterruptedException {\n int i = 100;\n Thread.sleep(10);\n ApiResponse<NftInfo> info = walletAPI.nftGetInfo(coinId);\n while(!info.success() && i > 0) {\n Thread.sleep(50);\n info = walletAPI.nftGetInfo(coinId);\n i--;\n }\n if (info.success()) {\n return info.data().get();\n } else {\n throw new IllegalStateException(\"Failed to get nft info after 20 tries\");\n }\n }\n\n public static String uidFromUrl(String url) {\n String[] parts = url.split(\"/\");\n String lastPart = parts[parts.length - 1];\n return lastPart.replace(\".png\", \"\");\n }\n\n}" } ]
import io.mindspice.databaseservice.client.api.OkraGameAPI; import io.mindspice.itemserver.util.CustomLogger; import io.mindspice.itemserver.util.Utils; import io.mindspice.jxch.rpc.http.WalletAPI; import io.mindspice.jxch.rpc.schemas.wallet.nft.NftInfo; import io.mindspice.jxch.transact.logging.TLogLevel; import io.mindspice.mindlib.data.tuples.Pair; import io.mindspice.mindlib.http.UnsafeHttpClient; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.awt.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.time.Instant; import java.util.Iterator; import java.util.List; import java.util.UUID;
1,026
package io.mindspice.itemserver.services; //TODO make logging make logging follow existing practices for formatting public class AvatarService { private final WalletAPI walletAPI; private final OkraGameAPI gameApi;
package io.mindspice.itemserver.services; //TODO make logging make logging follow existing practices for formatting public class AvatarService { private final WalletAPI walletAPI; private final OkraGameAPI gameApi;
private final CustomLogger logger;
0
2023-11-14 14:56:37+00:00
2k
KvRae/Mobile-Exemple-Java-Android
Project/app/src/main/java/com/example/pharmacie2/Views/Activities/SignInActivity.java
[ { "identifier": "UserDao", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Dao/UserDao.java", "snippet": "@Dao\npublic interface UserDao {\n @Insert\n void insert(User user);\n @Delete\n void delete(User user);\n\n @Query(\"SELECT * FROM users WHERE email = :email\")\n User getUserByEmail(String email);\n\n @Query(\"SELECT * FROM users WHERE email = :email AND password = :password\")\n User getUserByEmailAndPassword(String email, String password);\n @Query(\"SELECT * FROM users\")\n List<User> getAllUsers();\n\n @Query(\"SELECT * FROM users WHERE id = :id\")\n User getUserById(int id);\n\n @Update\n void updateUser(User user);\n\n\n}" }, { "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 private static PharmacyDB instance;\n\n public abstract UserDao userDao();\n\n public abstract MedicamentDao medicamentDao();\n public abstract MedecinDao medecinDao();\n\n public static synchronized PharmacyDB getInstance(Context context) {\n if (instance == null) {\n instance = Room.databaseBuilder(\n context.getApplicationContext(),\n PharmacyDB.class,\n \"user_database,medicament_database,medecin_database\"\n\n )\n .fallbackToDestructiveMigration()\n .build();\n }\n return instance;\n }\n}" }, { "identifier": "User", "path": "Project/app/src/main/java/com/example/pharmacie2/Data/Entities/User.java", "snippet": "@Entity(tableName = \"users\")\npublic class User {\n public String getEmail;\n @PrimaryKey(autoGenerate = true)\n private int id;\n\n private String name;\n private String email;\n\n private String password;\n\n\n\n public User(String email) {\n this.email = email;\n }\n public User(String email, String password) {\n this.name = email;\n this.email = password;\n }\n\n public User(String name, String email, String password) {\n this.name = name;\n this.email = email;\n this.password = password;\n }\n\n public User() {\n }\n\n\n\n // Getters and setters\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n User user = (User) o;\n return id == user.id && Objects.equals(getEmail, user.getEmail) && Objects.equals(name, user.name) && Objects.equals(email, user.email) && Objects.equals(password, user.password);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(getEmail, id, name, email, password);\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"getEmail='\" + getEmail + '\\'' +\n \", id=\" + id +\n \", name='\" + name + '\\'' +\n \", email='\" + email + '\\'' +\n \", password='\" + password + '\\'' +\n '}';\n }\n}" } ]
import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.pharmacie2.Data.Dao.UserDao; import com.example.pharmacie2.Data.Database.PharmacyDB; import com.example.pharmacie2.Data.Entities.User; import com.example.pharmacie2.R;
1,234
package com.example.pharmacie2.Views.Activities; public class SignInActivity extends AppCompatActivity { Button signInBtn; TextView createaccount ; private EditText editTextEmail; private EditText editTextPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); signInBtn = findViewById(R.id.buttonSignIn); createaccount = findViewById(R.id.createaccount); editTextEmail = findViewById(R.id.editTextEmail); editTextPassword = findViewById(R.id.editTextPassword); signInBtn.setOnClickListener(v -> { String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); new AuthenticateUserTask().execute(email, password); }); createaccount.setOnClickListener( e -> { Intent intent = new Intent(this, SignUpActivity.class); startActivity(intent); finish(); Toast.makeText(this, "Welcome",Toast.LENGTH_SHORT).show(); } ); }
package com.example.pharmacie2.Views.Activities; public class SignInActivity extends AppCompatActivity { Button signInBtn; TextView createaccount ; private EditText editTextEmail; private EditText editTextPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_in); signInBtn = findViewById(R.id.buttonSignIn); createaccount = findViewById(R.id.createaccount); editTextEmail = findViewById(R.id.editTextEmail); editTextPassword = findViewById(R.id.editTextPassword); signInBtn.setOnClickListener(v -> { String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); new AuthenticateUserTask().execute(email, password); }); createaccount.setOnClickListener( e -> { Intent intent = new Intent(this, SignUpActivity.class); startActivity(intent); finish(); Toast.makeText(this, "Welcome",Toast.LENGTH_SHORT).show(); } ); }
private class AuthenticateUserTask extends AsyncTask<String, Void, User> {
2
2023-11-14 22:07:33+00:00
2k
CodecNomad/CodecClient
src/main/java/com/github/codecnomad/codecclient/ui/Config.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();\n public static Rotation rotation = new Rotation();\n public static Config guiConfig;\n\n static {\n modules.put(\"FishingMacro\", new FishingMacro());\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n guiConfig = new Config();\n\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(rotation);\n\n MinecraftForge.EVENT_BUS.register(MainCommand.pathfinding);\n\n CommandManager.register(new MainCommand());\n }\n\n @SubscribeEvent\n public void disconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) {\n for (Map.Entry<String, Module> moduleMap : modules.entrySet()) {\n moduleMap.getValue().unregister();\n }\n }\n}" }, { "identifier": "Module", "path": "src/main/java/com/github/codecnomad/codecclient/modules/Module.java", "snippet": "public class Module {\n public boolean state;\n\n public void register() {\n MinecraftForge.EVENT_BUS.register(this);\n this.state = true;\n }\n\n public void unregister() {\n MinecraftForge.EVENT_BUS.unregister(this);\n this.state = false;\n }\n}" } ]
import cc.polyfrost.oneconfig.config.annotations.Number; import cc.polyfrost.oneconfig.config.annotations.*; import cc.polyfrost.oneconfig.config.core.OneColor; import cc.polyfrost.oneconfig.config.core.OneKeyBind; import cc.polyfrost.oneconfig.config.data.Mod; import cc.polyfrost.oneconfig.config.data.ModType; import com.github.codecnomad.codecclient.Client; import com.github.codecnomad.codecclient.modules.Module; import org.lwjgl.input.Keyboard;
1,078
package com.github.codecnomad.codecclient.ui; @SuppressWarnings("unused") public class Config extends cc.polyfrost.oneconfig.config.Config { @Color( name = "Color", category = "Visuals" ) public static OneColor VisualColor = new OneColor(100, 60, 160, 200); @KeyBind( name = "Fishing key-bind", category = "Macros", subcategory = "Fishing" ) public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F); @Number( name = "Catch delay", category = "Macros", subcategory = "Fishing", min = 1, max = 20 ) public static int FishingDelay = 10; @Number( name = "Kill delay", category = "Macros", subcategory = "Fishing", min = 1, max = 40 ) public static int KillDelay = 20; @Number( name = "Attack c/s", category = "Macros", subcategory = "Fishing", min = 5, max = 20 ) public static int AttackCps = 10; @Number( name = "Smoothing", category = "Macros", subcategory = "Fishing", min = 2, max = 10 ) public static int RotationSmoothing = 4; @Number( name = "Random movement frequency", category = "Macros", subcategory = "Fishing", min = 5, max = 50 ) public static int MovementFrequency = 15; @Switch( name = "Auto kill", category = "Macros", subcategory = "Fishing" ) public static boolean AutoKill = true; @Switch( name = "Only sound failsafe", category = "Macros", subcategory = "Fishing" ) public static boolean OnlySound = false; @Number( name = "Weapon slot", category = "Macros", subcategory = "Fishing", min = 1, max = 9 ) public static int WeaponSlot = 9; @Switch( name = "Right click attack", category = "Macros", subcategory = "Fishing" ) public static boolean RightClick = false; @HUD( name = "Fishing HUD", category = "Visuals" ) public FishingHud hudFishing = new FishingHud(); public Config() { super(new Mod("CodecClient", ModType.UTIL_QOL), "config.json"); initialize(); registerKeyBind(FishingKeybinding, () -> toggle("FishingMacro")); save(); } private static void toggle(String name) {
package com.github.codecnomad.codecclient.ui; @SuppressWarnings("unused") public class Config extends cc.polyfrost.oneconfig.config.Config { @Color( name = "Color", category = "Visuals" ) public static OneColor VisualColor = new OneColor(100, 60, 160, 200); @KeyBind( name = "Fishing key-bind", category = "Macros", subcategory = "Fishing" ) public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F); @Number( name = "Catch delay", category = "Macros", subcategory = "Fishing", min = 1, max = 20 ) public static int FishingDelay = 10; @Number( name = "Kill delay", category = "Macros", subcategory = "Fishing", min = 1, max = 40 ) public static int KillDelay = 20; @Number( name = "Attack c/s", category = "Macros", subcategory = "Fishing", min = 5, max = 20 ) public static int AttackCps = 10; @Number( name = "Smoothing", category = "Macros", subcategory = "Fishing", min = 2, max = 10 ) public static int RotationSmoothing = 4; @Number( name = "Random movement frequency", category = "Macros", subcategory = "Fishing", min = 5, max = 50 ) public static int MovementFrequency = 15; @Switch( name = "Auto kill", category = "Macros", subcategory = "Fishing" ) public static boolean AutoKill = true; @Switch( name = "Only sound failsafe", category = "Macros", subcategory = "Fishing" ) public static boolean OnlySound = false; @Number( name = "Weapon slot", category = "Macros", subcategory = "Fishing", min = 1, max = 9 ) public static int WeaponSlot = 9; @Switch( name = "Right click attack", category = "Macros", subcategory = "Fishing" ) public static boolean RightClick = false; @HUD( name = "Fishing HUD", category = "Visuals" ) public FishingHud hudFishing = new FishingHud(); public Config() { super(new Mod("CodecClient", ModType.UTIL_QOL), "config.json"); initialize(); registerKeyBind(FishingKeybinding, () -> toggle("FishingMacro")); save(); } private static void toggle(String name) {
Module helperClassModule = Client.modules.get(name);
0
2023-11-16 10:12:20+00:00
2k
Mightinity/store-management-system
src/main/java/com/systeminventory/controller/cashierProfileCardController.java
[ { "identifier": "DeleteCashierListener", "path": "src/main/java/com/systeminventory/interfaces/DeleteCashierListener.java", "snippet": "public interface DeleteCashierListener {\n public void clickDeleteCashierListener(Cashier cashier);\n}" }, { "identifier": "EditCashierListener", "path": "src/main/java/com/systeminventory/interfaces/EditCashierListener.java", "snippet": "public interface EditCashierListener {\n public void clickEditCashierListener(Cashier cashier);\n}" }, { "identifier": "ProfileDetailsListener", "path": "src/main/java/com/systeminventory/interfaces/ProfileDetailsListener.java", "snippet": "public interface ProfileDetailsListener {\n public void clickProfileDetailsListener(Cashier cashier);\n}" }, { "identifier": "Cashier", "path": "src/main/java/com/systeminventory/model/Cashier.java", "snippet": "public class Cashier {\n\n private String cashierName;\n private String cashierNoPhone;\n private String cashierImageSource;\n private String cashierEmail;\n private String cashierPassword;\n private String cashierDateOfBirth;\n private String cashierAddress;\n\n private String keyCashier;\n\n public String getCashierName() {\n return cashierName;\n }\n\n public void setCashierName(String cashierName) {\n this.cashierName = cashierName;\n }\n\n public String getCashierNoPhone() {\n return cashierNoPhone;\n }\n\n public void setCashierNoPhone(String cashierNoPhone) {\n this.cashierNoPhone = cashierNoPhone;\n }\n\n public String getCashierImageSource() {\n return cashierImageSource;\n }\n\n public void setCashierImageSource(String cashierImageSource) {\n this.cashierImageSource = cashierImageSource;\n }\n\n public String getCashierEmail() {\n return cashierEmail;\n }\n\n public void setCashierEmail(String cashierEmail) {\n this.cashierEmail = cashierEmail;\n }\n\n public String getCashierPassword() {\n return cashierPassword;\n }\n\n public void setCashierPassword(String cashierPassword) {\n this.cashierPassword = cashierPassword;\n }\n\n public String getCashierDateOfBirth() {\n return cashierDateOfBirth;\n }\n\n public void setCashierDateOfBirth(String cashierDateOfBirth) {\n this.cashierDateOfBirth = cashierDateOfBirth;\n }\n\n public String getCashierAddress() {\n return cashierAddress;\n }\n\n public void setCashierAddress(String cashierAddress) {\n this.cashierAddress = cashierAddress;\n }\n\n public String getKeyCashier() {\n return keyCashier;\n }\n\n public void setKeyCashier(String keyCashier) {\n this.keyCashier = keyCashier;\n }\n}" } ]
import com.systeminventory.interfaces.DeleteCashierListener; import com.systeminventory.interfaces.EditCashierListener; import com.systeminventory.interfaces.ProfileDetailsListener; import com.systeminventory.model.Cashier; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import java.io.*;
816
package com.systeminventory.controller; public class cashierProfileCardController { @FXML private ImageView profileCardImage; @FXML private Label profileCardName; @FXML private Label profileCardNoPhone; @FXML private Label profileCardEmail; @FXML private AnchorPane cashierProfileBackground; @FXML private Label keyCashierProfile; private Cashier cashier;
package com.systeminventory.controller; public class cashierProfileCardController { @FXML private ImageView profileCardImage; @FXML private Label profileCardName; @FXML private Label profileCardNoPhone; @FXML private Label profileCardEmail; @FXML private AnchorPane cashierProfileBackground; @FXML private Label keyCashierProfile; private Cashier cashier;
private ProfileDetailsListener profileDetailsListener;
2
2023-11-18 02:53:02+00:00
2k
dsntk/dsntk-java-server
src/main/java/io/dsntk/server/rest/controllers/RpcController.java
[ { "identifier": "ResultDto", "path": "src/main/java/io/dsntk/server/rest/dto/ResultDto.java", "snippet": "@Getter\npublic class ResultDto<T> {\n\n /** Data sent as a result. */\n @JsonProperty(\"data\")\n private T data;\n\n /**\n * Creates a new DTO object containing result data.\n *\n * @param data Result data.\n */\n public ResultDto(T data) {\n this.data = data;\n }\n}" }, { "identifier": "ValueDto", "path": "src/main/java/io/dsntk/server/rest/dto/ValueDto.java", "snippet": "@Getter\n@Setter\npublic class ValueDto {\n\n /** Simple value. */\n @JsonProperty(\"simple\")\n private SimpleDto simple;\n\n /** Object value. */\n @JsonProperty(\"components\")\n private ArrayList<ComponentDto> object;\n\n /** List value. */\n @JsonProperty(\"list\")\n private ListDto list;\n\n public Object toObject(Class<?> castClass) throws RpcException {\n if (this.simple != null) {\n return this.simple.toObject(castClass);\n }\n return null;\n }\n\n public static ValueDto fromObject(Object object) throws RpcException {\n CastType castType = CastType.fromClass(object.getClass());\n if (castType.isPrimitive()) {\n return simple(object, castType);\n }\n throw new RpcException(String.format(\"value conversion failed from object class %s\", object.getClass().getName()));\n }\n\n private static ValueDto simple(Object object, CastType castType) throws RpcException {\n ValueDto valueDto = new ValueDto();\n valueDto.simple = SimpleDto.fromObject(object, castType);\n return valueDto;\n }\n}" }, { "identifier": "RpcException", "path": "src/main/java/io/dsntk/server/rest/errors/RpcException.java", "snippet": "public class RpcException extends Exception {\n\n /**\n * Creates RPC exception.\n *\n * @param details Reason of the exception.\n */\n public RpcException(String details) {\n super(details);\n }\n}" }, { "identifier": "RpcParams", "path": "src/main/java/io/dsntk/server/rest/params/RpcParams.java", "snippet": "@Getter\n@Setter\npublic class RpcParams {\n /** Name of the class where called static method is defined. */\n @JsonProperty(\"className\")\n private String className;\n\n /** Name of the method to be called. */\n @JsonProperty(\"methodName\")\n private String methodName;\n\n @JsonProperty(\"parameterTypes\")\n private ArrayList<String> parameterTypes;\n\n @JsonProperty(\"arguments\")\n private ArrayList<ValueDto> arguments;\n}" }, { "identifier": "RpcService", "path": "src/main/java/io/dsntk/server/services/RpcService.java", "snippet": "@Slf4j\n@Service\npublic class RpcService {\n\n /**\n * Collection of classes for primitive types.\n */\n private static final Map<String, Class<?>> PRIMITIVE_CLASSES = (\n Collections.unmodifiableMap(\n new HashMap<>() {\n {\n for (Class<?> cls : new Class<?>[]{\n boolean.class,\n char.class,\n byte.class,\n short.class,\n int.class,\n long.class,\n float.class,\n double.class\n }) {\n put(cls.getName(), cls);\n }\n }\n }\n )\n );\n\n public ValueDto evaluate(String className, String methodName, List<String> parameterTypes, List<ValueDto> arguments) throws RpcException {\n try {\n // prepare a class containing called method definition\n Class<?> classObject = Class.forName(className);\n // prepare classes for argument types\n ArrayList<Class<?>> argument_types = new ArrayList<>();\n for (String typeName : parameterTypes) {\n if (PRIMITIVE_CLASSES.containsKey(typeName)) {\n argument_types.add(PRIMITIVE_CLASSES.get(typeName));\n } else {\n argument_types.add(Class.forName(typeName));\n }\n }\n // prepare argument values\n ArrayList<Object> argument_values = new ArrayList<>();\n for (int i = 0; i < arguments.size(); i++) {\n ValueDto valueDto = arguments.get(i);\n Class<?> castType = argument_types.get(i);\n Object obj = valueDto.toObject(castType);\n argument_values.add(obj);\n }\n // invoke the method\n Method method = classObject.getMethod(methodName, argument_types.toArray(new Class<?>[0]));\n Object result = method.invoke(null, argument_values.toArray(new Object[0]));\n // convert the result into value abd return to caller\n return ValueDto.fromObject(result);\n } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException e) {\n throw new RpcException(e.toString());\n } catch (InvocationTargetException e) {\n throw new RpcException(e.getCause().toString());\n }\n }\n}" } ]
import io.dsntk.server.rest.dto.ResultDto; import io.dsntk.server.rest.dto.ValueDto; import io.dsntk.server.rest.errors.RpcException; import io.dsntk.server.rest.params.RpcParams; import io.dsntk.server.services.RpcService; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
1,252
package io.dsntk.server.rest.controllers; /** * Java RPC controller. */ @Slf4j @RestController @RequestMapping(RequestMappings.M_RPC_SERVER) public class RpcController {
package io.dsntk.server.rest.controllers; /** * Java RPC controller. */ @Slf4j @RestController @RequestMapping(RequestMappings.M_RPC_SERVER) public class RpcController {
private final RpcService rpcService;
4
2023-11-10 18:06:05+00:00
2k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/commands/ServerCommand.java
[ { "identifier": "PScanRunner", "path": "src/main/java/anticope/rejects/utils/portscanner/PScanRunner.java", "snippet": "public class PScanRunner {\n public boolean running = true;\n public int portsScanned = 0;\n ExecutorService es;\n List<Future<PortScannerManager.ScanResult>> futures = new ArrayList<>();\n Thread runner;\n\n public PScanRunner(InetAddress address, int threads, int threadDelay, int timeoutMS, Collection<Integer> ports,\n Consumer<List<PortScannerManager.ScanResult>> callback) {\n runner = new Thread(() -> {\n es = Executors.newFixedThreadPool(threads);\n ports.forEach(port -> {\n futures.add(isPortOpen(es, address.getHostAddress(), port, timeoutMS, threadDelay));\n });\n try {\n es.awaitTermination(200L, TimeUnit.MILLISECONDS);\n } catch (InterruptedException ignored) {\n }\n List<PortScannerManager.ScanResult> results = new ArrayList<>();\n for (Future<PortScannerManager.ScanResult> fsc : futures) {\n try {\n results.add(fsc.get());\n } catch (InterruptedException | ExecutionException e) {\n e.printStackTrace();\n }\n }\n callback.accept(results);\n });\n runner.start();\n }\n\n public void cancel() {\n running = false;\n }\n\n private Future<PortScannerManager.ScanResult> isPortOpen(ExecutorService es, String ip, int port, int timeout,\n int delay) {\n return es.submit(() -> {\n if (!running)\n return new PortScannerManager.ScanResult(port, false);\n Thread.sleep(delay);\n portsScanned++;\n try {\n Socket socket = new Socket();\n socket.connect(new InetSocketAddress(ip, port), timeout);\n socket.close();\n return new PortScannerManager.ScanResult(port, true);\n } catch (Exception exc) {\n\n return new PortScannerManager.ScanResult(port, false);\n }\n });\n }\n}" }, { "identifier": "PortScannerManager", "path": "src/main/java/anticope/rejects/utils/portscanner/PortScannerManager.java", "snippet": "public class PortScannerManager {\n public static List<PScanRunner> scans = new ArrayList<>();\n\n public static void killAllScans() {\n for (PScanRunner runner : scans) {\n if (runner.running)\n runner.cancel();\n }\n scans.clear();\n }\n\n public static class ScanResult {\n private int port;\n\n private boolean isOpen;\n\n public ScanResult(int port, boolean isOpen) {\n super();\n this.port = port;\n this.isOpen = isOpen;\n }\n\n public int getPort() {\n return port;\n }\n\n public void setPort(int port) {\n this.port = port;\n }\n\n public boolean isOpen() {\n return isOpen;\n }\n\n public void setOpen(boolean isOpen) {\n this.isOpen = isOpen;\n }\n\n }\n}" } ]
import anticope.rejects.utils.portscanner.PScanRunner; import anticope.rejects.utils.portscanner.PortScannerManager; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.builder.LiteralArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import meteordevelopment.meteorclient.commands.Command; import net.minecraft.client.network.ServerInfo; import net.minecraft.command.CommandSource; import net.minecraft.text.ClickEvent; import net.minecraft.text.ClickEvent.Action; import net.minecraft.text.HoverEvent; import net.minecraft.text.MutableText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import static com.mojang.brigadier.Command.SINGLE_SUCCESS; import static meteordevelopment.meteorclient.MeteorClient.mc;
1,440
package anticope.rejects.commands; /* Ported from Cornos https://github.com/cornos/Cornos/blob/master/src/main/java/me/zeroX150/cornos/features/command/impl/Scan.java */ public class ServerCommand extends Command { private final static SimpleCommandExceptionType ADDRESS_ERROR = new SimpleCommandExceptionType(Text.literal("Couldn't obtain server address")); private final static SimpleCommandExceptionType INVALID_RANGE = new SimpleCommandExceptionType(Text.literal("Invalid range")); private final static HashMap<Integer, String> ports = new HashMap<>(); public ServerCommand() { super("server", "Prints server information"); ports.put(20, "FTP"); ports.put(22, "SSH"); ports.put(80, "HTTP"); ports.put(443, "HTTPS"); ports.put(25565, "Java Server"); ports.put(25575, "Java Server RCON"); ports.put(19132, "Bedrock Server"); ports.put(19133, "Bedrock Server IPv6"); ports.put(8123, "DynMap"); ports.put(25566, "Minequery"); ports.put(3306, "MySQL"); ports.put(3389, "RDP"); } @Override public void build(LiteralArgumentBuilder<CommandSource> builder) { builder.then(literal("ports").executes(ctx -> { scanKnownPorts(getAddress()); return SINGLE_SUCCESS; })); builder.then(literal("ports").then(literal("known").executes(ctx -> { scanKnownPorts(getAddress()); return SINGLE_SUCCESS; }))); builder.then(literal("ports").then(argument("from", IntegerArgumentType.integer(0)).then(argument("to", IntegerArgumentType.integer(1)).executes(ctx -> { scanRange(getAddress(), IntegerArgumentType.getInteger(ctx, "from"), IntegerArgumentType.getInteger(ctx, "to")); return SINGLE_SUCCESS; })))); } private InetAddress getAddress() throws CommandSyntaxException { if (mc.isIntegratedServerRunning()) { try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw ADDRESS_ERROR.create(); } } else { ServerInfo server = mc.getCurrentServerEntry(); if (server == null) throw ADDRESS_ERROR.create(); try { return InetAddress.getByName(server.address); } catch (UnknownHostException e) { throw ADDRESS_ERROR.create(); } } } private void scanPorts(InetAddress address, Collection<Integer> port_list) { info("Started scanning %d ports", port_list.size());
package anticope.rejects.commands; /* Ported from Cornos https://github.com/cornos/Cornos/blob/master/src/main/java/me/zeroX150/cornos/features/command/impl/Scan.java */ public class ServerCommand extends Command { private final static SimpleCommandExceptionType ADDRESS_ERROR = new SimpleCommandExceptionType(Text.literal("Couldn't obtain server address")); private final static SimpleCommandExceptionType INVALID_RANGE = new SimpleCommandExceptionType(Text.literal("Invalid range")); private final static HashMap<Integer, String> ports = new HashMap<>(); public ServerCommand() { super("server", "Prints server information"); ports.put(20, "FTP"); ports.put(22, "SSH"); ports.put(80, "HTTP"); ports.put(443, "HTTPS"); ports.put(25565, "Java Server"); ports.put(25575, "Java Server RCON"); ports.put(19132, "Bedrock Server"); ports.put(19133, "Bedrock Server IPv6"); ports.put(8123, "DynMap"); ports.put(25566, "Minequery"); ports.put(3306, "MySQL"); ports.put(3389, "RDP"); } @Override public void build(LiteralArgumentBuilder<CommandSource> builder) { builder.then(literal("ports").executes(ctx -> { scanKnownPorts(getAddress()); return SINGLE_SUCCESS; })); builder.then(literal("ports").then(literal("known").executes(ctx -> { scanKnownPorts(getAddress()); return SINGLE_SUCCESS; }))); builder.then(literal("ports").then(argument("from", IntegerArgumentType.integer(0)).then(argument("to", IntegerArgumentType.integer(1)).executes(ctx -> { scanRange(getAddress(), IntegerArgumentType.getInteger(ctx, "from"), IntegerArgumentType.getInteger(ctx, "to")); return SINGLE_SUCCESS; })))); } private InetAddress getAddress() throws CommandSyntaxException { if (mc.isIntegratedServerRunning()) { try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { throw ADDRESS_ERROR.create(); } } else { ServerInfo server = mc.getCurrentServerEntry(); if (server == null) throw ADDRESS_ERROR.create(); try { return InetAddress.getByName(server.address); } catch (UnknownHostException e) { throw ADDRESS_ERROR.create(); } } } private void scanPorts(InetAddress address, Collection<Integer> port_list) { info("Started scanning %d ports", port_list.size());
PScanRunner pScanRunner = new PScanRunner(address, 5, 3, 200, port_list, scanResults -> {
0
2023-11-13 08:11:28+00:00
2k
cosmah/database
src/main/java/com/example/application/apis/WorkerResource.java
[ { "identifier": "Worker", "path": "src/main/java/com/example/application/model/Worker.java", "snippet": "@Entity\npublic class Worker implements Serializable {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(nullable = false, updatable = false)\n private Long id;\n private String name;\n private String email;\n private String jobTitle;\n private String phone;\n @Column(nullable = false, updatable = false)\n private String employeeCode;\n\n public Worker(){\n //default constructor\n }\n\n public Worker(Long id, String name, String email, String jobTitle, String phone, String employeeCode) {\n this.id = id;\n this.name = name;\n this.email = email;\n this.jobTitle = jobTitle;\n this.phone = phone;\n this.employeeCode = employeeCode;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getJobTitle() {\n return jobTitle;\n }\n\n public void setJobTitle(String jobTitle) {\n this.jobTitle = jobTitle;\n }\n\n public String getEmployeeCode() {\n return employeeCode;\n }\n\n public void setEmployeeCode(String employeeCode) {\n this.employeeCode = employeeCode;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n @Override\n public String toString() {\n return \"Worker{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", email='\" + email + '\\'' +\n \", jobTitle='\" + jobTitle + '\\'' +\n \", phone='\" + phone + '\\'' +\n \", employeeCode='\" + employeeCode + '\\'' +\n '}';\n }\n}" }, { "identifier": "WorkerService", "path": "src/main/java/com/example/application/service/WorkerService.java", "snippet": "@Service\npublic class WorkerService {\n private final WorkerRepository workerRepository;\n\n\n @Autowired\n public WorkerService(WorkerRepository workerRepository) {\n this.workerRepository = workerRepository;\n }\n\n public Worker addWorker(Worker worker){\n worker.setEmployeeCode(UUID.randomUUID().toString());\n return workerRepository.save(worker);\n }\n\n public List<Worker> findAllWorkers(){\n return workerRepository.findAll();\n }\n\n public Worker updateWorker(Worker worker){\n return workerRepository.save(worker);\n }\n\n public Worker findWorkerById(Long id){\n return workerRepository.findWorkerById(id)\n .orElseThrow(() -> new UserNotFoundException(\"User by id\" +id+ \" was not found\"));\n }\n public void deleteWorker(Long id){\n workerRepository.deleteWorkerById(id);\n }\n}" } ]
import com.example.application.model.Worker; import com.example.application.service.WorkerService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List;
823
package com.example.application.apis; @RestController @RequestMapping("/worker") public class WorkerResource {
package com.example.application.apis; @RestController @RequestMapping("/worker") public class WorkerResource {
private final WorkerService workerService;
1
2023-11-18 09:36:32+00:00
2k
WallasAR/GUITest
src/main/java/com/example/guitest/RecordController.java
[ { "identifier": "RecordTable", "path": "src/main/java/com/table/view/RecordTable.java", "snippet": "public class RecordTable {\n private int idR;\n private String userR;\n private String medicineR;\n private int amountR;\n private float priceR;\n private String dateR;\n\n public RecordTable(int idR, String userR, String medicineR, int amountR, float priceR, String dateR) {\n this.idR = idR;\n this.userR = userR;\n this.medicineR = medicineR;\n this.amountR = amountR;\n this.priceR = priceR;\n this.dateR = dateR;\n }\n\n public int getIdR() {\n return idR;\n }\n\n public void setIdR(int idR) {\n this.idR = idR;\n }\n\n public String getUserR() {\n return userR;\n }\n\n public void setUserR(String userR) {\n this.userR = userR;\n }\n\n public String getMedicineR() {\n return medicineR;\n }\n\n public void setMedicineR(String medicineR) {\n this.medicineR = medicineR;\n }\n\n public int getAmountR() {\n return amountR;\n }\n\n public void setAmountR(int amountR) {\n this.amountR = amountR;\n }\n\n public float getPriceR() {\n return priceR;\n }\n\n public void setPriceR(float priceR) {\n this.priceR = priceR;\n }\n\n public String getDateR() {\n return dateR;\n }\n\n public void setDateR(String dateR) {\n this.dateR = dateR;\n }\n}" }, { "identifier": "AlertMsg", "path": "src/main/java/com/warning/alert/AlertMsg.java", "snippet": "public class AlertMsg {\n static ButtonType btnConfirm = new ButtonType(\"Confirmar\");\n static ButtonType btnCancel = new ButtonType(\"Cancelar\");\n static boolean answer;\n\n public static boolean msgConfirm(String headermsg, String msg){\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Alerta\");\n alert.setHeaderText(headermsg);\n alert.setContentText(msg);\n alert.getButtonTypes().setAll(btnConfirm, btnCancel);\n alert.showAndWait().ifPresent(b -> {\n if (b == btnConfirm){\n answer = true;\n } else {\n answer = false;\n }\n });\n return answer;\n }\n\n public void msgInformation(String header , String msg){\n Alert alert = new Alert(Alert.AlertType.INFORMATION);\n alert.setTitle(\"Aviso\");\n alert.setHeaderText(header);\n alert.setContentText(msg);\n alert.showAndWait();\n }\n}" }, { "identifier": "connection", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public static Connection connection = conexao();" } ]
import com.table.view.RecordTable; import com.warning.alert.AlertMsg; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import java.net.URL; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import static com.db.bank.Banco.connection;
842
package com.example.guitest; public class RecordController implements Initializable { @FXML protected void MainAction(MouseEvent e) {
package com.example.guitest; public class RecordController implements Initializable { @FXML protected void MainAction(MouseEvent e) {
if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) {
1
2023-11-16 14:55:08+00:00
2k
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 }\n\n\n public Buffer() {\n final int DEF_BUF_SIZE = 1024;\n this.bufSize = DEF_BUF_SIZE;\n this.buf = new Frame[DEF_BUF_SIZE];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n /**\n * @param bufSize:用户自定义的缓存区大小\n */\n public Buffer(int bufSize) throws Exception {\n if (bufSize <= 0) {\n throw new Exception(\"缓存区大小不可以为非正数!\");\n }\n this.bufSize = bufSize;\n this.buf = new Frame[bufSize];\n //初始化帧缓存区\n for (int i = 0; i < this.bufSize; i++) {\n this.buf[i] = new Frame();\n }\n }\n\n public Frame readFrame(int frameId) {\n return buf[frameId];\n }\n\n public void writeFrame(Page page, int frameId) {\n //先不进行任何操作\n }\n\n}" }, { "identifier": "Disk", "path": "src/main/java/cs/adb/wzh/Storage/Disk.java", "snippet": "public class Disk {\n private final int diskSize;\n private final Page[] disk;\n\n public int getDiskSize() {\n return diskSize;\n }\n\n public Page[] getDisk() {\n return disk;\n }\n\n\n public Disk() {\n final int DEF_BUF_SIZE = 65536;//256MB的磁盘\n this.diskSize = DEF_BUF_SIZE;\n this.disk = new Page[DEF_BUF_SIZE];\n //初始化磁盘空间\n for (int pageId = 0; pageId < this.diskSize; pageId++) {\n this.disk[pageId] = new Page();\n }\n }\n\n\n}" }, { "identifier": "BCB", "path": "src/main/java/cs/adb/wzh/bufferControlBlocks/BCB.java", "snippet": "public class BCB {\n private int pageId;\n private final int frameId;\n private int latch;\n private int count;\n private int dirty = 0;\n private int referenced = 1;\n private BCB next;\n private BCB pre;\n\n /**\n * BCB块的id对应其在缓存区中的frameId\n *\n * @param frameId:缓存区页号\n */\n public BCB(int frameId) {\n this.frameId = frameId;\n }\n\n\n public void setPageId(int pageId) {\n this.pageId = pageId;\n }\n\n public void setNext(BCB next) {\n this.next = next;\n }\n\n public void setPre(BCB pre) {\n this.pre = pre;\n }\n\n public void setDirty(int dirty) {\n this.dirty = dirty;\n }\n\n public void setReferenced(int referenced) {\n this.referenced = referenced;\n }\n\n public BCB getNext() {\n return next;\n }\n\n\n public BCB getPre() {\n return pre;\n }\n\n public int getPageId() {\n return pageId;\n }\n\n public int getFrameId() {\n return frameId;\n }\n\n public int getDirty() {\n return dirty;\n }\n\n public int getReferenced() {\n return referenced;\n }\n}" }, { "identifier": "PageRequestReader", "path": "src/main/java/cs/adb/wzh/utils/PageRequestReader.java", "snippet": "public class PageRequestReader {\n private final ArrayList<Integer> operations = new ArrayList<>();//0读1写\n private final ArrayList<Integer> pageIds = new ArrayList<>();//页号列表\n\n public PageRequestReader(String filePath) throws IOException {\n File fin = new File(filePath);\n FileInputStream fis = new FileInputStream(fin);\n\n //Construct BufferedReader from InputStreamReader\n BufferedReader br = new BufferedReader(new InputStreamReader(fis));\n\n String line;\n while ((line = br.readLine()) != null) {\n String[] str = line.split(\",\");\n operations.add(Integer.valueOf(str[0]));\n pageIds.add(Integer.valueOf(str[1]));\n }\n\n br.close();\n fis.close();\n\n }\n\n public int getOperation(int requestId) {\n return operations.get(requestId);\n }\n\n public int getPageId(int requestId) {\n return pageIds.get(requestId);\n }\n\n public int getRequestNum() {\n return pageIds.size();\n }\n}" }, { "identifier": "SwapMethod", "path": "src/main/java/cs/adb/wzh/utils/SwapMethod.java", "snippet": "public enum SwapMethod {\n LRU, CLOCK;\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,352
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ class BMgrTest { @Test void bMgrTest() throws Exception {
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ class BMgrTest { @Test void bMgrTest() throws Exception {
Buffer bf = new Buffer(8);
0
2023-11-15 16:30:06+00:00
2k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/DragonFly.java
[ { "identifier": "DebugMain", "path": "src/main/java/useless/dragonfly/debug/DebugMain.java", "snippet": "public class DebugMain {\n\tpublic static void init(){\n\t\tItemHelper.createItem(DragonFly.MOD_ID, new ItemDebugStick(\"debug\", 21000), \"debug\").setIconCoord(4, 10);\n\t\tDebugBlocks.init();\n\t\tDebugEntities.init();\n//\t\tStringBuilder builder = new StringBuilder();\n//\t\tfor (String string: ModelHelper.modelDataFiles.keySet()) {\n//\t\t\tbuilder.append(string);\n//\t\t\tbuilder.append(Utilities.tabBlock(ModelHelper.modelDataFiles.get(string).toString(), 1));\n//\t\t}\n//\t\tDragonFly.LOGGER.info(builder.toString());\n\t}\n}" }, { "identifier": "Animation", "path": "src/main/java/useless/dragonfly/model/entity/animation/Animation.java", "snippet": "public class Animation {\n\tprivate final Map<String, AnimationData> animations;\n\n\tpublic Map<String, AnimationData> getAnimations() {\n\t\treturn animations;\n\t}\n\n\tpublic Animation(Map<String, AnimationData> animations) {\n\t\tthis.animations = animations;\n\t}\n}" }, { "identifier": "AnimationDeserializer", "path": "src/main/java/useless/dragonfly/model/entity/animation/AnimationDeserializer.java", "snippet": "public class AnimationDeserializer implements JsonDeserializer<Animation> {\n\t@Override\n\tpublic Animation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {\n\t\tMap<String, AnimationData> animations = Maps.newHashMap();\n\n\t\tif (json.isJsonObject()) {\n\t\t\tJsonObject obj = (JsonObject) json;\n\t\t\tif (obj.has(\"animations\")) {\n\t\t\t\tfor (Map.Entry<String, JsonElement> entry : obj.getAsJsonObject(\"animations\").entrySet()) {\n\t\t\t\t\tanimations.put(entry.getKey(), makeAnimation((JsonObject) entry.getValue()));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn new Animation(animations);\n\t\t}\n\t\treturn new Animation(animations);\n\t}\n\n\n\tprivate AnimationData makeAnimation(JsonObject object) {\n\t\tboolean loop = object.has(\"loop\") && object.getAsJsonPrimitive(\"loop\").getAsBoolean();\n\n\t\tfloat length = object.has(\"animation_length\") ? object.getAsJsonPrimitive(\"animation_length\").getAsFloat() : 0;\n\t\tMap<String, BoneData> boneMap = object.has(\"bones\") ? makeBoneMap(object.getAsJsonObject(\"bones\")) : Maps.newHashMap();\n\n\t\treturn new AnimationData(loop, length, boneMap);\n\t}\n\n\tprivate Map<String, BoneData> makeBoneMap(JsonObject object) {\n\t\tMap<String, BoneData> boneMap = Maps.newHashMap();\n\t\tfor (Map.Entry<String, JsonElement> entry : object.entrySet()) {\n\t\t\tboneMap.put(entry.getKey(), makeBone(entry.getValue().getAsJsonObject()));\n\t\t}\n\t\treturn boneMap;\n\t}\n\n\tprivate BoneData makeBone(JsonObject object) {\n\t\tMap<String, PostData> rotateMap = object.has(\"rotation\") ? makePostMap(object.get(\"rotation\")) : Maps.newHashMap();\n\t\tMap<String, PostData> positionMap = object.has(\"position\") ? makePostMap(object.get(\"position\")) : Maps.newHashMap();\n\t\tMap<String, PostData> scaleMap = object.has(\"scale\") ? makePostMap(object.get(\"scale\")) : Maps.newHashMap();\n\n\t\treturn new BoneData(rotateMap, positionMap, scaleMap);\n\t}\n\n\tprivate Map<String, PostData> makePostMap(JsonElement element) {\n\t\tMap<String, PostData> postMap = Maps.newHashMap();\n\t\tif (element instanceof JsonArray) {\n\t\t\tList<Float> floats = Lists.newArrayList();\n\t\t\tfloats.add(element.getAsJsonArray().get(0).getAsFloat());\n\t\t\tfloats.add(element.getAsJsonArray().get(1).getAsFloat());\n\t\t\tfloats.add(element.getAsJsonArray().get(2).getAsFloat());\n\t\t\tpostMap.put(\"0\", new PostData(floats, \"catmullrom\"));\n\t\t\treturn postMap;\n\t\t}\n\t\tif (element instanceof JsonObject) {\n\t\t\tfor (Map.Entry<String, JsonElement> entry : ((JsonObject) element).entrySet()) {\n\t\t\t\tpostMap.put(entry.getKey(), makePost(entry.getValue()));\n\t\t\t}\n\t\t}\n\t\treturn postMap;\n\t}\n\n\tprivate PostData makePost(JsonElement element) {\n\t\tList<Float> list = Lists.newArrayList();\n\t\tif (element instanceof JsonPrimitive) {\n\t\t\tJsonArray array = new JsonArray(3);\n\n\t\t\tarray.add(element);\n\t\t\tarray.add(element);\n\t\t\tarray.add(element);\n\n\t\t\telement = array;\n\t\t}\n\n\t\tif (element instanceof JsonArray) {\n\t\t\tlist.add(0, ((JsonArray) element).get(0).getAsFloat());\n\t\t\tlist.add(1, ((JsonArray) element).get(1).getAsFloat());\n\t\t\tlist.add(2, ((JsonArray) element).get(2).getAsFloat());\n\t\t\treturn new PostData(list, \"catmullrom\");\n\t\t}\n\n\t\tif (element instanceof JsonObject) {\n\t\t\tJsonObject jsonObject = (JsonObject) element;\n\t\t\tlist.add(0, jsonObject.getAsJsonArray(\"post\").get(0).getAsFloat());\n\t\t\tlist.add(1, jsonObject.getAsJsonArray(\"post\").get(1).getAsFloat());\n\t\t\tlist.add(2, jsonObject.getAsJsonArray(\"post\").get(2).getAsFloat());\n\t\t\treturn new PostData(list, jsonObject.getAsJsonPrimitive(\"lerp_mode\").getAsString());\n\t\t}\n\t\treturn null;\n\t}\n}" } ]
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.client.render.TextureFX; import net.minecraft.core.Global; import net.minecraft.core.util.helper.Side; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import turniplabs.halplibe.util.GameStartEntrypoint; import useless.dragonfly.debug.DebugMain; import useless.dragonfly.model.entity.animation.Animation; import useless.dragonfly.model.entity.animation.AnimationDeserializer;
1,391
package useless.dragonfly; public class DragonFly implements GameStartEntrypoint { public static final String MOD_ID = "dragonfly"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
package useless.dragonfly; public class DragonFly implements GameStartEntrypoint { public static final String MOD_ID = "dragonfly"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
public static final Gson GSON = new GsonBuilder().registerTypeAdapter(Animation.class, new AnimationDeserializer()).create();
2
2023-11-16 01:10:52+00:00
2k
AntonyCheng/ai-bi
src/test/java/top/sharehome/springbootinittemplate/aop/NormalAopTest.java
[ { "identifier": "ArgsService", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/argsAop/service/ArgsService.java", "snippet": "public interface ArgsService {\n\n public void doMethod1();\n\n public String doMethod2();\n\n public void doMethod3() throws Exception;\n\n public void doMethod4(String param);\n\n}" }, { "identifier": "BeanService", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/beanAop/service/BeanService.java", "snippet": "public interface BeanService {\n\n void doMethod();\n\n}" }, { "identifier": "ExecutionService", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/executionAop/service/ExecutionService.java", "snippet": "public interface ExecutionService {\n\n public void doMethod1();\n\n public String doMethod2();\n\n public void doMethod3() throws Exception;\n\n public void doMethod4(String param);\n\n}" }, { "identifier": "TargetService", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/targetAop/service/TargetService.java", "snippet": "public interface TargetService {\n\n public void doMethod1();\n\n public String doMethod2();\n\n public void doMethod3() throws Exception;\n\n public void doMethod4(String param);\n\n}" }, { "identifier": "ThisService", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/thisAop/service/ThisService.java", "snippet": "public interface ThisService {\n\n public void doMethod1();\n\n public String doMethod2();\n\n public void doMethod3() throws Exception;\n\n public void doMethod4(String param);\n\n}" }, { "identifier": "WithinService", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/withinAop/service/WithinService.java", "snippet": "public interface WithinService {\n\n public void doMethod1();\n\n public String doMethod2();\n\n public void doMethod3() throws Exception;\n\n public void doMethod4(String param);\n\n}" }, { "identifier": "WithinServiceImpl1", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/withinAop/service/impl/WithinServiceImpl1.java", "snippet": "@Service\npublic class WithinServiceImpl1 implements WithinService {\n\n @Override\n public void doMethod1() {\n System.out.println(\"WithinServiceImpl1.doMethod1-1()\");\n }\n\n @Override\n public String doMethod2() {\n System.out.println(\"WithinServiceImpl1.doMethod1-2()\");\n return \"hello world\";\n }\n\n @Override\n public void doMethod3() throws Exception {\n System.out.println(\"WithinServiceImpl1.doMethod1-3()\");\n throw new Exception(\"some exception\");\n }\n\n @Override\n public void doMethod4(String param) {\n System.out.println(\"WithinServiceImpl1.doMethod1-4(), args = \" + param);\n }\n\n}" }, { "identifier": "WithinServiceImpl2", "path": "src/main/java/top/sharehome/springbootinittemplate/aop/studyDemo/normal/withinAop/service/impl/WithinServiceImpl2.java", "snippet": "@Service\npublic class WithinServiceImpl2 implements WithinService {\n\n @Override\n public void doMethod1() {\n System.out.println(\"WithinServiceImpl2.doMethod2-1()\");\n }\n\n @Override\n public String doMethod2() {\n System.out.println(\"WithinServiceImpl2.doMethod2-2()\");\n return \"hello world\";\n }\n\n @Override\n public void doMethod3() throws Exception {\n System.out.println(\"WithinServiceImpl2.doMethod2-3()\");\n throw new Exception(\"some exception\");\n }\n\n @Override\n public void doMethod4(String param) {\n System.out.println(\"WithinServiceImpl2.doMethod2-4(), args = \" + param);\n }\n\n}" } ]
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.argsAop.service.ArgsService; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.beanAop.service.BeanService; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.executionAop.service.ExecutionService; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.targetAop.service.TargetService; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.thisAop.service.ThisService; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.withinAop.service.WithinService; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.withinAop.service.impl.WithinServiceImpl1; import top.sharehome.springbootinittemplate.aop.studyDemo.normal.withinAop.service.impl.WithinServiceImpl2; import javax.annotation.Resource;
1,158
package top.sharehome.springbootinittemplate.aop; /** * 切点参数为execution型的切面测试类 * * @author AntonyCheng */ @SpringBootTest public class NormalAopTest { @Resource
package top.sharehome.springbootinittemplate.aop; /** * 切点参数为execution型的切面测试类 * * @author AntonyCheng */ @SpringBootTest public class NormalAopTest { @Resource
private ExecutionService executionService;
2
2023-11-12 07:49:59+00:00
2k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/audio/AudioThread.java
[ { "identifier": "PlayingSound", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/audio/play/PlayingSound.java", "snippet": "public abstract class PlayingSound {\n protected final int source;\n protected volatile boolean finished;\n\n /**\n * Internal use only.\n *\n * @param source OpenAL source name\n */\n public PlayingSound(int source) {\n this.source = source;\n finished = false;\n }\n\n /**\n * Sets the source's position in world space.\n *\n * @param pos absolute position in world space\n */\n public void setPositionAbsolute(Vector3fc pos) {\n if (finished) return;\n alSourcei(source, AL_SOURCE_RELATIVE, AL_FALSE);\n alSource3f(source, AL_POSITION, pos.x(), pos.y(), pos.z());\n }\n\n /**\n * Sets the source's position relative to the listener.\n *\n * @param pos position relative to the listener\n */\n public void setPositionRelative(Vector3fc pos) {\n if (finished) return;\n alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);\n alSource3f(source, AL_POSITION, pos.x(), pos.y(), pos.z());\n }\n\n /**\n * Sets the gain of the audio. A gain of 1 is the default volume, with\n * higher values corresponding to louder sound.\n *\n * @param gain new gain\n */\n public void setGain(float gain) {\n if (finished) return;\n alSourcef(source, AL_GAIN, gain);\n }\n\n /**\n * Sets the pitch of the audio. A pitch of 1 is the default pitch, with\n * higher values corresponding to higher pitch. A pitch of 2 would be\n * an an octave higher pitch.\n *\n * @param pitch new pitch\n */\n public void setPitch(float pitch) {\n if (finished) return;\n alSourcef(source, AL_PITCH, pitch);\n }\n\n /**\n * Sets whether the audio should automatically repeat when it reaches the\n * end.\n *\n * @param looping whether to loop\n */\n public abstract void setLooping(boolean looping);\n\n /**\n * Gets whether the audio is currently playing.\n *\n * @return if playing\n */\n public boolean isPlaying() {\n return !finished && alGetSourcei(source, AL_SOURCE_STATE) == AL_PLAYING;\n }\n\n /**\n * Stops the audio playback immediately.\n */\n public void stop() {\n if (finished) return;\n alSourceStop(source);\n }\n\n /**\n * Internal use only.\n * Releases the OpenAL source and any buffers associated with this sound.\n *\n * @return OpenAL source name\n */\n public int end() {\n if (finished) throw new IllegalStateException(\"Already finished\");\n finished = true;\n alSourcei(source, AL_BUFFER, 0);\n return source;\n }\n}" }, { "identifier": "PlayingStream", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/audio/play/PlayingStream.java", "snippet": "public final class PlayingStream extends PlayingSound {\n private static final int BUFFER_COUNT = 3;\n\n private final AudioStream stream;\n private final int[] buffers;\n private final int format;\n private boolean reachedEnd;\n\n public PlayingStream(int source, AudioStream stream) {\n super(source);\n this.stream = stream;\n reachedEnd = false;\n\n buffers = new int[BUFFER_COUNT];\n alGenBuffers(buffers);\n\n format = stream.getChannels() == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;\n\n for (int i = 0; i < BUFFER_COUNT; i++) {\n ShortBuffer pcm = stream.readSamples();\n if (pcm == null) {\n reachedEnd = true;\n break;\n }\n alBufferData(buffers[i], format, pcm, stream.getSampleRate());\n alSourceQueueBuffers(source, buffers[i]);\n MemoryUtil.memFree(pcm);\n }\n\n alSourcePlay(source);\n }\n\n @Override\n public void setLooping(boolean looping) {\n throw new UnsupportedOperationException(\"TODO\");\n }\n\n public void update() {\n if (reachedEnd)\n return;\n\n int processed = alGetSourcei(source, AL_BUFFERS_PROCESSED);\n for (int i = 0; i < processed; i++) {\n int buffer = alSourceUnqueueBuffers(source);\n\n ShortBuffer pcm = stream.readSamples();\n if (pcm == null) {\n reachedEnd = true;\n break;\n }\n alBufferData(buffer, format, pcm, stream.getSampleRate());\n MemoryUtil.memFree(pcm);\n alSourceQueueBuffers(source, buffer);\n }\n }\n\n @Override\n public int end() {\n alSourceStop(source);\n int[] ignored = new int[alGetSourcei(source, AL_BUFFERS_PROCESSED)];\n alSourceUnqueueBuffers(source, ignored);\n alDeleteBuffers(buffers);\n try {\n stream.close();\n } catch (Exception e) {\n System.err.println(\"Failed to close audio stream:\");\n e.printStackTrace();\n }\n\n return super.end();\n }\n}" } ]
import com.github.rmheuer.azalea.audio.play.PlayingSound; import com.github.rmheuer.azalea.audio.play.PlayingStream; import java.util.concurrent.CopyOnWriteArrayList;
1,483
package com.github.rmheuer.azalea.audio; final class AudioThread extends Thread { private volatile boolean running = false; private final AudioSystem system; private final CopyOnWriteArrayList<PlayingSound> sounds; public AudioThread(AudioSystem system) { super("Audio Thread"); this.system = system; sounds = new CopyOnWriteArrayList<>(); } public void add(PlayingSound sound) { sounds.add(sound); } @Override public void run() { System.out.println("Starting audio thread"); running = true; while (running) { for (PlayingSound sound : sounds) {
package com.github.rmheuer.azalea.audio; final class AudioThread extends Thread { private volatile boolean running = false; private final AudioSystem system; private final CopyOnWriteArrayList<PlayingSound> sounds; public AudioThread(AudioSystem system) { super("Audio Thread"); this.system = system; sounds = new CopyOnWriteArrayList<>(); } public void add(PlayingSound sound) { sounds.add(sound); } @Override public void run() { System.out.println("Starting audio thread"); running = true; while (running) { for (PlayingSound sound : sounds) {
if (sound instanceof PlayingStream)
1
2023-11-16 04:46:53+00:00
2k
jmgarridopaz/tienda-hexa
src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/configurador/TiendaHexaConfiguracion.java
[ { "identifier": "ClienteService", "path": "src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/negocio/ClienteService.java", "snippet": "public interface ClienteService {\n\n\tpublic void darAltaCliente ( String email, String nombre );\n\n\tpublic List<Cliente> obtenerTodosClientes();\n\t\n}" }, { "identifier": "ClienteServiceImpl", "path": "src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/negocio/ClienteServiceImpl.java", "snippet": "public class ClienteServiceImpl implements ClienteService {\n\n\tprivate final ClienteStore clienteStore;\n\t\n\tpublic ClienteServiceImpl(ClienteStore clienteStore) {\n\t\tthis.clienteStore = clienteStore;\n\t}\n\t\n\t@Override\n\tpublic void darAltaCliente ( String email, String nombre ) {\n\t\tlanzarExeptionSiEmailIncorrecto(email);\n\t\tCliente cliente = new Cliente(email);\n\t\tcliente.setNombre(nombre);\n\t\tthis.clienteStore.guardar(cliente);\n\t\treturn;\n\t}\n\n\t@Override\n\tpublic List<Cliente> obtenerTodosClientes() {\n\t\treturn this.clienteStore.recuperarTodos();\n\t}\n\n\tprivate void lanzarExeptionSiEmailIncorrecto ( String email ) {\n\t\tif ( email==null ) {\n\t\t\tthrow new EmailIncorrectoException(\"El email no puede ser nulo\");\n\t\t}\n\t\tif ( email.trim().length()==0 ) {\n\t\t\tthrow new RuntimeException(\"El email no puede estar en blanco\");\n\t\t}\n\t\tif ( ! formatoEmailEsCorrecto(email) ) {\n\t\t\tthrow new RuntimeException(\"El formato del email no es correcto\");\n\t\t}\n\t\treturn;\n\t}\n\t\n\tprivate boolean formatoEmailEsCorrecto(String email) {\n\t\tString patronEmail =\n\t \"^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@\"\n\t + \"[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$\";\n\t Pattern pattern = Pattern.compile(patronEmail);\n Matcher matcher = pattern.matcher(email);\n return matcher.matches();\n\t}\n\t\n}" }, { "identifier": "ClienteStore", "path": "src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/negocio/ClienteStore.java", "snippet": "public interface ClienteStore {\n\n public void guardar (Cliente cliente);\n\n public List<Cliente> recuperarTodos();\n\n}" }, { "identifier": "ClienteRepository", "path": "src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/persistencia/ClienteRepository.java", "snippet": "@Repository\npublic interface ClienteRepository extends JpaRepository<ClienteJpa, Long> {\n\n public ClienteJpa save (ClienteJpa cliente);\n\n public List<ClienteJpa> findAll();\n\n}" }, { "identifier": "ConversorStoreSpringJpa", "path": "src/main/java/es/uhu/etsi/tallerhexagonal/tiendahexa/persistencia/ConversorStoreSpringJpa.java", "snippet": "public class ConversorStoreSpringJpa implements ClienteStore {\n\n\tprivate final ClienteRepository clienteRepository;\n\n\tpublic ConversorStoreSpringJpa(ClienteRepository clienteRepository) {\n\t\tthis.clienteRepository = clienteRepository;\n\t}\n\n\t@Override\n\tpublic void guardar(Cliente cliente) {\n\t\tClienteJpa clienteJpa = ClienteMapper.toJpa(cliente);\n\t\tthis.clienteRepository.save(clienteJpa);\n\t\treturn;\n\t}\n\n\t@Override\n\tpublic List<Cliente> recuperarTodos() {\n\t\tList<ClienteJpa> clientesJpa = this.clienteRepository.findAll();\n\t\treturn ClienteMapper.fromJpaList(clientesJpa);\n\t}\n\n}" } ]
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import es.uhu.etsi.tallerhexagonal.tiendahexa.negocio.ClienteService; import es.uhu.etsi.tallerhexagonal.tiendahexa.negocio.ClienteServiceImpl; import es.uhu.etsi.tallerhexagonal.tiendahexa.negocio.ClienteStore; import es.uhu.etsi.tallerhexagonal.tiendahexa.persistencia.ClienteRepository; import es.uhu.etsi.tallerhexagonal.tiendahexa.persistencia.ConversorStoreSpringJpa;
1,060
package es.uhu.etsi.tallerhexagonal.tiendahexa.configurador; @Configuration public class TiendaHexaConfiguracion { @Bean
package es.uhu.etsi.tallerhexagonal.tiendahexa.configurador; @Configuration public class TiendaHexaConfiguracion { @Bean
public ClienteStore clienteStore ( ClienteRepository clienteRepository) {
3
2023-11-18 12:57:56+00:00
2k
orijer/IvritInterpreter
src/Preprocessor.java
[ { "identifier": "GeneralPreprocessingException", "path": "src/IvritExceptions/PreprocessingExceptions/GeneralPreprocessingException.java", "snippet": "public class GeneralPreprocessingException extends UncheckedIOException{\r\n /**\r\n * Constructor.\r\n * @param exception - The cause.\r\n */\r\n public GeneralPreprocessingException(IOException exception) {\r\n super(\"העיבוד המקדים נכשל. בדוק שהקובץ אכן בפורמט הנכון\", exception);\r\n }\r\n \r\n}\r" }, { "identifier": "RestartableBufferedReader", "path": "src/IvritStreams/RestartableBufferedReader.java", "snippet": "public class RestartableBufferedReader implements RestartableReader {\r\n //We delegate the reading itself to a buffered reader we save as a field:\r\n private BufferedReader delegatedReader;\r\n //The file weare reading from:\r\n private File sourceFile;\r\n //true IFF this reader is open (= usable):\r\n private boolean isOpen;\r\n\r\n /**\r\n * Constructor.\r\n * @param readFrom - The file this reads from.\r\n */\r\n public RestartableBufferedReader(File sourceFile) throws IOException {\r\n this.delegatedReader = new BufferedReader(\r\n new InputStreamReader(\r\n new FileInputStream(sourceFile), \"UTF-8\"));\r\n this.sourceFile = sourceFile;\r\n this.isOpen = true;\r\n }\r\n\r\n @Override\r\n public String readLine() throws IOException {\r\n if (this.isOpen) {\r\n String line;\r\n do {\r\n line = this.delegatedReader.readLine();\r\n } while (line != null && (line.isBlank() || line.charAt(0) == '#'));\r\n\r\n return line;\r\n }\r\n\r\n throw new IOException(\"הקורא הזה כבר סגור\");\r\n }\r\n\r\n @Override\r\n public void restart() throws IOException {\r\n if (this.isOpen) {\r\n this.delegatedReader.close();\r\n }\r\n\r\n this.delegatedReader = new BufferedReader(\r\n new InputStreamReader(\r\n new FileInputStream(sourceFile), \"UTF-8\"));\r\n }\r\n\r\n @Override\r\n public void close() throws IOException {\r\n if (this.isOpen) {\r\n this.delegatedReader.close();\r\n return;\r\n }\r\n\r\n throw new IOException(\"הקורא הזה כבר סגור\");\r\n }\r\n\r\n}\r" } ]
import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import IvritExceptions.PreprocessingExceptions.GeneralPreprocessingException; import IvritStreams.RestartableBufferedReader;
970
/** * This reads an entire source file and processes whatever it needs for the interpreter to work later. */ public class Preprocessor { //The file to be preprocessed private File sourceFile; //Contains a map that connects the titles for jumps, //to how many lines need to be skipped in order to get to the correct line of code. private Map<String, Integer> jumpMap; /** * Constructor. * @param file - The file to be preprocessed. */ public Preprocessor(File file){ //Maybe create a PreprocessingFailedException and throw that? this.sourceFile = file; this.jumpMap = new HashMap<>(); } /** * Starts to preprocess the file. * @throws GeneralPreprocessingException when an exception that can't be traced happened during the prepocessing stage. */ public void start() { try (RestartableBufferedReader reader = new RestartableBufferedReader(sourceFile)) { System.out.println("מתחיל עיבוד מקדים של הקובץ: " + this.sourceFile.getName()); int linesCounter = 1; String currentLine; while ((currentLine = reader.readLine()) != null) { if (currentLine.charAt(0) == Interpreter.JUMP_FLAG_CHAR) { this.jumpMap.put(currentLine.substring(1), linesCounter); } linesCounter++; } System.out.println("העיבוד המקדים הסתיים."); } catch(IOException exception) { //We can't really recover if we can't read from the source file...
/** * This reads an entire source file and processes whatever it needs for the interpreter to work later. */ public class Preprocessor { //The file to be preprocessed private File sourceFile; //Contains a map that connects the titles for jumps, //to how many lines need to be skipped in order to get to the correct line of code. private Map<String, Integer> jumpMap; /** * Constructor. * @param file - The file to be preprocessed. */ public Preprocessor(File file){ //Maybe create a PreprocessingFailedException and throw that? this.sourceFile = file; this.jumpMap = new HashMap<>(); } /** * Starts to preprocess the file. * @throws GeneralPreprocessingException when an exception that can't be traced happened during the prepocessing stage. */ public void start() { try (RestartableBufferedReader reader = new RestartableBufferedReader(sourceFile)) { System.out.println("מתחיל עיבוד מקדים של הקובץ: " + this.sourceFile.getName()); int linesCounter = 1; String currentLine; while ((currentLine = reader.readLine()) != null) { if (currentLine.charAt(0) == Interpreter.JUMP_FLAG_CHAR) { this.jumpMap.put(currentLine.substring(1), linesCounter); } linesCounter++; } System.out.println("העיבוד המקדים הסתיים."); } catch(IOException exception) { //We can't really recover if we can't read from the source file...
throw new GeneralPreprocessingException(exception);
0
2023-11-17 09:15:07+00:00
2k
WuKongOpenSource/Wukong_HRM
common/common-web/src/main/java/com/kakarote/core/feign/jxc/service/impl/JxcServiceImpl.java
[ { "identifier": "Result", "path": "common/common-web/src/main/java/com/kakarote/core/common/Result.java", "snippet": "public class Result<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @ApiModelProperty(value = \"code\", required = true, example = \"0\")\n private Integer code;\n\n @ApiModelProperty(value = \"msg\", required = true, example = \"success\")\n private String msg;\n\n private T data;\n\n Result() {\n\n }\n\n\n protected Result(ResultCode resultCode) {\n this.code = resultCode.getCode();\n this.msg = resultCode.getMsg();\n }\n\n private Result(ResultCode resultCode, String msg) {\n this.code = resultCode.getCode();\n this.msg = msg;\n }\n\n private Result(int code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n\n public Integer getCode() {\n return code;\n }\n\n public String getMsg() {\n return msg;\n }\n\n\n public static Result<String> noAuth() {\n return error(SystemCodeEnum.SYSTEM_NO_AUTH);\n }\n\n public static <T> Result<T> error(ResultCode resultCode) {\n return new Result<>(resultCode);\n }\n\n public static <T> Result<T> error(int code, String msg) {\n return new Result<>(code, msg);\n }\n\n public static <T> Result<T> error(ResultCode resultCode, String msg) {\n return new Result<T>(resultCode, msg);\n }\n\n public static <T> Result<T> ok(T data) {\n Result<T> result = new Result<>(SystemCodeEnum.SYSTEM_OK);\n result.setData(data);\n return result;\n }\n\n\n public static <T> Result<T> ok() {\n return new Result<T>(SystemCodeEnum.SYSTEM_OK);\n }\n\n\n public Result<T> setData(T data) {\n this.data = data;\n return this;\n }\n\n public T getData() {\n return this.data;\n }\n\n public boolean hasSuccess() {\n return Objects.equals(SystemCodeEnum.SYSTEM_OK.getCode(), code);\n }\n\n public String toJSONString() {\n return JSON.toJSONString(this);\n }\n\n @Override\n public String toString() {\n return toJSONString();\n }\n\n\n\n}" }, { "identifier": "SimpleUser", "path": "common/common-web/src/main/java/com/kakarote/core/feign/admin/entity/SimpleUser.java", "snippet": "@Getter\n@Setter\n@ApiModel(\"用户对象\")\npublic class SimpleUser implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @ApiModelProperty(\"用户ID\")\n private Long userId;\n\n @ApiModelProperty(\"头像\")\n private String img;\n\n @ApiModelProperty(\"昵称\")\n private String realname;\n\n @ApiModelProperty(\"用户状态 0禁用,1正常,2未激活\")\n private Integer status;\n\n @ApiModelProperty(\"部门ID\")\n private Long deptId;\n\n @ApiModelProperty(\"部门名称\")\n private String deptName;\n\n @ApiModelProperty(\"企业微信userId\")\n private String wxUserId;\n\n @ApiModelProperty(\"外部审核人邮箱\")\n private String outerUserEmail;\n\n public SimpleUser() {\n }\n\n public SimpleUser(Long userId, String img, String realname, Long deptId, String deptName) {\n this.userId = userId;\n this.img = img;\n this.realname = realname;\n this.deptId = deptId;\n this.deptName = deptName;\n }\n\n public SimpleUser(Long userId, String img, String realname, Integer status, Long deptId, String deptName, String wxUserId) {\n this.userId = userId;\n this.img = img;\n this.realname = realname;\n this.status = status;\n this.deptId = deptId;\n this.deptName = deptName;\n this.wxUserId = wxUserId;\n }\n}" }, { "identifier": "JxcService", "path": "common/common-web/src/main/java/com/kakarote/core/feign/jxc/service/JxcService.java", "snippet": "@FeignClient(name = \"jxc\", contextId = \"jxc\", fallback = JxcServiceImpl.class)\npublic interface JxcService {\n\n /**\n * 修改仓库Create用户name\n *\n * @param adminUser:用户对象\n */\n @PostMapping(\"/jxcWarehouse/updateWarehouseCreateUserName\")\n void updateWarehouseCreateUserName(@RequestBody SimpleUser adminUser);\n\n\n /**\n * 批量更新es\n *\n * @param id:数据id\n * @param name:数据名\n * @param type:数据类型\n */\n @PostMapping(value = \"/jxcField/batchUpdateEsData\")\n void batchUpdateEsData(@RequestParam(\"id\") String id, @RequestParam(\"name\") String name, @RequestParam(\"type\") String type);\n\n @ApiOperation(\"查询所有字段语言包key信息\")\n @PostMapping(value = \"/jxcField/getAllFieldLanguageRel\")\n Result<List<Map<String, Object>>> getAllFieldLanguageRel();\n\n}" } ]
import com.kakarote.core.common.Result; import com.kakarote.core.feign.admin.entity.SimpleUser; import com.kakarote.core.feign.jxc.service.JxcService; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map;
1,428
package com.kakarote.core.feign.jxc.service.impl; /** * @author wwl * @date 2022/7/13 16:00 */ @Component public class JxcServiceImpl implements JxcService { @Override public void updateWarehouseCreateUserName(SimpleUser adminUser) { } @Override public void batchUpdateEsData(String id, String name, String type) { } @Override
package com.kakarote.core.feign.jxc.service.impl; /** * @author wwl * @date 2022/7/13 16:00 */ @Component public class JxcServiceImpl implements JxcService { @Override public void updateWarehouseCreateUserName(SimpleUser adminUser) { } @Override public void batchUpdateEsData(String id, String name, String type) { } @Override
public Result<List<Map<String, Object>>> getAllFieldLanguageRel() {
0
2023-10-17 05:49:52+00:00
2k
WisdomShell/codeshell-intellij
src/main/java/com/codeshell/intellij/settings/CodeShellSettings.java
[ { "identifier": "ChatMaxToken", "path": "src/main/java/com/codeshell/intellij/enums/ChatMaxToken.java", "snippet": "public enum ChatMaxToken {\n LOW(\"1024\"),\n MEDIUM(\"2048\"),\n HIGH(\"4096\"),\n ULTRA(\"8192\");\n\n private final String description;\n\n ChatMaxToken(String description) {\n this.description = description;\n }\n\n public String getDescription() {\n return description;\n }\n\n @Override\n public String toString() {\n return description;\n }\n}" }, { "identifier": "CompletionMaxToken", "path": "src/main/java/com/codeshell/intellij/enums/CompletionMaxToken.java", "snippet": "public enum CompletionMaxToken {\n\n LOW(\"32\"),\n MEDIUM(\"64\"),\n HIGH(\"128\"),\n ULTRA(\"256\");\n\n private final String description;\n\n CompletionMaxToken(String description) {\n this.description = description;\n }\n\n public String getDescription() {\n return description;\n }\n\n @Override\n public String toString() {\n return description;\n }\n}" }, { "identifier": "TabActionOption", "path": "src/main/java/com/codeshell/intellij/enums/TabActionOption.java", "snippet": "public enum TabActionOption {\n ALL(\"All suggestions\");\n\n private final String description;\n\n TabActionOption(String description) {\n this.description = description;\n }\n\n @Override\n public String toString() {\n return description;\n }\n}" } ]
import com.codeshell.intellij.enums.ChatMaxToken; import com.codeshell.intellij.enums.CompletionMaxToken; import com.codeshell.intellij.enums.TabActionOption; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Objects;
673
package com.codeshell.intellij.settings; @State(name = "CodeShellSettings", storages = @Storage("codeshell_settings.xml")) public class CodeShellSettings implements PersistentStateComponent<Element> { public static final String SETTINGS_TAG = "CodeShellSettings"; private static final String SERVER_ADDRESS_TAG = "SERVER_ADDRESS_URL"; private static final String SAYT_TAG = "SAYT_ENABLED"; private static final String CPU_RADIO_BUTTON_TAG = "CPU_RADIO_BUTTON_ENABLED"; private static final String GPU_RADIO_BUTTON_TAG = "GPU_RADIO_BUTTON_ENABLED"; private static final String TAB_ACTION_TAG = "TAB_ACTION"; private static final String COMPLETION_MAX_TOKENS_TAG = "COMPLETION_MAX_TOKENS"; private static final String CHAT_MAX_TOKENS_TAG = "CHAT_MAX_TOKENS"; private boolean saytEnabled = true; private boolean cpuRadioButtonEnabled = true; private boolean gpuRadioButtonEnabled = false; private String serverAddressURL = "http://127.0.0.1:8080"; private TabActionOption tabActionOption = TabActionOption.ALL;
package com.codeshell.intellij.settings; @State(name = "CodeShellSettings", storages = @Storage("codeshell_settings.xml")) public class CodeShellSettings implements PersistentStateComponent<Element> { public static final String SETTINGS_TAG = "CodeShellSettings"; private static final String SERVER_ADDRESS_TAG = "SERVER_ADDRESS_URL"; private static final String SAYT_TAG = "SAYT_ENABLED"; private static final String CPU_RADIO_BUTTON_TAG = "CPU_RADIO_BUTTON_ENABLED"; private static final String GPU_RADIO_BUTTON_TAG = "GPU_RADIO_BUTTON_ENABLED"; private static final String TAB_ACTION_TAG = "TAB_ACTION"; private static final String COMPLETION_MAX_TOKENS_TAG = "COMPLETION_MAX_TOKENS"; private static final String CHAT_MAX_TOKENS_TAG = "CHAT_MAX_TOKENS"; private boolean saytEnabled = true; private boolean cpuRadioButtonEnabled = true; private boolean gpuRadioButtonEnabled = false; private String serverAddressURL = "http://127.0.0.1:8080"; private TabActionOption tabActionOption = TabActionOption.ALL;
private CompletionMaxToken completionMaxToken = CompletionMaxToken.MEDIUM;
1
2023-10-18 06:29:13+00:00
2k
djkcyl/Shamrock
qqinterface/src/main/java/com/tencent/protofile/join_group_link/join_group_link.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 null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr) {\n return null;\n }\n\n public static ByteStringMicro copyFrom(byte[] bArr, int i2, int i3) {\n return null;\n }\n\n public static ByteStringMicro copyFromUtf8(String str) {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public int size() {\n return 0;\n }\n\n public byte[] toByteArray() {\n return null;\n }\n\n public String toString(String str) {\n return \"\";\n }\n\n public String toStringUtf8() {\n return \"\";\n }\n}" }, { "identifier": "MessageMicro", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/MessageMicro.java", "snippet": "public class MessageMicro<T extends MessageMicro<T>> {\n public final T mergeFrom(byte[] bArr) {\n return null;\n }\n\n public final byte[] toByteArray() {\n return null;\n }\n\n public T get() {\n return null;\n }\n\n public void set(T t) {\n }\n}" }, { "identifier": "PBBoolField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBBoolField.java", "snippet": "public class PBBoolField extends PBPrimitiveField<Boolean> {\n public PBBoolField(boolean z, boolean z2) {\n }\n\n public void set(boolean z) {\n }\n\n public boolean get() {\n return false;\n }\n}" }, { "identifier": "PBBytesField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBBytesField.java", "snippet": "public class PBBytesField extends PBPrimitiveField<ByteStringMicro> {\n public static PBField<ByteStringMicro> __repeatHelper__;\n\n public PBBytesField(ByteStringMicro byteStringMicro, boolean z) {\n }\n\n public ByteStringMicro get() {\n return null;\n }\n\n public void set(ByteStringMicro byteStringMicro) {\n }\n}" }, { "identifier": "PBEnumField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBEnumField.java", "snippet": "public class PBEnumField extends PBPrimitiveField<Integer>{\n public PBEnumField(int i2, boolean z) {\n }\n\n public int get() {\n return 0;\n }\n\n public void set(int i2) {\n }\n\n}" }, { "identifier": "PBField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBField.java", "snippet": "public abstract class PBField<T> {\n public static <T extends MessageMicro<T>> PBRepeatMessageField<T> initRepeatMessage(Class<T> cls) {\n return new PBRepeatMessageField<>(cls);\n }\n\n public static <T> PBRepeatField<T> initRepeat(PBField<T> pBField) {\n return new PBRepeatField<>(pBField);\n }\n\n public static PBUInt32Field initUInt32(int i2) {\n return new PBUInt32Field(i2, false);\n }\n\n public static PBStringField initString(String str) {\n return new PBStringField(str, false);\n }\n\n public static PBBytesField initBytes(ByteStringMicro byteStringMicro) {\n return new PBBytesField(byteStringMicro, false);\n }\n\n public static PBBoolField initBool(boolean z) {\n return new PBBoolField(z, false);\n }\n\n public static PBInt32Field initInt32(int i2) {\n return new PBInt32Field(i2, false);\n }\n\n public static PBUInt64Field initUInt64(long j2) {\n return new PBUInt64Field(j2, false);\n }\n\n public static PBInt64Field initInt64(long j2) {\n return new PBInt64Field(j2, false);\n }\n\n public static PBEnumField initEnum(int i2) {\n return new PBEnumField(i2, false);\n }\n}" }, { "identifier": "PBStringField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBStringField.java", "snippet": "public class PBStringField extends PBPrimitiveField<String>{\n public PBStringField(String str, boolean z) {\n }\n\n public void set(String str, boolean z) {\n }\n\n public void set(String str) {\n }\n\n public String get() {\n return \"\";\n }\n}" }, { "identifier": "PBUInt32Field", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt32Field.java", "snippet": "public class PBUInt32Field extends PBPrimitiveField<Integer> {\n public static PBUInt32Field __repeatHelper__;\n\n public PBUInt32Field(int i2, boolean z) {\n }\n\n public void set(int i2) {\n\n }\n\n public int get() {\n return 0;\n }\n}" }, { "identifier": "PBUInt64Field", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBUInt64Field.java", "snippet": "public class PBUInt64Field extends PBPrimitiveField<Long> {\n public static PBField<Long> __repeatHelper__;\n\n public PBUInt64Field(long i2, boolean z) {\n }\n\n public void set(long i2) {\n\n }\n\n public long get() {\n return 0;\n }\n}" } ]
import com.tencent.mobileqq.pb.ByteStringMicro; import com.tencent.mobileqq.pb.MessageMicro; import com.tencent.mobileqq.pb.PBBoolField; import com.tencent.mobileqq.pb.PBBytesField; import com.tencent.mobileqq.pb.PBEnumField; import com.tencent.mobileqq.pb.PBField; import com.tencent.mobileqq.pb.PBStringField; import com.tencent.mobileqq.pb.PBUInt32Field; import com.tencent.mobileqq.pb.PBUInt64Field;
1,509
package com.tencent.protofile.join_group_link; public class join_group_link { public static class ReqBody extends MessageMicro<ReqBody> { public final PBBoolField get_ark = PBField.initBool(false); public final PBBytesField str_context = PBField.initBytes(null); public final PBBytesField str_url_param = PBField.initBytes(null);
package com.tencent.protofile.join_group_link; public class join_group_link { public static class ReqBody extends MessageMicro<ReqBody> { public final PBBoolField get_ark = PBField.initBool(false); public final PBBytesField str_context = PBField.initBytes(null); public final PBBytesField str_url_param = PBField.initBytes(null);
public final PBEnumField type = PBField.initEnum(1);
4
2023-10-20 10:43:47+00:00
2k