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
jpdev01/asaasSdk
src/main/java/io/github/jpdev/asaassdk/rest/payment/identificationfield/PaymentIdentificationFieldFetcher.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": "Fetcher", "path": "src/main/java/io/github/jpdev/asaassdk/rest/action/Fetcher.java", "snippet": "public abstract class Fetcher<T> {\n\n public T fetch() {\n return fetch(Asaas.getRestClient());\n }\n\n public T fetch(final AsaasRestClient client) {\n try {\n Response response = client.get(getResourceUrl());\n\n return client.getObjectMapper().readValue(response.getContent(), getResourceClass());\n } catch (Exception exception) {\n return null;\n }\n }\n\n public abstract String getResourceUrl();\n\n public abstract Class<T> getResourceClass();\n}" } ]
import io.github.jpdev.asaassdk.http.Domain; import io.github.jpdev.asaassdk.rest.action.Fetcher;
663
package io.github.jpdev.asaassdk.rest.payment.identificationfield; public class PaymentIdentificationFieldFetcher extends Fetcher<PaymentIdentificationField> { final String id; public PaymentIdentificationFieldFetcher(String id) { this.id = id; } @Override public String getResourceUrl() {
package io.github.jpdev.asaassdk.rest.payment.identificationfield; public class PaymentIdentificationFieldFetcher extends Fetcher<PaymentIdentificationField> { final String id; public PaymentIdentificationFieldFetcher(String id) { this.id = id; } @Override public String getResourceUrl() {
return Domain.PAYMENT.addVariableList(this.id, "identificationField");
0
2023-11-12 01:19:17+00:00
2k
GoldenStack/minestom-ca
src/main/java/dev/goldenstack/minestom_ca/parser/Parser.java
[ { "identifier": "Token", "path": "src/main/java/dev/goldenstack/minestom_ca/parser/Scanner.java", "snippet": "public sealed interface Token {\r\n record Identifier(String value) implements Token {\r\n }\r\n\r\n record Constant(String value) implements Token {\r\n }\r\n\r\n record Number(long value) implements Token {\r\n }\r\n\r\n record Offset(long x, long y) implements Token {\r\n }\r\n\r\n record Arrow() implements Token {\r\n }\r\n\r\n record At() implements Token {\r\n }\r\n\r\n record Dollar() implements Token {\r\n }\r\n\r\n record Tilde() implements Token {\r\n }\r\n\r\n record And() implements Token {\r\n }\r\n\r\n record Exclamation() implements Token {\r\n }\r\n\r\n record Comma() implements Token {\r\n }\r\n\r\n record Separator() implements Token {\r\n }\r\n\r\n record LeftBracket() implements Token {\r\n }\r\n\r\n record RightBracket() implements Token {\r\n }\r\n\r\n record Colon() implements Token {\r\n }\r\n\r\n record Equals() implements Token {\r\n }\r\n\r\n record Plus() implements Token {\r\n }\r\n\r\n record Minus() implements Token {\r\n }\r\n\r\n record GreaterThan() implements Token {\r\n }\r\n\r\n record LessThan() implements Token {\r\n }\r\n\r\n record EOF() implements Token {\r\n }\r\n}\r" }, { "identifier": "NAMED", "path": "src/main/java/dev/goldenstack/minestom_ca/Neighbors.java", "snippet": "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);" } ]
import dev.goldenstack.minestom_ca.Program; import dev.goldenstack.minestom_ca.Rule; import dev.goldenstack.minestom_ca.parser.Scanner.Token; import net.minestom.server.coordinate.Point; import net.minestom.server.instance.block.Block; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import static dev.goldenstack.minestom_ca.Neighbors.NAMED;
1,272
package dev.goldenstack.minestom_ca.parser; public final class Parser { private int line; private List<Token> tokens; private int index; private final AtomicInteger stateCounter = new AtomicInteger(0); private final Map<String, Integer> properties = new HashMap<>(); private final List<Rule> rules = new ArrayList<>(); public Parser() { } public void feedTokens(List<Token> tokens) { this.line++; this.tokens = tokens; this.index = 0; while (!isAtEnd()) { List<Rule.Condition> conditions = new ArrayList<>(); List<Rule.Result> results = new ArrayList<>(); while (!(peek() instanceof Token.Arrow)) { conditions.add(nextCondition()); if (peek() instanceof Token.And) advance(); } consume(Token.Arrow.class, "Expected '->'"); while (!(peek() instanceof Token.EOF)) results.add(nextResult()); this.rules.add(new Rule(conditions.size() == 1 ? conditions.get(0) : new Rule.Condition.And(conditions), results)); } } private Rule.Condition nextCondition() { CountPredicate countPredicate = new CountPredicate(1, false, false, 0); if (peek() instanceof Token.LeftBracket) { countPredicate = nextCountPredicate(); } if (peek() instanceof Token.Constant) { // Self block check final Block block = nextBlock(); return new Rule.Condition.Equal(block); } else if (peek() instanceof Token.Exclamation) { // Self block check not advance(); final Token.Constant constant = consume(Token.Constant.class, "Expected constant"); final Block block = Block.fromNamespaceId(constant.value()); if (block == null) throw error("Unknown block " + constant.value()); return new Rule.Condition.Not(new Rule.Condition.Equal(block)); } else if (peek() instanceof Token.Identifier identifier) { advance(); if (!(peek() instanceof Token.At)) { // Self identifier final int index = getIndex(identifier.value()); return switch (advance()) { case Token.Equals ignored -> new Rule.Condition.Equal( new Rule.Expression.Index(index), nextExpression() ); case Token.Exclamation ignored -> new Rule.Condition.Not( new Rule.Condition.Equal( new Rule.Expression.Index(index), nextExpression() )); default -> throw error("Expected operator"); }; } else { // Neighbor block check consume(Token.At.class, "Expected '@'");
package dev.goldenstack.minestom_ca.parser; public final class Parser { private int line; private List<Token> tokens; private int index; private final AtomicInteger stateCounter = new AtomicInteger(0); private final Map<String, Integer> properties = new HashMap<>(); private final List<Rule> rules = new ArrayList<>(); public Parser() { } public void feedTokens(List<Token> tokens) { this.line++; this.tokens = tokens; this.index = 0; while (!isAtEnd()) { List<Rule.Condition> conditions = new ArrayList<>(); List<Rule.Result> results = new ArrayList<>(); while (!(peek() instanceof Token.Arrow)) { conditions.add(nextCondition()); if (peek() instanceof Token.And) advance(); } consume(Token.Arrow.class, "Expected '->'"); while (!(peek() instanceof Token.EOF)) results.add(nextResult()); this.rules.add(new Rule(conditions.size() == 1 ? conditions.get(0) : new Rule.Condition.And(conditions), results)); } } private Rule.Condition nextCondition() { CountPredicate countPredicate = new CountPredicate(1, false, false, 0); if (peek() instanceof Token.LeftBracket) { countPredicate = nextCountPredicate(); } if (peek() instanceof Token.Constant) { // Self block check final Block block = nextBlock(); return new Rule.Condition.Equal(block); } else if (peek() instanceof Token.Exclamation) { // Self block check not advance(); final Token.Constant constant = consume(Token.Constant.class, "Expected constant"); final Block block = Block.fromNamespaceId(constant.value()); if (block == null) throw error("Unknown block " + constant.value()); return new Rule.Condition.Not(new Rule.Condition.Equal(block)); } else if (peek() instanceof Token.Identifier identifier) { advance(); if (!(peek() instanceof Token.At)) { // Self identifier final int index = getIndex(identifier.value()); return switch (advance()) { case Token.Equals ignored -> new Rule.Condition.Equal( new Rule.Expression.Index(index), nextExpression() ); case Token.Exclamation ignored -> new Rule.Condition.Not( new Rule.Condition.Equal( new Rule.Expression.Index(index), nextExpression() )); default -> throw error("Expected operator"); }; } else { // Neighbor block check consume(Token.At.class, "Expected '@'");
final List<Point> targets = NAMED.get(identifier.value());
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/parsers/RewriteParserConfiguration.java
[ { "identifier": "ScopeConfiguration", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/boot/autoconfigure/ScopeConfiguration.java", "snippet": "@AutoConfiguration\npublic class ScopeConfiguration {\n\n\t@Bean\n\tExecutionScope executionScope() {\n\t\treturn new ExecutionScope();\n\t}\n\n\t@Bean\n\tScanScope scanScope() {\n\t\treturn new ScanScope();\n\t}\n\n\t/**\n\t * Register {@link ScanScope} and {@link ExecutionScope}.\n\t */\n\t@Bean\n\tpublic static BeanFactoryPostProcessor beanFactoryPostProcessor(ExecutionScope executionScope,\n\t\t\tScanScope scanScope) {\n\t\treturn beanFactory -> {\n\t\t\tbeanFactory.registerScope(ScanScope.SCOPE_NAME, scanScope);\n\t\t\tbeanFactory.registerScope(ExecutionScope.SCOPE_NAME, executionScope);\n\t\t};\n\t}\n\n\t@Bean\n\t@org.springframework.rewrite.scopes.annotations.ScanScope\n\tProjectMetadata projectMetadata() {\n\t\treturn new ProjectMetadata();\n\t}\n\n\t@Bean\n\t@ConditionalOnMissingBean(name = \"executionContextSupplier\")\n\tSupplier<ExecutionContext> executionContextSupplier() {\n\t\treturn () -> new InMemoryExecutionContext(t -> {\n\t\t\tthrow new RuntimeException(t);\n\t\t});\n\t}\n\n\t@Bean\n\t@org.springframework.rewrite.scopes.annotations.ScanScope\n\tExecutionContext executionContext(ProjectMetadata projectMetadata,\n\t\t\tSupplier<ExecutionContext> executionContextSupplier, MavenPomCache mavenPomCache) {\n\t\tExecutionContext executionContext = executionContextSupplier.get();\n\t\treturn executionContext;\n\t}\n\n}" }, { "identifier": "RewriteParsingEventListenerAdapter", "path": "spring-rewrite-commons-launcher/src/main/java/org/springframework/rewrite/parsers/events/RewriteParsingEventListenerAdapter.java", "snippet": "public class RewriteParsingEventListenerAdapter implements ParsingEventListener {\n\n\tprivate static final Logger LOGGER = LoggerFactory.getLogger(RewriteParsingEventListenerAdapter.class);\n\n\tprivate final ApplicationEventPublisher eventPublisher;\n\n\tpublic RewriteParsingEventListenerAdapter(ApplicationEventPublisher eventPublisher) {\n\t\tthis.eventPublisher = eventPublisher;\n\t}\n\n\t@Override\n\tpublic void intermediateMessage(String stateMessage) {\n\t\teventPublisher.publishEvent(new IntermediateParsingEvent(stateMessage));\n\t}\n\n\t@Override\n\tpublic void startedParsing(Parser.Input input) {\n\t\teventPublisher.publishEvent(new StartedParsingResourceEvent(input));\n\t}\n\n\t@Override\n\tpublic void parsed(Parser.Input input, SourceFile sourceFile) {\n\t\tLOGGER.debug(\"Parsed %s to %s\".formatted(input.getPath(), sourceFile.getSourcePath()));\n\t\teventPublisher.publishEvent(new FinishedParsingResourceEvent(input, sourceFile));\n\t}\n\n}" } ]
import org.openrewrite.ExecutionContext; import org.openrewrite.maven.cache.CompositeMavenPomCache; import org.openrewrite.maven.cache.InMemoryMavenPomCache; import org.openrewrite.maven.cache.MavenPomCache; import org.openrewrite.maven.cache.RocksdbMavenPomCache; import org.openrewrite.maven.utilities.MavenArtifactDownloader; import org.openrewrite.tree.ParsingEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import org.springframework.core.io.ResourceLoader; import org.springframework.rewrite.boot.autoconfigure.ScopeConfiguration; import org.springframework.rewrite.parsers.events.RewriteParsingEventListenerAdapter; import org.springframework.rewrite.parsers.maven.*; import org.springframework.rewrite.scopes.annotations.ScanScope; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.Path; import java.util.function.Consumer;
1,364
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers; /** * Module configuration. * * @author Fabian Krüger */ @AutoConfiguration(after = { ScopeConfiguration.class }) @EnableConfigurationProperties({ SpringRewriteProperties.class }) @Import({ org.springframework.rewrite.scopes.ScanScope.class, ScopeConfiguration.class, RewriteParserMavenConfiguration.class }) public class RewriteParserConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(RewriteParserConfiguration.class); @Bean ProjectScanner projectScanner(ResourceLoader resourceLoader, SpringRewriteProperties springRewriteProperties) { return new ProjectScanner(resourceLoader, springRewriteProperties); } @Bean ProvenanceMarkerFactory provenanceMarkerFactory(MavenProvenanceMarkerFactory mavenPovenanceMarkerFactory) { return new ProvenanceMarkerFactory(mavenPovenanceMarkerFactory); } @Bean @ScanScope JavaParserBuilder javaParserBuilder() { return new JavaParserBuilder(); } @Bean Consumer<Throwable> artifactDownloaderErrorConsumer() { return (t) -> { throw new RuntimeException(t); }; } @Bean MavenModuleParser mavenModuleParser(SpringRewriteProperties springRewriteProperties) { return new MavenModuleParser(springRewriteProperties); } @Bean SourceFileParser sourceFileParser(MavenModuleParser mavenModuleParser) { return new SourceFileParser(mavenModuleParser); } @Bean StyleDetector styleDetector() { return new StyleDetector(); } @Bean @ConditionalOnMissingBean(ParsingEventListener.class) ParsingEventListener parsingEventListener(ApplicationEventPublisher eventPublisher) {
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers; /** * Module configuration. * * @author Fabian Krüger */ @AutoConfiguration(after = { ScopeConfiguration.class }) @EnableConfigurationProperties({ SpringRewriteProperties.class }) @Import({ org.springframework.rewrite.scopes.ScanScope.class, ScopeConfiguration.class, RewriteParserMavenConfiguration.class }) public class RewriteParserConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(RewriteParserConfiguration.class); @Bean ProjectScanner projectScanner(ResourceLoader resourceLoader, SpringRewriteProperties springRewriteProperties) { return new ProjectScanner(resourceLoader, springRewriteProperties); } @Bean ProvenanceMarkerFactory provenanceMarkerFactory(MavenProvenanceMarkerFactory mavenPovenanceMarkerFactory) { return new ProvenanceMarkerFactory(mavenPovenanceMarkerFactory); } @Bean @ScanScope JavaParserBuilder javaParserBuilder() { return new JavaParserBuilder(); } @Bean Consumer<Throwable> artifactDownloaderErrorConsumer() { return (t) -> { throw new RuntimeException(t); }; } @Bean MavenModuleParser mavenModuleParser(SpringRewriteProperties springRewriteProperties) { return new MavenModuleParser(springRewriteProperties); } @Bean SourceFileParser sourceFileParser(MavenModuleParser mavenModuleParser) { return new SourceFileParser(mavenModuleParser); } @Bean StyleDetector styleDetector() { return new StyleDetector(); } @Bean @ConditionalOnMissingBean(ParsingEventListener.class) ParsingEventListener parsingEventListener(ApplicationEventPublisher eventPublisher) {
return new RewriteParsingEventListenerAdapter(eventPublisher);
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,343
/** * 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; @Resource private ChatService chatService; @Resource private RepositoryService repositoryService; @GetMapping("/recommend") public Response recommend() { // TODO 根据关键字(语言?)来推荐项目列表 返回一个项目列表对象 Project return new Response(); } @GetMapping("/search/project") public Response searchProject(@RequestParam String query) { log.info("search project query: {}", query); List<Repository> repositories = null; try { repositories = repositoryService.searchRepository(query); } catch (Exception e) { log.error("search project failed: {}", e.getMessage(), e); return new Response(1, "search project failed"); } return new Response(repositories); } @GetMapping("/search/code") public Response searchCode(@RequestParam String query) {
/** * 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; @Resource private ChatService chatService; @Resource private RepositoryService repositoryService; @GetMapping("/recommend") public Response recommend() { // TODO 根据关键字(语言?)来推荐项目列表 返回一个项目列表对象 Project return new Response(); } @GetMapping("/search/project") public Response searchProject(@RequestParam String query) { log.info("search project query: {}", query); List<Repository> repositories = null; try { repositories = repositoryService.searchRepository(query); } catch (Exception e) { log.error("search project failed: {}", e.getMessage(), e); return new Response(1, "search project failed"); } return new Response(repositories); } @GetMapping("/search/code") public Response searchCode(@RequestParam String query) {
List<FunctionVo> functionVos = codeService.searchCode(query);
3
2023-11-15 08:58:35+00:00
2k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/comparison/MarkedStringTest.java
[ { "identifier": "OutputType", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/OutputType.java", "snippet": "public enum OutputType {\n CONSOLE, LOG, HTML\n}" }, { "identifier": "Fragment", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Fragment.java", "snippet": "public interface Fragment extends CharSequence, Adaptable {\n\n /**\n * Gets the string (either the left or the right part of the comparison) this {@link Fragment} belongs to\n * @return A non-null string\n */\n String getSource();\n\n /**\n * Gets whether this {@link Fragment} represents an insertion (i.e., a part of the line to the right that is missing\n * in the line to the left)\n * @return True or false\n */\n boolean isInsert();\n\n /**\n * Gets whether this {@link Fragment} represents a deletion (i.e., a part of the line to the left that is missing in\n * the line to the right)\n * @return True or false\n */\n boolean isDelete();\n\n /**\n * Gets whether the difference is \"pending\", that is, has not been silenced and will eventually make\n * {@link AnyDiff} report a mismatch\n * @return True or false\n */\n default boolean isPending() {\n return isInsert() || isDelete();\n }\n\n /**\n * Gets whether this {@link Fragment} equals to the provided other string content-wise\n * @param other String value to compare to\n * @return True or false\n */\n default boolean equals(String other) {\n return StringUtils.equals(toString(), other);\n }\n}" } ]
import com.exadel.etoolbox.anydiff.OutputType; import com.exadel.etoolbox.anydiff.diff.Fragment; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Test; import java.util.List;
752
/* * 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 MarkedStringTest { private static final String DEFAULT_TEXT = "Lorem ipsum"; private static final String MARKED_TEXT_1 = "{{eq}} Lorem ipsum{{/}}"; private static final String MARKED_TEXT_2 = "{{del}}Lorem{{/}} {{ins}}ipsum{{/}}"; private static final int DEFAULT_COLUMN = 60; private static final String DELETE_STRING = Marker.DELETE.toConsole(); private static final String INSERT_STRING = Marker.INSERT.toConsole(); private static final String RESET_STRING = Marker.RESET.toConsole(); @Test public void shouldParseSimpleText() { MarkedString side = new MarkedString(DEFAULT_TEXT, false); Assert.assertEquals(DEFAULT_TEXT, side.toString());
/* * 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 MarkedStringTest { private static final String DEFAULT_TEXT = "Lorem ipsum"; private static final String MARKED_TEXT_1 = "{{eq}} Lorem ipsum{{/}}"; private static final String MARKED_TEXT_2 = "{{del}}Lorem{{/}} {{ins}}ipsum{{/}}"; private static final int DEFAULT_COLUMN = 60; private static final String DELETE_STRING = Marker.DELETE.toConsole(); private static final String INSERT_STRING = Marker.INSERT.toConsole(); private static final String RESET_STRING = Marker.RESET.toConsole(); @Test public void shouldParseSimpleText() { MarkedString side = new MarkedString(DEFAULT_TEXT, false); Assert.assertEquals(DEFAULT_TEXT, side.toString());
Assert.assertEquals(DEFAULT_TEXT, stripEnd(side.toText(OutputType.CONSOLE, DEFAULT_COLUMN).get(0)));
0
2023-11-16 14:29:45+00:00
2k
jimbro1000/DriveWire4Rebuild
src/test/java/org/thelair/dw4/drivewire/ports/DWPortManagerTest.java
[ { "identifier": "DWSerialPort", "path": "src/main/java/org/thelair/dw4/drivewire/ports/serial/DWSerialPort.java", "snippet": "public final class DWSerialPort implements DWIPort {\n /**\n * Log appender.\n */\n private static final Logger LOGGER = LogManager.getLogger(DWSerialPort.class);\n /**\n * Serial port definition.\n */\n private SerialPortDef portDef;\n /**\n * Port manager.\n */\n private final DWIPortManager portManager;\n /**\n * concrete com port object.\n */\n private DWISerial comPort;\n /**\n * Serial port handler.\n */\n private final SerialPortHardware portHandler;\n /**\n * Unique port identifier.\n */\n private final int portId;\n\n /**\n * Create serial port with reference to manager.\n * @param manager port manager handling this port\n * @param port identifier\n * @param hardPorts host serial hardware\n */\n public DWSerialPort(\n final DWIPortManager manager,\n final int port,\n final SerialPortHardware hardPorts\n ) {\n this.portManager = manager;\n this.portId = port;\n this.portHandler = hardPorts;\n LOGGER.info(\"Serial port created \" + port);\n }\n @Override\n public void openWith(final BasePortDef port)\n throws InvalidPortTypeDefinition {\n this.portDef = validatePortDef(port);\n this.portDef.setPortId(portId);\n portManager.registerOpenPort(this);\n }\n\n @Override\n public void setPortDef(final BasePortDef port)\n throws InvalidPortTypeDefinition {\n this.portDef = validatePortDef(port);\n }\n\n @Override\n public int identifyPort() {\n return portDef.getPortId();\n }\n\n @Override\n public void closePort() {\n portManager.registerClosedPort(this);\n }\n\n private SerialPortDef validatePortDef(final BasePortDef port)\n throws InvalidPortTypeDefinition {\n if (port.getClass() != SerialPortDef.class) {\n LOGGER.error(\"Invalid port definition provided for a serial port\");\n throw new InvalidPortTypeDefinition(\"Invalid serial port definition\",\n port);\n }\n final SerialPortDef serialDef = (SerialPortDef) port;\n comPort = matchPort(serialDef.getPortName());\n return serialDef;\n }\n\n private DWISerial matchPort(final String portName)\n throws InvalidPortTypeDefinition {\n final DWISerial matchedPort = portHandler.getPortByName(portName);\n if (matchedPort == null) {\n LOGGER.error(\"named serial port is not available\");\n throw new InvalidPortTypeDefinition(\n \"named port is not available\", this.portDef\n );\n }\n return matchedPort;\n }\n\n /**\n * Get serialised port definition.\n *\n * @return port details\n */\n public String getPortDefinition() {\n final StringBuilder stringDef = new StringBuilder();\n final Map<String, Integer> def = portDef.getPortDetail();\n for (final Map.Entry<String, Integer> entry : def.entrySet()) {\n stringDef.append(entry.getKey())\n .append(\" : \")\n .append(entry.getValue())\n .append(\" | \");\n }\n return stringDef.toString();\n }\n}" }, { "identifier": "DWTcpPort", "path": "src/main/java/org/thelair/dw4/drivewire/ports/tcp/DWTcpPort.java", "snippet": "public final class DWTcpPort implements DWIPort {\n /**\n * TCP port definition.\n */\n private TcpPortDef portDef;\n @Override\n public void openWith(final BasePortDef port)\n throws InvalidPortTypeDefinition {\n portDef = validatePortDef(port);\n //register\n }\n\n @Override\n public void setPortDef(final BasePortDef port)\n throws InvalidPortTypeDefinition {\n portDef = validatePortDef(port);\n }\n\n @Override\n public int identifyPort() {\n return DWIPortType.DWPortTypeIdentity.TCP_PORT.getPortType();\n }\n\n @Override\n public void closePort() {\n\n }\n\n /**\n * Serialise port definition as String.\n *\n * @return port definition values\n */\n @Override\n public String getPortDefinition() {\n return \"\";\n }\n\n private TcpPortDef validatePortDef(final BasePortDef port)\n throws InvalidPortTypeDefinition {\n if (port.getClass() == TcpPortDef.class) {\n return (TcpPortDef) port;\n } else {\n throw new InvalidPortTypeDefinition(\"Invalid serial port definition\",\n port);\n }\n }\n}" } ]
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.thelair.dw4.drivewire.ports.serial.DWSerialPort; import org.thelair.dw4.drivewire.ports.tcp.DWTcpPort; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail;
1,426
package org.thelair.dw4.drivewire.ports; /** * Describes drivewire port manager. */ public class DWPortManagerTest { private DWIPortManager portManager; /** * Prepare port manager for tests. */ @BeforeEach public void setup() { portManager = new DWPortManager(); } /** * It should generate null ports when required. */ @Test public void itShouldReturnANullPortOnRequest() { DWIPort actual = portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.NULL_PORT); assertEquals(DWNullPort.class, actual.getClass(), "it should provide a " + "null port"); } /** * It should generate serial ports when required. */ @Test public void itShouldReturnASerialPortOnRequest() { DWIPort actual = portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.SERIAL_PORT);
package org.thelair.dw4.drivewire.ports; /** * Describes drivewire port manager. */ public class DWPortManagerTest { private DWIPortManager portManager; /** * Prepare port manager for tests. */ @BeforeEach public void setup() { portManager = new DWPortManager(); } /** * It should generate null ports when required. */ @Test public void itShouldReturnANullPortOnRequest() { DWIPort actual = portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.NULL_PORT); assertEquals(DWNullPort.class, actual.getClass(), "it should provide a " + "null port"); } /** * It should generate serial ports when required. */ @Test public void itShouldReturnASerialPortOnRequest() { DWIPort actual = portManager.createPortInstance(DWIPortType.DWPortTypeIdentity.SERIAL_PORT);
assertEquals(DWSerialPort.class, actual.getClass(), "it should provide a " +
0
2023-11-18 11:35:16+00:00
2k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/items/attachments/GenericMag.java
[ { "identifier": "GunRenderContext", "path": "src/main/java/sheridan/gunscraft/items/attachments/util/GunRenderContext.java", "snippet": "public class GunRenderContext {\n public boolean occupiedStock = false;\n public boolean occupiedIS = false;\n public boolean occupiedMag = false;\n public boolean occupiedMuzzle = false;\n public boolean occupiedGrip = false;\n public boolean occupiedHandGuard = false;\n}" }, { "identifier": "IGenericGun", "path": "src/main/java/sheridan/gunscraft/items/guns/IGenericGun.java", "snippet": "public interface IGenericGun {\n ResourceLocation getTexture(int index);\n int getCurrentTextureIndex(ItemStack stack);\n boolean preShoot(ItemStack stack, LivingEntity entity, boolean mainHand);\n void shoot(ItemStack stack, LivingEntity entity, boolean mainHand, float spread);\n boolean preReload(ItemStack stack, LivingEntity entity, boolean mainHand);\n void reload(ItemStack stack, LivingEntity entity, boolean mainHand);\n boolean canHoldInOneHand();\n int getMagSize(ItemStack stack);\n void setMagSize(ItemStack stack, int magSize);\n int getAmmoLeft(ItemStack stack);\n void setAmmoLeft(ItemStack stack, int count);\n int getFireMode(ItemStack stack);\n void setFireMode(ItemStack stack, int mode);\n void switchFireMode(ItemStack stack);\n int getShootDelay();\n float getMinSpread(ItemStack stack);\n float getMaxSpread(ItemStack stack);\n boolean isFreeBlot();\n boolean isPistol();\n int getReloadLength(ItemStack stack);\n String getMuzzleFlashState(ItemStack stack);\n int getBurstCount();\n float getAimingSpeed(ItemStack stack);\n float getRecoilUp(ItemStack stack);\n float getRecoilRandom(ItemStack stack);\n float getRecoilDec(ItemStack stack);\n GunAttachmentSlot getSlot(String name);\n List<GunAttachmentSlot> getAllSlots();\n String getSeriesName();\n String getBulletType();\n}" } ]
import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import sheridan.gunscraft.items.attachments.util.GunRenderContext; import sheridan.gunscraft.items.guns.IGenericGun;
702
package sheridan.gunscraft.items.attachments; public class GenericMag extends GenericAttachment{ public int ammoIncrement; public GenericMag(Properties properties, int id, String type, String name, int ammoIncrement) { super(properties, id, type, name); this.ammoIncrement = ammoIncrement; } @Override public void onAttach(ItemStack stack, IGenericGun gun) { gun.setMagSize(stack, gun.getMagSize(stack) + ammoIncrement); } @Override public void onOff(ItemStack stack, IGenericGun gun) { gun.setMagSize(stack, gun.getMagSize(stack) - ammoIncrement); int ammoDec = gun.getAmmoLeft(stack); ammoDec = ammoDec > ammoIncrement ? ammoDec - ammoIncrement : 0; gun.setAmmoLeft(stack, ammoDec); } @Override
package sheridan.gunscraft.items.attachments; public class GenericMag extends GenericAttachment{ public int ammoIncrement; public GenericMag(Properties properties, int id, String type, String name, int ammoIncrement) { super(properties, id, type, name); this.ammoIncrement = ammoIncrement; } @Override public void onAttach(ItemStack stack, IGenericGun gun) { gun.setMagSize(stack, gun.getMagSize(stack) + ammoIncrement); } @Override public void onOff(ItemStack stack, IGenericGun gun) { gun.setMagSize(stack, gun.getMagSize(stack) - ammoIncrement); int ammoDec = gun.getAmmoLeft(stack); ammoDec = ammoDec > ammoIncrement ? ammoDec - ammoIncrement : 0; gun.setAmmoLeft(stack, ammoDec); } @Override
public void handleParams(GunRenderContext params) {
0
2023-11-14 14:00:55+00:00
2k
zpascual/5419-Arm-Example
src/main/java/com/team5419/frc2023/subsystems/Intake.java
[ { "identifier": "Ports", "path": "src/main/java/com/team5419/frc2023/Ports.java", "snippet": "public class Ports {\n\n public static int kArm = 1;\n public static int kWrist = 2;\n public static int kIntake = 3;\n\n public static int kDriver = 0;\n public static int kOperator = 1;\n\n}" }, { "identifier": "ILooper", "path": "src/main/java/com/team5419/frc2023/loops/ILooper.java", "snippet": "public interface ILooper {\n void register(Loop loop);\n}" }, { "identifier": "Loop", "path": "src/main/java/com/team5419/frc2023/loops/Loop.java", "snippet": "public interface Loop {\n\n public void onStart(double timestamp);\n\n public void onLoop(double timestamp);\n\n public void onStop(double timestamp);\n}" }, { "identifier": "Request", "path": "src/main/java/com/team5419/lib/requests/Request.java", "snippet": "public abstract class Request {\n\n\tpublic abstract void act();\n\t\n\tpublic boolean isFinished() {return true;}\n\n\tprivate final List<Prerequisite> prerequisites = new ArrayList<>();\n\n\tpublic Request withPrerequisites(Prerequisite... prereqs) {\n\t\tfor(Prerequisite prereq : prereqs){\n\t\t\tprerequisites.add(prereq);\n\t\t}\n\t\treturn this;\n\t}\n\n\tpublic Request withPrerequisite(Prerequisite prereq) {\n\t\tprerequisites.add(prereq);\n\t\treturn this;\n\t}\n\n\tpublic boolean allowed() {\n\t\treturn prerequisites.stream().allMatch(p -> p.met());\n\t}\n\n\tprivate LambdaRequest.VoidInterface cleanupFunction = () -> {};\n\n\tpublic Request withCleanup(LambdaRequest.VoidInterface cleanupFunction) {\n\t\tthis.cleanupFunction = cleanupFunction;\n\t\treturn this;\n\t}\n\n\tpublic void cleanup() {\n\t\tcleanupFunction.f();\n\t}\n\n}" } ]
import com.ctre.phoenix6.hardware.TalonFX; import com.team5419.frc2023.Ports; import com.team5419.frc2023.loops.ILooper; import com.team5419.frc2023.loops.Loop; import com.team5419.lib.requests.Request; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
748
package com.team5419.frc2023.subsystems; public class Intake extends Subsystem { public static Intake mInstance = null; public static Intake getInstance() { if (mInstance == null) { return mInstance = new Intake(); } return mInstance; } protected final TalonFX motor = new TalonFX(Ports.kIntake); public Intake() { } public enum State { IDLE(0.0), INTAKE(6.0), OUTTAKE(12.0); public final double voltage; State (double voltage) { this.voltage = voltage; } } private State currentState = State.IDLE; public State getState() { return currentState; } public void setState(State wantedState) { if (currentState != wantedState) { currentState = wantedState; } } @Override public void registerEnabledLoops(ILooper mEnabledLooper) {
package com.team5419.frc2023.subsystems; public class Intake extends Subsystem { public static Intake mInstance = null; public static Intake getInstance() { if (mInstance == null) { return mInstance = new Intake(); } return mInstance; } protected final TalonFX motor = new TalonFX(Ports.kIntake); public Intake() { } public enum State { IDLE(0.0), INTAKE(6.0), OUTTAKE(12.0); public final double voltage; State (double voltage) { this.voltage = voltage; } } private State currentState = State.IDLE; public State getState() { return currentState; } public void setState(State wantedState) { if (currentState != wantedState) { currentState = wantedState; } } @Override public void registerEnabledLoops(ILooper mEnabledLooper) {
mEnabledLooper.register(new Loop() {
2
2023-11-14 06:44:40+00:00
2k
Ouest-France/querydsl-postgrest
src/main/java/fr/ouestfrance/querydsl/postgrest/mappers/NotInMapper.java
[ { "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}" }, { "identifier": "PostgrestRequestException", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/exceptions/PostgrestRequestException.java", "snippet": "public class PostgrestRequestException extends RuntimeException {\n\n /**\n * PostgrestRequestException constructor\n *\n * @param resourceName resource name\n * @param message cause message\n */\n public PostgrestRequestException(String resourceName, String message) {\n this(resourceName, message, null);\n }\n\n\n /**\n * PostgrestRequestException constructor\n *\n * @param resourceName resource name\n * @param message cause message\n * @param cause exception raised\n */\n\n public PostgrestRequestException(String resourceName, String message, Throwable cause) {\n this(\"Error on querying \" + resourceName + \" cause by \" + message, cause);\n }\n\n /**\n * PostgrestRequestException constructor\n *\n * @param message cause message\n */\n public PostgrestRequestException(String message) {\n super(message);\n }\n\n /**\n * PostgrestRequestException constructor\n *\n * @param message cause message\n * @param cause exception raised\n */\n public PostgrestRequestException(String message, Throwable cause) {\n super(message, cause);\n }\n}" }, { "identifier": "QueryFilter", "path": "src/main/java/fr/ouestfrance/querydsl/postgrest/model/impl/QueryFilter.java", "snippet": "@Getter\n@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\npublic class QueryFilter implements Filter, FilterVisitor {\n\n /**\n * Field name\n */\n private final String key;\n /**\n * operator (eq, ne, gt, ...).\n */\n private final String operator;\n /**\n * Value\n */\n private final Object value;\n\n /**\n * Static method to build a simple filter\n *\n * @param fieldName name of the query param\n * @param operator operator of the query param\n * @param value value of the query param\n * @return Simple filter\n */\n public static Filter of(String fieldName, String operator, Object value) {\n return new QueryFilter(fieldName, operator, value);\n }\n\n @Override\n public void accept(QueryFilterVisitor visitor) {\n visitor.visit(this);\n }\n\n @Override\n public String getKey() {\n return key;\n }\n}" } ]
import java.util.Collection; import java.util.stream.Collectors; import fr.ouestfrance.querydsl.FilterOperation; import fr.ouestfrance.querydsl.postgrest.model.Filter; import fr.ouestfrance.querydsl.postgrest.model.exceptions.PostgrestRequestException; import fr.ouestfrance.querydsl.postgrest.model.impl.QueryFilter;
783
package fr.ouestfrance.querydsl.postgrest.mappers; /** * Concrete mapping for notIn */ public class NotInMapper extends AbstractMapper { @Override
package fr.ouestfrance.querydsl.postgrest.mappers; /** * Concrete mapping for notIn */ public class NotInMapper extends AbstractMapper { @Override
public Filter getFilter(String field, Object value) {
0
2023-11-14 10:45:54+00:00
2k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/fragments/AboutFragment.java
[ { "identifier": "AboutAdapter", "path": "app/src/main/java/com/threethan/questpatcher/adapters/AboutAdapter.java", "snippet": "public class AboutAdapter extends RecyclerView.Adapter<AboutAdapter.ViewHolder> {\n\n private static List<sSerializableItems> data;\n\n public AboutAdapter(List<sSerializableItems> data) {\n AboutAdapter.data = data;\n }\n\n @NonNull\n @Override\n public AboutAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n View rowItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_view_about, parent, false);\n return new AboutAdapter.ViewHolder(rowItem);\n }\n\n @Override\n public void onBindViewHolder(@NonNull AboutAdapter.ViewHolder holder, int position) {\n holder.Title.setText(data.get(position).getTextOne());\n holder.Description.setText(data.get(position).getTextTwo());\n if (sThemeUtils.isDarkTheme(holder.Title.getContext())) {\n holder.Title.setTextColor(APKEditorUtils.getThemeAccentColor(holder.Title.getContext()));\n }\n if (position != 0) {\n holder.mIcon.setColorFilter(sThemeUtils.isDarkTheme(holder.Title.getContext()) ? Color.WHITE : Color.BLACK);\n }\n holder.mIcon.setImageDrawable(data.get(position).getIcon());\n holder.mRVLayout.setOnClickListener(v -> {\n if (data.get(position).getTextThree() != null) {\n sCommonUtils.launchUrl(data.get(position).getTextThree(), (Activity) v.getContext());\n } else if (position == 0) {\n Intent settings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n settings.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n Uri uri = Uri.fromParts(\"package\", BuildConfig.APPLICATION_ID, null);\n settings.setData(uri);\n v.getContext().startActivity(settings);\n } else if (position == 5) {\n Intent documentation = new Intent(v.getContext(), DocumentationActivity.class);\n v.getContext().startActivity(documentation);\n } else if (position == 6) {\n new sTranslatorUtils(v.getContext().getString(R.string.app_name_short), \"https://poeditor.com/join/project?hash=QztabxONOp\",\n (Activity) v.getContext()).show();\n } else if (position == 7) {\n new sCreditsUtils(AppSettings.getCredits(v.getContext()),\n sCommonUtils.getDrawable(R.mipmap.ic_launcher, v.getContext()),\n sCommonUtils.getDrawable(R.drawable.ic_back, v.getContext()),\n sCommonUtils.getColor(R.color.colorBlue, v.getContext()),\n 18, v.getContext().getString(R.string.app_name), \"2023-2024, APK Explorer & Editor\",\n BuildConfig.VERSION_NAME).launchCredits(v.getContext());\n } else {\n Intent share_app = new Intent();\n share_app.setAction(Intent.ACTION_SEND);\n share_app.putExtra(Intent.EXTRA_TEXT, v.getContext().getString(R.string.share_summary, BuildConfig.VERSION_NAME));\n share_app.setType(\"text/plain\");\n Intent shareIntent = Intent.createChooser(share_app, v.getContext().getString(R.string.share_with));\n v.getContext().startActivity(shareIntent);\n }\n });\n }\n\n @Override\n public int getItemCount() {\n return data.size();\n }\n\n public static class ViewHolder extends RecyclerView.ViewHolder {\n private final AppCompatImageButton mIcon;\n private final MaterialTextView Description, Title;\n private final LinearLayoutCompat mRVLayout;\n\n public ViewHolder(View view) {\n super(view);\n this.mIcon = view.findViewById(R.id.icon);\n this.Title = view.findViewById(R.id.title);\n this.Description = view.findViewById(R.id.description);\n this.mRVLayout = view.findViewById(R.id.rv_about);\n }\n }\n\n}" }, { "identifier": "APKEditorUtils", "path": "app/src/main/java/com/threethan/questpatcher/utils/APKEditorUtils.java", "snippet": "public class APKEditorUtils {\n\n public static int getThemeAccentColor(Context context) {\n TypedValue value = new TypedValue();\n context.getTheme().resolveAttribute(R.attr.colorAccent, value, true);\n return value.data;\n }\n\n public static boolean isFullVersion(Context context) {\n return true;\n }\n\n public static CharSequence fromHtml(String text) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\n return Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY);\n } else {\n return Html.fromHtml(text);\n }\n }\n\n public static void unzip(String zip, String path) {\n try (ZipFile zipFile = new ZipFile(zip)) {\n zipFile.extractAll(path);\n } catch (IOException ignored) {\n }\n }\n\n public static void zip(File path, File zip) {\n try (ZipFile zipFile = new ZipFile(zip)) {\n for (File mFile : Objects.requireNonNull(path.listFiles())) {\n if (mFile.isDirectory()) {\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setCompressionMethod(CompressionMethod.STORE);\n zipFile.addFolder(mFile, zipParameters);\n } else {\n ZipParameters zipParameters = new ZipParameters();\n zipParameters.setCompressionMethod(CompressionMethod.STORE);\n zipFile.addFile(mFile, zipParameters);\n }\n }\n } catch (IOException ignored) {\n }\n }\n\n public static boolean isDocumentsUI(Uri uri) {\n return \"com.android.providers.downloads.documents\".equals(uri.getAuthority());\n }\n\n}" } ]
import android.content.res.Configuration; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.threethan.questpatcher.BuildConfig; import com.threethan.questpatcher.R; import com.threethan.questpatcher.adapters.AboutAdapter; import com.threethan.questpatcher.utils.APKEditorUtils; import java.util.ArrayList; import java.util.List; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sSerializableItems;
1,527
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021 */ public class AboutFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_about, container, false); RecyclerView mRecyclerView = mRootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), sCommonUtils.getOrientation(requireActivity()) == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2));
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 04, 2021 */ public class AboutFragment extends Fragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_about, container, false); RecyclerView mRecyclerView = mRootView.findViewById(R.id.recycler_view); mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), sCommonUtils.getOrientation(requireActivity()) == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2));
AboutAdapter mRecycleViewAdapter = new AboutAdapter(getData());
0
2023-11-18 15:13:30+00:00
2k
jenkinsci/harbor-plugin
src/main/java/io/jenkins/plugins/harbor/steps/WaitForHarborWebhookStep.java
[ { "identifier": "Severity", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Severity.java", "snippet": "public enum Severity {\n None(\"None\"),\n Unknown(\"Unknown\"),\n Negligible(\"Negligible\"),\n Low(\"Low\"),\n Medium(\"Medium\"),\n High(\"High\"),\n Critical(\"Critical\");\n\n @JsonValue\n private final String severity;\n\n Severity(String severity) {\n this.severity = severity;\n }\n\n public String getSeverity() {\n return severity;\n }\n}" }, { "identifier": "HarborPluginGlobalConfiguration", "path": "src/main/java/io/jenkins/plugins/harbor/configuration/HarborPluginGlobalConfiguration.java", "snippet": "@Extension\npublic class HarborPluginGlobalConfiguration extends GlobalConfiguration implements Serializable {\n private static final Logger logger = Logger.getLogger(HarborPluginGlobalConfiguration.class.getName());\n\n private List<HarborServer> servers;\n\n public HarborPluginGlobalConfiguration() {\n load();\n }\n\n public static HarborPluginGlobalConfiguration get() {\n return GlobalConfiguration.all().get(HarborPluginGlobalConfiguration.class);\n }\n\n public static HarborServer getHarborServerByName(String name) {\n return get().getServers().stream()\n .filter(harborServer -> StringUtils.equals(name, harborServer.getName()))\n .findFirst()\n .orElseThrow(() -> new HarborException(\"The Harbor Server Name Is Invalid\"));\n }\n\n public List<HarborServer> getServers() {\n return servers;\n }\n\n public void setServers(List<HarborServer> servers) {\n this.servers = servers;\n }\n\n @Override\n public boolean configure(StaplerRequest req, JSONObject json) throws FormException {\n req.bindJSON(this, json);\n save();\n return true;\n }\n}" }, { "identifier": "HarborServer", "path": "src/main/java/io/jenkins/plugins/harbor/configuration/HarborServer.java", "snippet": "public class HarborServer extends AbstractDescribableImpl<HarborServer> implements Serializable {\n private static final long serialVersionUID = 1L;\n private static final Logger logger = Logger.getLogger(HarborServer.class.getName());\n private String name;\n private String baseUrl;\n private String webhookSecretId;\n private boolean skipTlsVerify = false;\n private boolean debugLogging = false;\n\n @DataBoundConstructor\n public HarborServer(\n String name, String baseUrl, String webhookSecretId, boolean skipTlsVerify, boolean debugLogging) {\n this.name = name;\n this.baseUrl = baseUrl;\n this.webhookSecretId = webhookSecretId;\n this.skipTlsVerify = skipTlsVerify;\n this.debugLogging = debugLogging;\n }\n\n public String getName() {\n return name;\n }\n\n @DataBoundSetter\n public void setName(String name) {\n this.name = name;\n }\n\n public String getBaseUrl() {\n return baseUrl;\n }\n\n @DataBoundSetter\n public void setBaseUrl(String baseUrl) {\n this.baseUrl = baseUrl;\n }\n\n public String getWebhookSecretId() {\n return webhookSecretId;\n }\n\n @DataBoundSetter\n public void setWebhookSecretId(String webhookSecretId) {\n this.webhookSecretId = webhookSecretId;\n }\n\n public boolean isSkipTlsVerify() {\n return skipTlsVerify;\n }\n\n @DataBoundSetter\n public void setSkipTlsVerify(boolean skipTlsVerify) {\n this.skipTlsVerify = skipTlsVerify;\n }\n\n public boolean isDebugLogging() {\n return debugLogging;\n }\n\n @DataBoundSetter\n public void setDebugLogging(boolean debugLogging) {\n this.debugLogging = debugLogging;\n }\n\n @Extension\n public static class DescriptorImpl extends Descriptor<HarborServer> {\n /**\n * Checks that the supplied URL is valid.\n *\n * @param value the URL to check.\n * @return the validation results.\n */\n @SuppressWarnings({\"unused\", \"lgtm[jenkins/csrf]\"})\n public static FormValidation doCheckBaseUrl(@QueryParameter String value) {\n if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {\n return FormValidation.error(\"You do not have sufficient permissions.\");\n }\n\n try {\n new URL(value);\n } catch (MalformedURLException e) {\n return FormValidation.error(\"Invalid URL: \" + e.getMessage());\n }\n return FormValidation.ok();\n }\n\n @SuppressWarnings({\"unused\", \"lgtm[jenkins/csrf]\"})\n public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) {\n if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {\n return new StandardListBoxModel().includeCurrentValue(webhookSecretId);\n }\n\n return new StandardListBoxModel()\n .includeEmptyValue()\n .includeMatchingAs(\n ACL.SYSTEM,\n Jenkins.get(),\n StringCredentials.class,\n Collections.emptyList(),\n CredentialsMatchers.always());\n }\n\n @Override\n public String getDisplayName() {\n return \"Harbor Server\";\n }\n }\n}" } ]
import com.cloudbees.plugins.credentials.CredentialsMatchers; import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardListBoxModel; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import com.cloudbees.plugins.credentials.common.UsernamePasswordCredentials; import com.google.common.collect.ImmutableSet; import hudson.EnvVars; import hudson.Extension; import hudson.FilePath; import hudson.Launcher; import hudson.model.Item; import hudson.model.Run; import hudson.model.TaskListener; import hudson.security.ACL; import hudson.util.ListBoxModel; import io.jenkins.plugins.harbor.client.models.Severity; import io.jenkins.plugins.harbor.configuration.HarborPluginGlobalConfiguration; import io.jenkins.plugins.harbor.configuration.HarborServer; import java.io.Serializable; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.logging.Logger; import org.jenkinsci.plugins.workflow.steps.Step; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepDescriptor; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.kohsuke.stapler.AncestorInPath; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.DataBoundSetter;
1,596
package io.jenkins.plugins.harbor.steps; public class WaitForHarborWebhookStep extends Step implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(WaitForHarborWebhookStep.class.getName()); private String server; private String credentialsId; private String fullImageName;
package io.jenkins.plugins.harbor.steps; public class WaitForHarborWebhookStep extends Step implements Serializable { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(WaitForHarborWebhookStep.class.getName()); private String server; private String credentialsId; private String fullImageName;
private Severity severity;
0
2023-11-11 14:54:53+00:00
2k
wangxianhui111/xuechengzaixian
xuecheng-plus-generator/src/main/java/com/xuecheng/content/service/impl/TeachplanServiceImpl.java
[ { "identifier": "Teachplan", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/Teachplan.java", "snippet": "@Data\n@TableName(\"teachplan\")\npublic class Teachplan implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 教学计划id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 课程计划名称\n */\n private String pname;\n\n /**\n * 课程计划父级Id\n */\n private Long parentid;\n\n /**\n * 层级,分为1、2、3级\n */\n private Integer grade;\n\n /**\n * 课程类型:1视频、2文档\n */\n private String mediaType;\n\n /**\n * 开始直播时间\n */\n private LocalDateTime startTime;\n\n /**\n * 直播结束时间\n */\n private LocalDateTime endTime;\n\n /**\n * 章节及课程时介绍\n */\n private String description;\n\n /**\n * 时长,单位时:分:秒\n */\n private String timelength;\n\n /**\n * 排序字段\n */\n private Integer orderby;\n\n /**\n * 课程标识\n */\n private Long courseId;\n\n /**\n * 课程发布标识\n */\n private Long coursePubId;\n\n /**\n * 状态(1正常 0删除)\n */\n private Integer status;\n\n /**\n * 是否支持试学或预览(试看)\n */\n private String isPreview;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 修改时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime changeDate;\n\n\n}" }, { "identifier": "TeachplanMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/TeachplanMapper.java", "snippet": "public interface TeachplanMapper extends BaseMapper<Teachplan> {\n\n // 查询课程计划(组成树形结构)\n List<TeachplanDto> selectTreeNodes(Long courseId);\n\n}" }, { "identifier": "TeachplanService", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/TeachplanService.java", "snippet": "public interface TeachplanService {\n\n /**\n * 查询课程计划树形结构\n *\n * @param courseId 课程id\n * @return 课程计划树形结构\n */\n List<TeachplanDto> findTeachplanTree(Long courseId);\n\n /**\n * 保存课程计划(新增/修改)\n *\n * @param teachplan 课程计划\n */\n void saveTeachplan(SaveTeachplanDto teachplan);\n\n /**\n * 教学计划绑定媒资\n *\n * @param bindTeachplanMediaDto 教学计划-媒资管理绑定数据\n * @return {@link com.xuecheng.content.model.po.TeachplanMedia}\n * @author Mr.M\n * @since 2022/9/14 22:20\n */\n TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto);\n\n /**\n * 删除指定教学计划-媒资绑定信息\n *\n * @param teachplanId 教学计划id\n * @param mediaId 媒资id\n */\n void deleteTeachplanMedia(Long teachplanId, String mediaId);\n\n}" } ]
import com.xuecheng.content.model.po.Teachplan; import com.xuecheng.content.mapper.TeachplanMapper; import com.xuecheng.content.service.TeachplanService; 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;
1,141
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 TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {
1
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;
830
package com.dynatrace.research.shufflebench; public class AggregateFunction extends KeyedProcessFunction<String, Tuple2<String, TimestampedRecord>, Tuple2<String, ConsumerEvent>> {
package com.dynatrace.research.shufflebench; public class AggregateFunction extends KeyedProcessFunction<String, Tuple2<String, TimestampedRecord>, Tuple2<String, ConsumerEvent>> {
private final StatefulConsumer consumer;
3
2023-11-17 08:53:15+00:00
2k
KafeinDev/InteractiveNpcs
src/main/java/dev/kafein/interactivenpcs/command/CommandAdapter.java
[ { "identifier": "RegisteredTabCompletion", "path": "src/main/java/dev/kafein/interactivenpcs/command/completion/RegisteredTabCompletion.java", "snippet": "public final class RegisteredTabCompletion {\n private final int index;\n private final TabCompletion tabCompletion;\n\n public RegisteredTabCompletion(int index, TabCompletion tabCompletion) {\n this.index = index;\n this.tabCompletion = tabCompletion;\n }\n\n public static RegisteredTabCompletion of(int index, TabCompletion tabCompletion) {\n return new RegisteredTabCompletion(index, tabCompletion);\n }\n\n public int getIndex() {\n return this.index;\n }\n\n public TabCompletion getTabCompletion() {\n return this.tabCompletion;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof RegisteredTabCompletion)) {\n return false;\n }\n if (obj == this) {\n return true;\n }\n\n RegisteredTabCompletion other = (RegisteredTabCompletion) obj;\n return Objects.equals(this.index, other.index) && Objects.equals(this.tabCompletion, other.tabCompletion);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(this.index, this.tabCompletion);\n }\n\n @Override\n public String toString() {\n return \"RegisteredTabCompletion{\" +\n \"index=\" + this.index +\n \", tabCompletion=\" + this.tabCompletion +\n \"}\";\n }\n}" }, { "identifier": "TabCompletion", "path": "src/main/java/dev/kafein/interactivenpcs/command/completion/TabCompletion.java", "snippet": "@FunctionalInterface\npublic interface TabCompletion extends Function<CommandSender, List<String>> {\n}" } ]
import java.util.Arrays; import java.util.List; import com.google.common.collect.ImmutableList; import dev.kafein.interactivenpcs.command.completion.RegisteredTabCompletion; import dev.kafein.interactivenpcs.command.completion.TabCompletion; import org.bukkit.command.CommandSender; import org.bukkit.command.defaults.BukkitCommand; import org.jetbrains.annotations.NotNull;
1,201
/* * MIT License * * Copyright (c) 2023 Kafein * * 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 dev.kafein.interactivenpcs.command; final class CommandAdapter extends BukkitCommand { private final Command command; CommandAdapter(Command command) { super(command.getName(), command.getDescription(), command.getUsage(), command.getAliases()); this.command = command; } @Override public boolean execute(@NotNull org.bukkit.command.CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { if (!getAliases().contains(commandLabel)) { return false; } if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) { //TODO: Send message return true; } if (args.length == 0) { this.command.execute(sender, args); } else { Command subCommand = this.command.findSubCommand(args); if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) { //TODO: Send message return true; } String[] subCommandArgs = Arrays.copyOfRange(args, this.command.findSubCommandIndex(args), args.length); subCommand.execute(sender, subCommandArgs); } return true; } @Override public @NotNull List<String> tabComplete(@NotNull org.bukkit.command.CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) { return ImmutableList.of(); } if (args.length == 0) { return complete(this.command, sender, 0); } else { Command subCommand = this.command.findSubCommand(args); if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) { return ImmutableList.of(); } int subCommandIndex = this.command.findSubCommandIndex(args); return complete(subCommand, sender, (args.length - subCommandIndex) - 1); } } private List<String> complete(@NotNull Command command, @NotNull CommandSender commandSender, int index) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (Command subCommand : command.getSubCommands()) { builder.addAll(subCommand.getAliases()); } for (RegisteredTabCompletion registeredTabCompletion : command.getTabCompletions(index)) {
/* * MIT License * * Copyright (c) 2023 Kafein * * 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 dev.kafein.interactivenpcs.command; final class CommandAdapter extends BukkitCommand { private final Command command; CommandAdapter(Command command) { super(command.getName(), command.getDescription(), command.getUsage(), command.getAliases()); this.command = command; } @Override public boolean execute(@NotNull org.bukkit.command.CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { if (!getAliases().contains(commandLabel)) { return false; } if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) { //TODO: Send message return true; } if (args.length == 0) { this.command.execute(sender, args); } else { Command subCommand = this.command.findSubCommand(args); if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) { //TODO: Send message return true; } String[] subCommandArgs = Arrays.copyOfRange(args, this.command.findSubCommandIndex(args), args.length); subCommand.execute(sender, subCommandArgs); } return true; } @Override public @NotNull List<String> tabComplete(@NotNull org.bukkit.command.CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException { if (this.command.getPermission() != null && !sender.hasPermission(this.command.getPermission())) { return ImmutableList.of(); } if (args.length == 0) { return complete(this.command, sender, 0); } else { Command subCommand = this.command.findSubCommand(args); if (subCommand.getPermission() != null && !sender.hasPermission(subCommand.getPermission())) { return ImmutableList.of(); } int subCommandIndex = this.command.findSubCommandIndex(args); return complete(subCommand, sender, (args.length - subCommandIndex) - 1); } } private List<String> complete(@NotNull Command command, @NotNull CommandSender commandSender, int index) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (Command subCommand : command.getSubCommands()) { builder.addAll(subCommand.getAliases()); } for (RegisteredTabCompletion registeredTabCompletion : command.getTabCompletions(index)) {
TabCompletion tabCompletion = registeredTabCompletion.getTabCompletion();
1
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;
986
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( location, new Vector(-(amount*0.05) + (0.1*i), Y_VALUE, 0), this.location.getYaw(), 0, 0); ItemDisplay skullDisplay = (ItemDisplay) location.getWorld().spawnEntity( displayLocation, EntityType.ITEM_DISPLAY); skullDisplay.setItemStack(this.skull); Transformation skullTransformation = skullDisplay.getTransformation(); skullTransformation.getScale().set(0.2); skullDisplay.setTransformation(skullTransformation); this.skullDisplays.add(skullDisplay); } } @Override public void destroy() { this.skullDisplays.forEach(Entity::remove); } /** * Plays pressing animation. */ public void press() {
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( location, new Vector(-(amount*0.05) + (0.1*i), Y_VALUE, 0), this.location.getYaw(), 0, 0); ItemDisplay skullDisplay = (ItemDisplay) location.getWorld().spawnEntity( displayLocation, EntityType.ITEM_DISPLAY); skullDisplay.setItemStack(this.skull); Transformation skullTransformation = skullDisplay.getTransformation(); skullTransformation.getScale().set(0.2); skullDisplay.setTransformation(skullTransformation); this.skullDisplays.add(skullDisplay); } } @Override public void destroy() { this.skullDisplays.forEach(Entity::remove); } /** * Plays pressing animation. */ public void press() {
new TypeWriterButtonComponentRunnable(this).runTaskTimer(TypewriterPlugin.getInstance(), 0, 1);
0
2023-11-18 20:44:30+00:00
2k
Nurislom373/SpringMicroservice
Observability/Grafana/src/main/java/og/khasanof/grafana/factories/handler/DefaultObservationHandlerFactory.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": "IObservationHandler", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/IObservationHandler.java", "snippet": "public interface IObservationHandler extends ObservationHandler<Observation.Context> {\n\n void onStart(Observation.Context context, boolean moveToNext);\n\n void onStop(Observation.Context context, boolean moveToNext);\n\n ObserveType observeType();\n\n @Override\n default boolean supportsContext(Observation.Context context) {\n return true;\n }\n\n}" }, { "identifier": "ResourceContext", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/context/ResourceContext.java", "snippet": "public interface ResourceContext {\n\n IObservationHandler get(ObserveType key);\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": "Resource", "path": "Observability/Grafana/src/main/java/og/khasanof/grafana/models/resource/Resource.java", "snippet": "public interface Resource {\n\n String getName(); // resource name must be unique!\n\n String getUri();\n\n HttpMethod getMethod();\n\n Set<ObserveType> getObserveTypes();\n\n}" } ]
import og.khasanof.grafana.AbstractObservationHandler; import og.khasanof.grafana.IObservationHandler; import og.khasanof.grafana.context.ResourceContext; import og.khasanof.grafana.enumeration.ObserveType; import og.khasanof.grafana.models.resource.Resource; import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.Set;
946
package og.khasanof.grafana.factories.handler; /** * @author Nurislom * @see og.khasanof.grafana.factories.handler * @since 12/16/2023 11:50 AM */ @Component public class DefaultObservationHandlerFactory implements ObservationHandlerFactory { private final ResourceContext context; public DefaultObservationHandlerFactory(ResourceContext context) { this.context = context; } @Override
package og.khasanof.grafana.factories.handler; /** * @author Nurislom * @see og.khasanof.grafana.factories.handler * @since 12/16/2023 11:50 AM */ @Component public class DefaultObservationHandlerFactory implements ObservationHandlerFactory { private final ResourceContext context; public DefaultObservationHandlerFactory(ResourceContext context) { this.context = context; } @Override
public IObservationHandler create(Resource resource) {
1
2023-11-18 07:57:34+00:00
2k
ZhiQinIsZhen/dubbo-springboot3
dubbo-service/dubbo-service-staff/staff-biz/src/main/java/com/liyz/boot3/service/staff/service/impl/StaffLoginLogServiceImpl.java
[ { "identifier": "Device", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/enums/Device.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum Device {\n MOBILE(1, \"移动端\"),\n WEB(2, \"网页端\"),\n ;\n\n private final int type;\n private final String desc;\n\n public static Device getByType(int type) {\n for (Device device : Device.values()) {\n if (type == device.type) {\n return device;\n }\n }\n return null;\n }\n\n @Override\n public String toString() {\n return type + \":\" + desc;\n }\n}" }, { "identifier": "StaffLoginLogMapper", "path": "dubbo-service/dubbo-service-staff/staff-dao/src/main/java/com/liyz/boot3/service/staff/dao/StaffLoginLogMapper.java", "snippet": "public interface StaffLoginLogMapper extends BaseMapper<StaffLoginLogDO> {\n}" }, { "identifier": "StaffLoginLogDO", "path": "dubbo-service/dubbo-service-staff/staff-dao/src/main/java/com/liyz/boot3/service/staff/model/StaffLoginLogDO.java", "snippet": "@Getter\n@Setter\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(\"staff_login_log\")\npublic class StaffLoginLogDO extends BaseDO implements Serializable {\n @Serial\n private static final long serialVersionUID = 3070437801653890936L;\n\n @TableId(type = IdType.AUTO)\n private Long id;\n\n private Long staffId;\n\n /**\n * 登录方式:1:手机;2:邮箱\n */\n private Integer loginType;\n\n private Integer device;\n\n private Date loginTime;\n\n private String ip;\n}" }, { "identifier": "StaffLoginLogService", "path": "dubbo-service/dubbo-service-staff/staff-biz/src/main/java/com/liyz/boot3/service/staff/service/StaffLoginLogService.java", "snippet": "public interface StaffLoginLogService extends IService<StaffLoginLogDO> {\n\n /**\n * 获取上次登录时间\n *\n * @param staffId 员工ID\n * @param device 设备类型\n * @return 上次登录时间\n */\n Date lastLoginTime(Long staffId, Device device);\n}" } ]
import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.liyz.boot3.service.auth.enums.Device; import com.liyz.boot3.service.staff.dao.StaffLoginLogMapper; import com.liyz.boot3.service.staff.model.StaffLoginLogDO; import com.liyz.boot3.service.staff.service.StaffLoginLogService; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.Date; import java.util.Objects;
788
package com.liyz.boot3.service.staff.service.impl; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/6/15 14:02 */ @Service public class StaffLoginLogServiceImpl extends ServiceImpl<StaffLoginLogMapper, StaffLoginLogDO> implements StaffLoginLogService { /** * 获取上次登录时间 * * @param staffId 员工ID * @param device 设备类型 * @return 上次登录时间 */ @Override
package com.liyz.boot3.service.staff.service.impl; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/6/15 14:02 */ @Service public class StaffLoginLogServiceImpl extends ServiceImpl<StaffLoginLogMapper, StaffLoginLogDO> implements StaffLoginLogService { /** * 获取上次登录时间 * * @param staffId 员工ID * @param device 设备类型 * @return 上次登录时间 */ @Override
public Date lastLoginTime(Long staffId, Device device) {
0
2023-11-13 01:28:21+00:00
2k
glowingstone124/QAPI3
src/main/java/org/qo/Main.java
[ { "identifier": "BackupDatabase", "path": "src/main/java/org/qo/server/BackupDatabase.java", "snippet": "public class BackupDatabase extends TimerTask {\n public static String dbName = \"qouser\";\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyyMMdd_HHmmss\");\n String formattedDate = dateFormat.format(new Date());\n String path = \"database/backup_\" + formattedDate + \".sql\";\n @Override\n public void run() {\n if (!Files.exists(Path.of(\"database\"))){\n try {\n Files.createDirectory(Path.of(\"database\"));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n try {\n Process process = Runtime.getRuntime().exec(\"mysqldump \" + dbName + \" > \" + path);\n int exitCode = process.waitFor();\n if (exitCode == 0) {\n Logger.log(\"Database backup complete.\", Logger.LogLevel.INFO);\n upload(path);\n } else {\n Logger.log(\"ERROR IN backup DATABASE!\", Logger.LogLevel.ERROR);\n upload(path);\n }\n } catch (IOException | InterruptedException e) {\n Logger.log(\"Exception caused!\", Logger.LogLevel.ERROR);\n Logger.log(e.getMessage(), Logger.LogLevel.ERROR);\n }\n }\n\n private void upload(String filePath) {\n try {\n HttpClient httpClient = HttpClient.newHttpClient();\n HttpRequest request = HttpRequest.newBuilder()\n .uri(new URI(\"http://mc17.rhymc.com:52000/qo/upload/backup\")) // 替换为实际的API端点\n .header(\"Content-Type\", \"application/octet-stream\")\n .POST(HttpRequest.BodyPublishers.ofFile(Path.of(filePath)))\n .build();\n\n HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());\n if (response.statusCode() == 200) {\n Logger.log(\"Database upload complete.\", Logger.LogLevel.INFO);\n } else {\n Logger.log(\"Database upload ERROR with response code \" + response.statusCode(), Logger.LogLevel.ERROR);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}" }, { "identifier": "LogLevel", "path": "src/main/java/org/qo/Logger.java", "snippet": "public enum LogLevel {\n INFO, WARNING, ERROR, UNKNOWN\n}" } ]
import org.qo.server.BackupDatabase; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; import static org.qo.Logger.LogLevel.*;
688
package org.qo; @SpringBootApplication public class Main { public static void main(String[] args) throws Exception { Funcs.Start(); Logger.log("API Started.", INFO); SpringApplication.run(ApiApplication.class, args); Logger.startLogWriter("log.log", 3000); Timer timer = new Timer();
package org.qo; @SpringBootApplication public class Main { public static void main(String[] args) throws Exception { Funcs.Start(); Logger.log("API Started.", INFO); SpringApplication.run(ApiApplication.class, args); Logger.startLogWriter("log.log", 3000); Timer timer = new Timer();
TimerTask task = new BackupDatabase();
0
2023-11-15 13:38:53+00:00
2k
RaniAgus/java-docker-tutorial
src/main/java/io/github/raniagus/example/Application.java
[ { "identifier": "Bootstrap", "path": "src/main/java/io/github/raniagus/example/bootstrap/Bootstrap.java", "snippet": "public class Bootstrap implements Runnable, WithSimplePersistenceUnit {\n private static final Logger log = LoggerFactory.getLogger(Bootstrap.class);\n\n public static void main(String[] args) {\n Application.startDatabaseConnection();\n new Bootstrap().run();\n }\n\n @Override\n public void run() {\n log.info(\"Iniciando reinicio de base de datos...\");\n try (var reader = new CsvReader<>(UserDto.class, \"/data/users.csv\")){\n var users = reader.readAll().stream().map(UserDto::toEntity).toList();\n\n withTransaction(() -> {\n RepositorioDeUsuarios.INSTANCE.eliminarTodos();\n users.forEach(RepositorioDeUsuarios.INSTANCE::guardar);\n });\n\n users.forEach(user -> log.info(\"Usuario insertado: {}\", user));\n }\n }\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": "ErrorController", "path": "src/main/java/io/github/raniagus/example/controller/ErrorController.java", "snippet": "public enum ErrorController {\n INSTANCE;\n\n public void handleShouldLogin(Context ctx) {\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, ctx.path())\n ));\n }\n\n public void handleNotFound(Context ctx) {\n new ErrorView(\"404\", \"No pudimos encontrar la página que estabas buscando.\").render(ctx);\n }\n\n public void handleError(Context ctx) {\n new ErrorView(\"¡Oops!\", \"Algo salió mal. Vuelve a intentarlo más tarde.\").render(ctx);\n }\n}" }, { "identifier": "HomeController", "path": "src/main/java/io/github/raniagus/example/controller/HomeController.java", "snippet": "public enum HomeController {\n INSTANCE;\n\n public void renderHome(Context ctx) {\n Usuario usuario = ctx.sessionAttribute(Session.USER);\n new HomeView(usuario.getNombre(), usuario.getApellido()).render(ctx);\n }\n}" }, { "identifier": "LoginController", "path": "src/main/java/io/github/raniagus/example/controller/LoginController.java", "snippet": "public enum LoginController {\n INSTANCE;\n\n public void handleSession(Context ctx) {\n if (ctx.routeRoles().isEmpty()) {\n return;\n }\n\n Usuario usuario = ctx.sessionAttribute(Session.USER);\n if (usuario == null) {\n throw new ShouldLoginException();\n } else if (!ctx.routeRoles().contains(usuario.getRol())) {\n throw new UserNotAuthorizedException();\n }\n }\n\n public void renderLogin(Context ctx) {\n var email = ctx.queryParamAsClass(Params.EMAIL, String.class).getOrDefault(\"\");\n var origin = ctx.queryParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME);\n var errors = ctx.queryParamAsClass(Params.ERRORS, String.class).getOrDefault(\"\");\n\n if (ctx.sessionAttribute(Session.USER) != null) {\n ctx.redirect(origin);\n return;\n }\n\n new LoginView(email, origin, errors.isEmpty() ? Set.of() : Set.of(errors.split(\",\"))).render(ctx);\n }\n\n public void performLogin(Context ctx) {\n var email = ctx.formParamAsClass(Params.EMAIL, String.class)\n .check(s -> s.matches(\".+@.+\\\\..+\"), \"INVALID_EMAIL\");\n var password = ctx.formParamAsClass(Params.PASSWORD, String.class)\n .check(s -> s.length() >= 8, \"INVALID_PASSWORD\");\n var origin = ctx.formParamAsClass(Params.ORIGIN, String.class).getOrDefault(Routes.HOME);\n\n try {\n RepositorioDeUsuarios.INSTANCE.buscarPorEmail(email.get())\n .filter(u -> u.getPassword().matches(password.get()))\n .ifPresentOrElse(usuario -> {\n ctx.sessionAttribute(Session.USER, usuario);\n ctx.redirect(origin);\n }, () ->\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, origin),\n HtmlUtil.encode(Params.EMAIL, email.get()),\n HtmlUtil.encode(Params.ERRORS, String.join(\",\", Params.EMAIL, Params.PASSWORD))\n ))\n );\n } catch (ValidationException e) {\n var errors = Validation.collectErrors(email, password);\n ctx.redirect(HtmlUtil.joinParams(Routes.LOGIN,\n HtmlUtil.encode(Params.ORIGIN, origin),\n HtmlUtil.encode(Params.EMAIL, email.errors().isEmpty() ? email.get() : \"\"),\n HtmlUtil.encode(Params.ERRORS, errors.keySet())\n ));\n }\n }\n\n public void performLogout(Context ctx) {\n ctx.consumeSessionAttribute(Session.USER);\n ctx.redirect(Routes.HOME);\n }\n}" }, { "identifier": "ShouldLoginException", "path": "src/main/java/io/github/raniagus/example/exception/ShouldLoginException.java", "snippet": "public class ShouldLoginException extends RuntimeException {\n}" }, { "identifier": "UserNotAuthorizedException", "path": "src/main/java/io/github/raniagus/example/exception/UserNotAuthorizedException.java", "snippet": "public class UserNotAuthorizedException extends RuntimeException {\n}" }, { "identifier": "Rol", "path": "src/main/java/io/github/raniagus/example/model/Rol.java", "snippet": "public enum Rol implements RouteRole {\n ADMIN,\n USER\n}" } ]
import gg.jte.ContentType; import gg.jte.TemplateEngine; import gg.jte.output.StringOutput; import gg.jte.resolve.DirectoryCodeResolver; import io.github.flbulgarelli.jpa.extras.simple.WithSimplePersistenceUnit; import io.github.raniagus.example.bootstrap.Bootstrap; import io.github.raniagus.example.constants.Routes; import io.github.raniagus.example.controller.ErrorController; import io.github.raniagus.example.controller.HomeController; import io.github.raniagus.example.controller.LoginController; import io.github.raniagus.example.exception.ShouldLoginException; import io.github.raniagus.example.exception.UserNotAuthorizedException; import io.github.raniagus.example.model.Rol; import io.javalin.Javalin; import io.javalin.http.staticfiles.Location; import java.nio.file.Path; import java.time.LocalDate;
1,444
package io.github.raniagus.example; public class Application { public static final Config config = Config.create(); public static void main(String[] args) { startDatabaseConnection(); if (config.databaseHbm2ddlAuto().equals("create-drop")) {
package io.github.raniagus.example; public class Application { public static final Config config = Config.create(); public static void main(String[] args) { startDatabaseConnection(); if (config.databaseHbm2ddlAuto().equals("create-drop")) {
new Bootstrap().run();
0
2023-11-12 15:14:24+00:00
2k
heldermartins4/RPG_Pokemon
src/main/java/interfaces/combat/Combat.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 java.awt.image.BufferedImage; import controllers.combat.Trainer; import interfaces.GamePanel;
1,038
package interfaces.combat; public class Combat { BufferedImage gui, playerPokemon, rivalPokemon, move1, move2, move3, move4; Trainer player, rival;
package interfaces.combat; public class Combat { BufferedImage gui, playerPokemon, rivalPokemon, move1, move2, move3, move4; Trainer player, rival;
GamePanel screen;
1
2023-11-12 16:44:00+00:00
2k
kigangka/iotdb-server
src/main/java/com/kit/iotdb/common/task/WeatherTask.java
[ { "identifier": "WeatherClient", "path": "src/main/java/com/kit/iotdb/common/client/WeatherClient.java", "snippet": "public interface WeatherClient {\n\n /**\n * 根据城市代码获取城市天气情况\n */\n @Get(\"http://t.weather.itboy.net/api/weather/city/{0}\")\n JSONObject getCityWeatherInfo(Integer cityKey);\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.DatePattern; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.StrUtil; import com.alibaba.fastjson.JSONObject; import com.kit.iotdb.common.client.WeatherClient; import com.kit.iotdb.entity.WeatherEntity; import com.kit.iotdb.service.WeatherService; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource;
657
package com.kit.iotdb.common.task; /** * 添加说明 * * @author kit * @version 1.0 * @date 2023/11/10 10:25 */ @Component @Slf4j public class WeatherTask { @Resource private WeatherClient weatherClient; @Resource
package com.kit.iotdb.common.task; /** * 添加说明 * * @author kit * @version 1.0 * @date 2023/11/10 10:25 */ @Component @Slf4j public class WeatherTask { @Resource private WeatherClient weatherClient; @Resource
private WeatherService weatherService;
2
2023-11-15 06:04:04+00:00
2k
penyoofficial/HerbMS
src/main/java/com/penyo/herbms/controller/ExperienceController.java
[ { "identifier": "Experience", "path": "src/main/java/com/penyo/herbms/pojo/Experience.java", "snippet": "public class Experience extends GenericBean {\n /**\n * 唯一识别码\n */\n private int id;\n /**\n * 中草药 ID(外键)\n */\n private int herbId;\n /**\n * 出处\n */\n private String derivation;\n /**\n * 内容\n */\n private String content;\n\n public Experience() {\n }\n\n public Experience(int id, int herbId, String derivation, String content) {\n this.id = id;\n this.herbId = herbId;\n this.derivation = derivation;\n this.content = content;\n }\n\n @Override\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getHerbId() {\n return herbId;\n }\n\n public void setHerbId(int herbId) {\n this.herbId = herbId;\n }\n\n public String getDerivation() {\n return derivation;\n }\n\n public void setDerivation(String derivation) {\n this.derivation = derivation;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\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": "ExperienceService", "path": "src/main/java/com/penyo/herbms/service/ExperienceService.java", "snippet": "@Service\npublic class ExperienceService extends GenericService<Experience> {\n @Override\n public int add(Experience o) {\n return experienceDAO.add(o);\n }\n\n @Override\n public int delete(int id) {\n return experienceDAO.delete(id);\n }\n\n @Override\n public int update(Experience o) {\n return experienceDAO.update(o);\n }\n\n @Override\n public Experience selectById(int id) {\n return experienceDAO.selectById(id);\n }\n\n @Override\n public List<Experience> selectByFields(List<String> fields) {\n return experienceDAO.selectByFields(fields);\n }\n\n /**\n * 根据中草药 ID 查找多个中草药使用心得内容。\n */\n public List<String> selectContentsByHerbId(int id) {\n List<String> contents = new ArrayList<>();\n\n for (Experience h : experienceDAO.selectByHerbId(id))\n contents.add(h.getContent());\n return contents;\n }\n}" }, { "identifier": "HerbService", "path": "src/main/java/com/penyo/herbms/service/HerbService.java", "snippet": "@Service\npublic class HerbService extends GenericService<Herb> {\n @Override\n public int add(Herb o) {\n return herbDAO.add(o);\n }\n\n @Override\n public int delete(int id) {\n return herbDAO.delete(id);\n }\n\n @Override\n public int update(Herb o) {\n return herbDAO.update(o);\n }\n\n @Override\n public Herb selectById(int id) {\n return herbDAO.selectById(id);\n }\n\n @Override\n public List<Herb> selectByFields(List<String> fields) {\n return herbDAO.selectByFields(fields);\n }\n\n /**\n * 根据中草药使用心得 ID 查询单个中草药名称。\n */\n public String selectNameByExperienceId(int id) {\n return herbDAO.selectByExperienceId(id).getName();\n }\n\n /**\n * 根据处方 ID 查找多个中草药名称和解释。\n */\n public List<String> selectNamesAndDescriptionsByPrescriptionId(int id) {\n List<String> names = new ArrayList<>();\n\n for (Herb o : herbDAO.selectByPrescriptionId(id))\n names.add(o.getName() + \"/\" + o.getDescription());\n return names;\n }\n}" } ]
import com.penyo.herbms.pojo.Experience; import com.penyo.herbms.pojo.ReturnDataPack; import com.penyo.herbms.service.ExperienceService; import com.penyo.herbms.service.HerbService; import java.util.ArrayList; import java.util.List; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
1,525
package com.penyo.herbms.controller; /** * 中草药使用心得的控制器代理 * * @author Penyo * @see Experience * @see GenericController */ @Controller public class ExperienceController extends GenericController<Experience> { @Override @RequestMapping("/use-experiences") @ResponseBody public String requestMain(HttpServletRequest request) { return requestMain(toMap(request), getService(ExperienceService.class)).toString(); } @Override @RequestMapping("/use-experiences-specific") @ResponseBody public String requestSub(HttpServletRequest request) { List<String> hs = new ArrayList<>(); ReturnDataPack<Experience> exps = requestMain(toMap(request), getService(ExperienceService.class)); for (Experience o : exps.getObjs()) { StringBuilder hTemp = new StringBuilder("\"");
package com.penyo.herbms.controller; /** * 中草药使用心得的控制器代理 * * @author Penyo * @see Experience * @see GenericController */ @Controller public class ExperienceController extends GenericController<Experience> { @Override @RequestMapping("/use-experiences") @ResponseBody public String requestMain(HttpServletRequest request) { return requestMain(toMap(request), getService(ExperienceService.class)).toString(); } @Override @RequestMapping("/use-experiences-specific") @ResponseBody public String requestSub(HttpServletRequest request) { List<String> hs = new ArrayList<>(); ReturnDataPack<Experience> exps = requestMain(toMap(request), getService(ExperienceService.class)); for (Experience o : exps.getObjs()) { StringBuilder hTemp = new StringBuilder("\"");
hTemp.append(getService(HerbService.class).selectNameByExperienceId(o.getId()));
3
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;
1,159
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; @OLog("导出字典数据") @ApiOperation("导出字典数据") @GetMapping(value = "/download") @PreAuthorize("@ps.check('dict:list')") public void download(HttpServletResponse response, DictQueryCriteria criteria) throws IOException { dictService.download(dictService.queryAll(criteria), response); } @OLog("查询字典") @ApiOperation("查询字典") @GetMapping(value = "/all") @PreAuthorize("@ps.check('dict:list')") public ResponseEntity<Object> queryAll() { return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()), HttpStatus.OK); } @OLog("查询字典") @ApiOperation("查询字典") @GetMapping @PreAuthorize("@ps.check('dict:list')") public ResponseEntity<Object> query(DictQueryCriteria resources, Pageable pageable) { return new ResponseEntity<>(dictService.queryAll(resources, pageable), HttpStatus.OK); } @OLog("新增字典") @ApiOperation("新增字典") @PostMapping @PreAuthorize("@ps.check('dict:add')")
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; @OLog("导出字典数据") @ApiOperation("导出字典数据") @GetMapping(value = "/download") @PreAuthorize("@ps.check('dict:list')") public void download(HttpServletResponse response, DictQueryCriteria criteria) throws IOException { dictService.download(dictService.queryAll(criteria), response); } @OLog("查询字典") @ApiOperation("查询字典") @GetMapping(value = "/all") @PreAuthorize("@ps.check('dict:list')") public ResponseEntity<Object> queryAll() { return new ResponseEntity<>(dictService.queryAll(new DictQueryCriteria()), HttpStatus.OK); } @OLog("查询字典") @ApiOperation("查询字典") @GetMapping @PreAuthorize("@ps.check('dict:list')") public ResponseEntity<Object> query(DictQueryCriteria resources, Pageable pageable) { return new ResponseEntity<>(dictService.queryAll(resources, pageable), HttpStatus.OK); } @OLog("新增字典") @ApiOperation("新增字典") @PostMapping @PreAuthorize("@ps.check('dict:add')")
public ResponseEntity<Object> create(@Validated @RequestBody Dict resources) {
1
2023-11-10 03:30:36+00:00
2k
LazyCoder0101/LazyCoder
ui-datasource-edit/src/main/java/com/lazycoder/uidatasourceedit/moduleedit/commandinput/moduleinit/variable/ModuleVariableFolderHiddenButton.java
[ { "identifier": "FoldButton", "path": "ui-utils/src/main/java/com/lazycoder/uiutils/folder/FoldButton.java", "snippet": "public class FoldButton extends MyToggleButton implements ItemSelectable {\n\n /**\n *\n */\n private static final long serialVersionUID = 332081120052094106L;\n\n // 事件处理器集合\n private ArrayList<ItemListener> listeners = new ArrayList<ItemListener>();\n\n // 是否展开\n private boolean expanded;\n\n /**\n * 是否展开\n *\n * @param expanded\n */\n public FoldButton(boolean expanded) {\n // TODO Auto-generated constructor stub\n this.expanded = expanded;\n // setSelected(expanded);\n }\n\n @Override\n public void doClick() {\n // TODO Auto-generated method stub\n super.doClick();\n if (isEnabled() == true) {\n ((FoldButtonUI) getUI()).setArmed(true);\n // 折叠或者展开\n setExpanded(!isExpanded());\n // 触发选择事件\n ItemEvent evt = new ItemEvent(this, isExpanded() ? 0 : 1, getText(),\n isExpanded() ? ItemEvent.SELECTED : ItemEvent.DESELECTED);\n fireItemStateChanged(evt);\n // 获得焦点\n requestFocus();\n }\n }\n\n // 添加选择事件处理器\n @Override\n public void addItemListener(ItemListener l) {\n if (!listeners.contains(l)) {\n listeners.add(l);\n }\n }\n\n // 删除选择事件处理器\n @Override\n public void removeItemListener(ItemListener l) {\n if (listeners.contains(l)) {\n listeners.remove(l);\n }\n }\n\n public void removeAllItemListener() {\n listeners.clear();\n }\n\n // 触发事件处理器\n @Override\n public void fireItemStateChanged(ItemEvent e) {\n for (ItemListener l : listeners) {\n l.itemStateChanged(e);\n }\n }\n\n public boolean isExpanded() {\n return expanded;\n }\n\n public void setExpanded(boolean expanded) {\n this.expanded = expanded;\n//\t\tsetSelected(expanded);\n repaint();\n }\n\n /**\n * 点击鼠标前需要进行的操作\n *\n * @param expanded\n */\n public void doSomethingWhenMousePressed(boolean expanded) {\n }\n\n}" }, { "identifier": "FoldButtonUI", "path": "ui-utils/src/main/java/com/lazycoder/uiutils/folder/FoldButtonUI.java", "snippet": "public class FoldButtonUI extends BEButtonUI implements MouseMotionListener, MouseListener, FocusListener {\n\n\tprotected FoldButton button;\n\n\t/**\n\t * 当前鼠标是否浮动在上面\n\t */\n\tprivate boolean hovered;\n\n\tpublic static ComponentUI createUI(JComponent c) {\n\t\treturn new FoldButtonUI();\n\t}\n\n\t@Override\n\tpublic void installUI(JComponent c) {\n\t\t// 设置缺省属性\n\t\tbutton = (FoldButton) c;\n\t\tbutton.setFocusPainted(false);\n\t\tbutton.setFocusable(true);\n\t\t// 添加事件处理器\n\t\tbutton.addMouseListener(this);\n\t\tbutton.addMouseMotionListener(this);\n\t\tbutton.addFocusListener(this);\n\t}\n\n\t/**\n\t * 卸载UI\n\t */\n\t@Override\n\tpublic void uninstallUI(JComponent c) {\n\t\t// 卸载事件处理器\n\t\tbutton.removeMouseListener(this);\n\t\tbutton.removeMouseMotionListener(this);\n\t\tbutton.removeFocusListener(this);\n\t}\n\n\tpublic void setArmed(boolean b) {\n\t\t// armed=b;\n\t\tbutton.repaint();\n\t}\n\n\tpublic void setHovered(boolean b) {\n\t\thovered = b;\n\t\tbutton.repaint();\n\t}\n\n\t@Override\n\tpublic void focusLost(FocusEvent arg0) {\n\t\t// TODO Auto-generated method stub\n\t\tsetArmed(false);\n\t}\n\n\t/**\n\t * 鼠标退出事件\n\t */\n\t@Override\n\tpublic void mouseExited(MouseEvent arg0) {\n\t\t// TODO Auto-generated method stub\n\t\t// 浮动消失\n\t\tsetHovered(false);\n\t}\n\n\t@Override\n\tpublic void mouseEntered(MouseEvent arg0) {\n\t\t// 浮动\n\t\tsetHovered(true);\n\t\t// 改鼠标外观\n\t\tbutton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));\n\t}\n\n\t/**\n\t * 处理按下鼠标事件\n\t */\n\t@Override\n\tpublic void mousePressed(MouseEvent arg0) {\n\t\tif (button.isEnabled() == true) {\n\t\t\t// 改换外观\n\t\t\tsetArmed(true);\n\t\t\t// 折叠或者展开\n\t\t\tbutton.setExpanded(!button.isExpanded());\n\t\t\tbutton.doSomethingWhenMousePressed(button.isExpanded());\n\t\t\t// 触发选择事件\n\t\t\tItemEvent evt = new ItemEvent(button, button.isExpanded() ? 0 : 1, button.getText(),\n\t\t\t\t\tbutton.isExpanded() ? ItemEvent.SELECTED : ItemEvent.DESELECTED);\n\t\t\tbutton.fireItemStateChanged(evt);\n\t\t\t// 获得焦点\n\t\t\tbutton.requestFocus();\n\t\t}\n\t}\n\n\t@Override\n\tpublic void focusGained(FocusEvent arg0) {\n\t}\n\n\t@Override\n\tpublic void mouseClicked(MouseEvent arg0) {\n\t}\n\n\t@Override\n\tpublic void mouseReleased(MouseEvent arg0) {\n\t}\n\n\t@Override\n\tpublic void mouseDragged(MouseEvent arg0) {\n\t}\n\n\t@Override\n\tpublic void mouseMoved(MouseEvent arg0) {\n\t}\n\n}" } ]
import com.lazycoder.uiutils.folder.FoldButton; import com.lazycoder.uiutils.folder.FoldButtonUI;
1,571
package com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleinit.variable; public class ModuleVariableFolderHiddenButton extends FoldButton { /** * */ private static final long serialVersionUID = -7822164353880179167L; /** * 是否隐藏面板 * * @param expanded */ public ModuleVariableFolderHiddenButton(boolean expanded) { super(expanded); // TODO Auto-generated constructor stub setText("模块变量");
package com.lazycoder.uidatasourceedit.moduleedit.commandinput.moduleinit.variable; public class ModuleVariableFolderHiddenButton extends FoldButton { /** * */ private static final long serialVersionUID = -7822164353880179167L; /** * 是否隐藏面板 * * @param expanded */ public ModuleVariableFolderHiddenButton(boolean expanded) { super(expanded); // TODO Auto-generated constructor stub setText("模块变量");
setUI(new FoldButtonUI());
1
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;
702
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")); try { int id = Integer.parseInt(request.getParameter("id"));
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")); try { int id = Integer.parseInt(request.getParameter("id"));
Order order = Singleton.orderDAO.get(id);
1
2023-11-16 07:15:44+00:00
2k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/device/DoorLockTest.java
[ { "identifier": "PROP_CURRENT_STATES", "path": "app/src/main/java/kr/or/kashi/hde/device/DoorLock.java", "snippet": "@PropertyDef(valueClass=State.class, formatHint=\"bits\")\npublic static final String PROP_CURRENT_STATES = PROP_PREFIX + \"current_states\";" }, { "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.DoorLock.PROP_CURRENT_STATES; import kr.or.kashi.hde.test.DeviceTestCase;
1,025
/* * 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 DoorLockTest extends DeviceTestCase { public void test_DoorOpen() throws Exception {
/* * 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 DoorLockTest extends DeviceTestCase { public void test_DoorOpen() throws Exception {
final long state = device().getProperty(PROP_CURRENT_STATES, Long.class);
0
2023-11-10 01:19:44+00:00
2k
zizai-Shen/young-im
young-im-spring-boot-starter/young-im-spring-boot-starter-adapter/young-im-spring-boot-starter-adapter-config/src/main/java/cn/young/im/springboot/starter/adapter/config/parse/ConfigParseFactory.java
[ { "identifier": "ConfigType", "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/ConfigType.java", "snippet": "@Getter\npublic enum ConfigType {\n\n /**\n * Json\n */\n JSON(\"json\"),\n\n /**\n * text\n */\n PROPERTIES(\"properties\"),\n\n /**\n * yaml\n */\n YAML(\"yaml\"),\n\n /**\n *\n */\n UNSET(\"unset\");\n\n private static final Map<String, ConfigType> LOCAL_MAP = new HashMap<>();\n\n static {\n for (ConfigType configType : values()) {\n LOCAL_MAP.put(configType.getType(), configType);\n }\n }\n\n private final String type;\n\n ConfigType(String type) {\n this.type = type;\n }\n\n /**\n * 获取默认类型\n */\n public static ConfigType getDefaultType() {\n return YAML;\n }\n\n /**\n * 判断类型是否合法\n */\n public static Boolean isValidType(String type) {\n if (StringUtils.isBlank(type)) {\n return false;\n }\n return null != LOCAL_MAP.get(type);\n }\n}" }, { "identifier": "JsonConfigParseHandler", "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/parse/handler/JsonConfigParseHandler.java", "snippet": "public class JsonConfigParseHandler implements IConfigParseHandler {\n /**\n * 解析\n */\n @Override\n public void parse(String content, Object bean) {\n Object obj = JSON.parseObject(content, bean.getClass());\n // 对原来的对象进行赋值\n BeanUtils.copyProperties(obj, bean);\n }\n}" }, { "identifier": "PropertiesConfigParseHandler", "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/parse/handler/PropertiesConfigParseHandler.java", "snippet": "public class PropertiesConfigParseHandler implements IConfigParseHandler {\n\n @Override\n @SneakyThrows\n public void parse(String content, Object bean) {\n Properties properties = new Properties();\n properties.load(new StringReader(content));\n Props props = new Props(properties);\n Object sourceBean = props.toBean(bean.getClass());\n BeanUtils.copyProperties(sourceBean, bean);\n }\n}" }, { "identifier": "YamlConfigParseHandler", "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/parse/handler/YamlConfigParseHandler.java", "snippet": "@Slf4j\npublic class YamlConfigParseHandler implements IConfigParseHandler {\n\n @Override\n public void parse(String content, Object bean) {\n try (YamlReader reader = new YamlReader(content)) {\n Object sourceBean = reader.read(bean.getClass());\n BeanUtils.copyProperties(sourceBean, bean);\n } catch (IOException e) {\n log.error(e.getMessage(), e);\n }\n }\n}" } ]
import cn.young.im.springboot.starter.adapter.config.ConfigType; import cn.young.im.springboot.starter.adapter.config.parse.handler.JsonConfigParseHandler; import cn.young.im.springboot.starter.adapter.config.parse.handler.PropertiesConfigParseHandler; import cn.young.im.springboot.starter.adapter.config.parse.handler.YamlConfigParseHandler; import java.util.LinkedHashMap; import java.util.Map; import static java.util.Collections.synchronizedMap;
1,007
package cn.young.im.springboot.starter.adapter.config.parse; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description 配置解析处理器工厂 * @date 2023/12/16 */ public class ConfigParseFactory { private static final Map<String, IConfigParseHandler> handlers = synchronizedMap(new LinkedHashMap<>()); static {
package cn.young.im.springboot.starter.adapter.config.parse; /** * 作者:沈自在 <a href="https://www.szz.tax">Blog</a> * * @description 配置解析处理器工厂 * @date 2023/12/16 */ public class ConfigParseFactory { private static final Map<String, IConfigParseHandler> handlers = synchronizedMap(new LinkedHashMap<>()); static {
handlers.put(ConfigType.JSON.getType(), new JsonConfigParseHandler());
0
2023-11-10 06:21:17+00:00
2k
Ouest-France/querydsl
src/test/java/fr/ouestfrance/querydsl/FilterFieldServiceTest.java
[ { "identifier": "DummyRequest", "path": "src/test/java/fr/ouestfrance/querydsl/dummy/DummyRequest.java", "snippet": "@Getter\n@Setter\npublic class DummyRequest {\n\n @FilterField\n private String uuid;\n\n @FilterField(key = \"productCode\")\n private String code;\n\n @FilterField(operation = FilterOperation.IN.class, key = \"edition\")\n private List<String> editions;\n\n @FilterField(operation = FilterOperation.GTE.class, key = \"startDate\")\n @FilterField(operation = FilterOperation.LTE.class, key = \"endDate\", orNull = true)\n private LocalDate validityDate;\n\n @FilterField\n private boolean valid;\n\n private String noFilterField;\n}" }, { "identifier": "DummyRequestOrGroupMultipleField", "path": "src/test/java/fr/ouestfrance/querydsl/dummy/DummyRequestOrGroupMultipleField.java", "snippet": "@Getter\n@Setter\npublic class DummyRequestOrGroupMultipleField {\n\n // size = $size OR defaultSize = $defaultSize\n\n @FilterField(key = \"size\", groupName = \"group1\")\n private String size;\n\n @FilterField(key = \"defaultSize\", groupName =\"group1\")\n private String defaultSize;\n\n}" }, { "identifier": "DummyRequestOrSingleField", "path": "src/test/java/fr/ouestfrance/querydsl/dummy/DummyRequestOrSingleField.java", "snippet": "@Getter\n@Setter\npublic class DummyRequestOrSingleField {\n\n // size = $size OR (minSize < size AND maxSize > size)\n\n @FilterField(key = \"size\", groupName = \"group1\")\n @FilterFields(groupName = \"group1\", value = {\n @FilterField(key = \"minSize\", operation = FilterOperation.GTE.class),\n @FilterField(key = \"maxSize\", operation = FilterOperation.LTE.class)\n })\n private String size;\n\n}" }, { "identifier": "DummyViolatedRulesRequest", "path": "src/test/java/fr/ouestfrance/querydsl/dummy/DummyViolatedRulesRequest.java", "snippet": "@Getter\n@Setter\npublic class DummyViolatedRulesRequest {\n\n @FilterField(operation = IN.class)\n private String code;\n\n @FilterField(operation = LTE.class, key = \"edition\")\n private List<String> editions;\n\n @FilterField(operation = LIKE.class)\n private int quantity;\n}" }, { "identifier": "Filter", "path": "src/main/java/fr/ouestfrance/querydsl/model/Filter.java", "snippet": "public interface Filter {\n}" }, { "identifier": "FilterFieldAnnotationProcessorService", "path": "src/main/java/fr/ouestfrance/querydsl/service/FilterFieldAnnotationProcessorService.java", "snippet": "public class FilterFieldAnnotationProcessorService {\n\n /**\n * Cache of models\n */\n private static final Map<Class<?>, List<Filter>> CACHE = new ConcurrentHashMap<>();\n /**\n * Annotation scanner\n */\n private final FilterFieldAnnotationScanner scanner = new FilterFieldAnnotationScanner();\n\n /**\n * Process a specific class and return a list of filterFieldModel\n *\n * @param clazz clazz to handle\n * @return List of filterFieldModel\n */\n public List<Filter> process(Class<?> clazz) {\n return CACHE.computeIfAbsent(clazz, x -> scanner.scan(clazz));\n }\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}" } ]
import fr.ouestfrance.querydsl.dummy.DummyRequest; import fr.ouestfrance.querydsl.dummy.DummyRequestOrGroupMultipleField; import fr.ouestfrance.querydsl.dummy.DummyRequestOrSingleField; import fr.ouestfrance.querydsl.dummy.DummyViolatedRulesRequest; import fr.ouestfrance.querydsl.model.SimpleFilter; import fr.ouestfrance.querydsl.model.Filter; import fr.ouestfrance.querydsl.service.FilterFieldAnnotationProcessorService; import fr.ouestfrance.querydsl.service.validators.FilterFieldConstraintException; import org.junit.jupiter.api.Test; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; import static org.junit.jupiter.api.Assertions.*;
1,286
package fr.ouestfrance.querydsl; class FilterFieldServiceTest { private final FilterFieldAnnotationProcessorService service = new FilterFieldAnnotationProcessorService(); @Test void shouldLoad() { List<Filter> model = service.process(DummyRequest.class); System.out.println(model.stream().map(Filter::toString).collect(Collectors.joining("\n"))); assertNotNull(model); assertEquals(6, model.size()); AtomicBoolean shouldFindOrNull = new AtomicBoolean(false); model.forEach(x -> { assertNotNull(x); assertTrue(x instanceof SimpleFilter); SimpleFilter filter = (SimpleFilter)x; assertNotNull(filter.field()); shouldFindOrNull.set(shouldFindOrNull.get() | filter.orNull()); }); assertTrue(shouldFindOrNull.get()); } @Test void shouldLoadComplexe() {
package fr.ouestfrance.querydsl; class FilterFieldServiceTest { private final FilterFieldAnnotationProcessorService service = new FilterFieldAnnotationProcessorService(); @Test void shouldLoad() { List<Filter> model = service.process(DummyRequest.class); System.out.println(model.stream().map(Filter::toString).collect(Collectors.joining("\n"))); assertNotNull(model); assertEquals(6, model.size()); AtomicBoolean shouldFindOrNull = new AtomicBoolean(false); model.forEach(x -> { assertNotNull(x); assertTrue(x instanceof SimpleFilter); SimpleFilter filter = (SimpleFilter)x; assertNotNull(filter.field()); shouldFindOrNull.set(shouldFindOrNull.get() | filter.orNull()); }); assertTrue(shouldFindOrNull.get()); } @Test void shouldLoadComplexe() {
List<Filter> model = service.process(DummyRequestOrSingleField.class);
2
2023-11-14 10:50:02+00:00
2k
backend-source/ecommerce-microservice-architecture
product-service/src/main/java/com/hoangtien2k3/productservice/service/impl/CategoryServiceImpl.java
[ { "identifier": "CategoryDto", "path": "product-service/src/main/java/com/hoangtien2k3/productservice/dto/CategoryDto.java", "snippet": "@NoArgsConstructor\n@AllArgsConstructor\n@Data\n@Builder\npublic class CategoryDto implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n private Integer categoryId;\n private String categoryTitle;\n private String imageUrl;\n\n @JsonInclude(JsonInclude.Include.NON_NULL) // nếu subCategoriesDtos khác null thì hiển thị đầu ra của Json, ngược lại nếu null thì sẽ ko được hiển thị ở đầu ra của Json.\n private Set<CategoryDto> subCategoriesDtos;\n\n @JsonProperty(\"parentCategory\") // tên hiển thị khi chuyển sang Json\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private CategoryDto parentCategoryDto;\n\n @JsonInclude(JsonInclude.Include.NON_NULL)\n private Set<ProductDto> productDtos;\n\n}" }, { "identifier": "CategoryNotFoundException", "path": "product-service/src/main/java/com/hoangtien2k3/productservice/exception/wrapper/CategoryNotFoundException.java", "snippet": "public class CategoryNotFoundException extends RuntimeException {\n @Serial\n private static final long serialVersionUID = 1L;\n\n public CategoryNotFoundException() {\n super();\n }\n\n public CategoryNotFoundException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public CategoryNotFoundException(String message) {\n super(message);\n }\n\n public CategoryNotFoundException(Throwable cause) {\n super(cause);\n }\n\n}" }, { "identifier": "CategoryMappingHelper", "path": "product-service/src/main/java/com/hoangtien2k3/productservice/helper/CategoryMappingHelper.java", "snippet": "public interface CategoryMappingHelper {\n // map Category -> CategoryDto\n static CategoryDto map(final Category category) {\n final var parentCategory = Optional.ofNullable(category.getParentCategory())\n .orElseGet(Category::new); // () -> new Category()\n return CategoryDto.builder()\n .categoryId(category.getCategoryId())\n .categoryTitle(category.getCategoryTitle())\n .imageUrl(category.getImageUrl())\n .parentCategoryDto(\n CategoryDto.builder()\n .categoryId(parentCategory.getCategoryId())\n .categoryTitle(parentCategory.getCategoryTitle())\n .imageUrl(parentCategory.getImageUrl())\n .build()\n )\n .build();\n }\n\n\n // map CategoryDto -> Category\n static Category map(CategoryDto categoryDto) {\n final var parentCategoryDto = Optional.ofNullable(categoryDto.getParentCategoryDto())\n .orElseGet(CategoryDto::new);\n return Category.builder()\n .categoryId(categoryDto.getCategoryId())\n .categoryTitle(categoryDto.getCategoryTitle())\n .imageUrl(categoryDto.getImageUrl())\n .parentCategory(Category.builder()\n .categoryId(parentCategoryDto.getCategoryId())\n .categoryTitle(parentCategoryDto.getCategoryTitle())\n .imageUrl(parentCategoryDto.getImageUrl())\n .build())\n .build();\n }\n\n}" }, { "identifier": "CategoryRepository", "path": "product-service/src/main/java/com/hoangtien2k3/productservice/repository/CategoryRepository.java", "snippet": "public interface CategoryRepository extends JpaRepository<Category, Integer> {\n\n}" }, { "identifier": "CategoryService", "path": "product-service/src/main/java/com/hoangtien2k3/productservice/service/CategoryService.java", "snippet": "public interface CategoryService {\n List<CategoryDto> findAll();\n CategoryDto findById(final Integer categoryId);\n CategoryDto save(final CategoryDto categoryDto);\n CategoryDto update(final CategoryDto categoryDto);\n CategoryDto update(final Integer categoryId, final CategoryDto categoryDto);\n void deleteById(final Integer categoryId);\n}" } ]
import com.hoangtien2k3.productservice.dto.CategoryDto; import com.hoangtien2k3.productservice.exception.wrapper.CategoryNotFoundException; import com.hoangtien2k3.productservice.helper.CategoryMappingHelper; import com.hoangtien2k3.productservice.repository.CategoryRepository; import com.hoangtien2k3.productservice.service.CategoryService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.List; import java.util.stream.Collectors;
1,016
package com.hoangtien2k3.productservice.service.impl; @Transactional @Slf4j @RequiredArgsConstructor @Service public class CategoryServiceImpl implements CategoryService { @Autowired
package com.hoangtien2k3.productservice.service.impl; @Transactional @Slf4j @RequiredArgsConstructor @Service public class CategoryServiceImpl implements CategoryService { @Autowired
private final CategoryRepository categoryRepository;
3
2023-11-13 04:24:52+00:00
2k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/events/def/SkyblockInteractEvent.java
[ { "identifier": "TriggerType", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/abilities/TriggerType.java", "snippet": "public enum TriggerType {\n NONE,\n RIGHT_CLICK,\n LEFT_CLICK;\n\n public static TriggerType getTriggerType(Action action) {\n return switch (action) {\n case RIGHT_CLICK_AIR, RIGHT_CLICK_BLOCK -> RIGHT_CLICK;\n case LEFT_CLICK_AIR, LEFT_CLICK_BLOCK -> LEFT_CLICK;\n default -> NONE;\n };\n }\n}" }, { "identifier": "SkyblockPlayer", "path": "src/main/java/com/sweattypalms/skyblock/core/player/SkyblockPlayer.java", "snippet": "@Getter\npublic class SkyblockPlayer {\n private static final HashMap<UUID, SkyblockPlayer> players = new HashMap<>();\n\n private final Random random = new Random();\n private final StatsManager statsManager;\n private final InventoryManager inventoryManager;\n private final BonusManager bonusManager;\n private final CooldownManager cooldownManager;\n private final ActionBarManager actionBarManager;\n private final ScoreboardManager scoreboardManager;\n private final SlayerManager slayerManager;\n private final SkillManager skillManager;\n private final CurrencyManager currencyManager;\n private final Player player;\n private BukkitTask tickRunnable;\n\n @Getter @Setter\n private Regions lastKnownRegion = null;\n\n /**\n * This is used to get last use time of abilities\n */\n private final Map<String, Long> cooldowns = new HashMap<>();\n\n public SkyblockPlayer(Player player) {\n this.player = player;\n\n this.statsManager = new StatsManager(this);\n this.inventoryManager = new InventoryManager(this);\n this.bonusManager = new BonusManager(this);\n this.cooldownManager = new CooldownManager(this);\n this.actionBarManager = new ActionBarManager(this);\n this.slayerManager = new SlayerManager(this);\n this.skillManager = new SkillManager(this);\n this.currencyManager = new CurrencyManager(this);\n // Should be last because it uses the other managers\n this.scoreboardManager = new ScoreboardManager(this);\n\n players.put(player.getUniqueId(), this);\n init();\n }\n\n public static SkyblockPlayer getSkyblockPlayer(Player player) {\n return players.get(player.getUniqueId());\n }\n\n public static void newPlayer(Player player) {\n new SkyblockPlayer(player);\n }\n\n private void init() {\n\n String displayName = \"$c[OWNER] \" + this.player.getName();\n displayName = PlaceholderFormatter.format(displayName);\n this.player.setDisplayName(displayName);\n\n this.tickRunnable = new BukkitRunnable() {\n @Override\n public void run() {\n tick();\n }\n }.runTaskTimerAsynchronously(SkyBlock.getInstance(), 0, 1);\n\n this.statsManager.initHealth();\n }\n\n private int tickCount = 0;\n private void tick() {\n if (!this.player.isOnline()) {\n SkyblockPlayer.players.remove(this.player.getUniqueId());\n this.tickRunnable.cancel();\n }\n if (this.player.isDead()){\n return;\n }\n this.tickCount++;\n\n if (this.tickCount % 20 != 0) return;\n\n this.bonusManager.cleanupExpiredBonuses();\n this.statsManager.tick();\n this.actionBarManager.tick();\n\n this.scoreboardManager.updateScoreboard();\n RegionManager.updatePlayerRegion(this);\n }\n\n /**\n * Damage the player\n * TODO: Add various damage types\n * @param damage Damage to deal (With reduction)\n */\n public void damage(double damage) {\n if (this.player.getGameMode() != GameMode.SURVIVAL)\n return;\n this.player.setHealth(\n Math.max(\n this.player.getHealth() - damage,\n 0\n )\n );\n }\n\n public void damageWithReduction(double damage){\n double defense = this.statsManager.getMaxStats().get(Stats.DEFENSE);\n double finalDamage = DamageCalculator.calculateDamageReduction(defense, damage);\n this.damage(finalDamage);\n }\n\n /**\n * Send auto formatted message to player\n * @param s Message to send\n */\n public void sendMessage(String s) {\n this.player.sendMessage(PlaceholderFormatter.format(s));\n }\n\n public long getLastUseTime(String key){\n return this.cooldowns.getOrDefault(key, 0L);\n }\n\n public void setLastUseTime(String key, long time){\n this.cooldowns.put(key, time);\n }\n}" } ]
import com.sweattypalms.skyblock.core.items.builder.abilities.TriggerType; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import org.bukkit.block.Block; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList;
1,221
package com.sweattypalms.skyblock.core.events.def; public class SkyblockInteractEvent extends SkyblockPlayerEvent implements Cancellable { private static final HandlerList HANDLERS = new HandlerList(); private boolean isCancelled; private final SkyblockPlayer skyblockPlayer;
package com.sweattypalms.skyblock.core.events.def; public class SkyblockInteractEvent extends SkyblockPlayerEvent implements Cancellable { private static final HandlerList HANDLERS = new HandlerList(); private boolean isCancelled; private final SkyblockPlayer skyblockPlayer;
private final TriggerType interactType;
0
2023-11-15 15:05:58+00:00
2k
microsphere-projects/microsphere-i18n
microsphere-i18n-core/src/test/java/io/microsphere/i18n/spring/context/I18nConfigurationTest.java
[ { "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}" }, { "identifier": "TestServiceMessageSourceConfiguration", "path": "microsphere-i18n-core/src/test/java/io/microsphere/i18n/spring/beans/TestServiceMessageSourceConfiguration.java", "snippet": "public class TestServiceMessageSourceConfiguration {\n\n @Bean\n public static ServiceMessageSourceFactoryBean testServiceMessageSource() {\n return new ServiceMessageSourceFactoryBean(\"test\");\n }\n}" }, { "identifier": "serviceMessageSource", "path": "microsphere-i18n-core/src/main/java/io/microsphere/i18n/util/I18nUtils.java", "snippet": "public static ServiceMessageSource serviceMessageSource() {\n if (serviceMessageSource == null) {\n logger.warn(\"serviceMessageSource is not initialized, EmptyServiceMessageSource will be used\");\n return EmptyServiceMessageSource.INSTANCE;\n }\n return serviceMessageSource;\n}" } ]
import io.microsphere.i18n.ServiceMessageSource; import io.microsphere.i18n.spring.beans.TestServiceMessageSourceConfiguration; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.Locale; import static io.microsphere.i18n.util.I18nUtils.serviceMessageSource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame;
910
package io.microsphere.i18n.spring.context; /** * {@link I18nConfiguration} Test * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @since 1.0.0 */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = {I18nConfiguration.class, TestServiceMessageSourceConfiguration.class}) public class I18nConfigurationTest { @Before public void before() { LocaleContextHolder.resetLocaleContext(); } @Autowired
package io.microsphere.i18n.spring.context; /** * {@link I18nConfiguration} Test * * @author <a href="mailto:mercyblitz@gmail.com">Mercy<a/> * @since 1.0.0 */ @RunWith(SpringRunner.class) @ContextConfiguration(classes = {I18nConfiguration.class, TestServiceMessageSourceConfiguration.class}) public class I18nConfigurationTest { @Before public void before() { LocaleContextHolder.resetLocaleContext(); } @Autowired
private ServiceMessageSource serviceMessageSource;
2
2023-11-17 11:35:59+00:00
2k
issavior/savior
savior-event/src/main/java/cn/sunjinxin/savior/event/listener/sub/SyncListener.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": "EventContainer", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/container/EventContainer.java", "snippet": "@RequiredArgsConstructor\n@FieldDefaults(level = AccessLevel.PRIVATE, makeFinal = true)\npublic class EventContainer {\n\n List<EventHandler> eventHandlers;\n\n EventProperties eventProperties;\n\n public EventHandler of(Eventer event) {\n return Optional.ofNullable(eventHandlers).orElse(Lists.newArrayList())\n .stream()\n .filter(r -> r.strategy().contains(eventProperties.getStrategy()))\n .filter(r -> r.event() == event)\n .findFirst()\n .orElseThrow(() -> new RuntimeException(\"can`t match event handler\"));\n }\n}" }, { "identifier": "EventContext", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/context/EventContext.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\n@FieldDefaults(level = AccessLevel.PRIVATE)\npublic class EventContext<EventType, RequestParam> implements Serializable {\n\n EventType eventType;\n\n RequestParam request;\n\n String eventId;\n\n}" }, { "identifier": "InnerEventContext", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/context/InnerEventContext.java", "snippet": "@Builder\n@FieldDefaults(level = AccessLevel.PRIVATE)\n@Accessors(chain = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class InnerEventContext<EventType, RequestParam> {\n EventContext<EventType, RequestParam> eventContext;\n Eventer eventer;\n}" }, { "identifier": "Eventer", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/control/Eventer.java", "snippet": "public enum Eventer {\n\n /**\n * SYNC\n */\n SYNC,\n\n /**\n * ASYNC\n */\n ASYNC;\n\n public <T, R> void publish(EventContext<T, R> context) {\n InnerEventContext<T, R> innerEventContext = InnerEventContext.<T,R>builder().eventContext(context).build();\n SpringHelper.getBean(EventContainer.class).of(this).post(innerEventContext);\n }\n}" }, { "identifier": "Listener", "path": "savior-event/src/main/java/cn/sunjinxin/savior/event/listener/Listener.java", "snippet": "@External\npublic interface Listener<EventType, EventContext> extends InitializingBean, EventHandler<InnerEventContext> {\n\n List<EventType> supportEventType();\n\n boolean enable(EventType type);\n\n void handle(EventContext context);\n\n}" } ]
import cn.sunjinxin.savior.core.helper.SpringHelper; import cn.sunjinxin.savior.event.container.EventContainer; import cn.sunjinxin.savior.event.context.EventContext; import cn.sunjinxin.savior.event.context.InnerEventContext; import cn.sunjinxin.savior.event.control.Eventer; import cn.sunjinxin.savior.event.listener.Listener; import com.google.common.eventbus.Subscribe; import org.springframework.context.event.EventListener; import java.util.Optional;
1,085
package cn.sunjinxin.savior.event.listener.sub; /** * Sync Api * * @author issavior */ @SuppressWarnings("all") public interface SyncListener<EventType, RequestParam> extends Listener<EventType, EventContext<EventType, RequestParam>> { /** * t * * @param t / * @return / */ @Override default boolean enable(EventType t) { return supportEventType().contains(t); } @Override
package cn.sunjinxin.savior.event.listener.sub; /** * Sync Api * * @author issavior */ @SuppressWarnings("all") public interface SyncListener<EventType, RequestParam> extends Listener<EventType, EventContext<EventType, RequestParam>> { /** * t * * @param t / * @return / */ @Override default boolean enable(EventType t) { return supportEventType().contains(t); } @Override
default void onEvent(InnerEventContext event, long l, boolean b) {
3
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;
717
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);
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);
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, AECommonConfig.getConfig());
1
2023-11-12 12:23:21+00:00
2k
pyzpre/Create-Bicycles-Bitterballen
src/main/java/createbicyclesbitterballen/CreateBicBitMod.java
[ { "identifier": "BlockEntityRegistry", "path": "src/main/java/createbicyclesbitterballen/index/BlockEntityRegistry.java", "snippet": "public class BlockEntityRegistry {\n\n public static final BlockEntityEntry<MechanicalFryerEntity> MECHANICAL_FRYER = REGISTRATE\n .blockEntity(\"mechanical_fryer\", MechanicalFryerEntity::new)\n .instance(() -> FryerInstance::new)\n .validBlocks(BlockRegistry.MECHANICAL_FRYER)\n .renderer(() -> MechanicalFryerRenderer::new)\n .register();\n\n // You can add more BlockEntityEntries following the above format.\n\n public static void register() {\n }\n}" }, { "identifier": "ConfigRegistry", "path": "src/main/java/createbicyclesbitterballen/config/ConfigRegistry.java", "snippet": "public class ConfigRegistry {\n public static final ForgeConfigSpec.Builder SERVER_BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SERVER_SPEC;\n\n\n static {\n SERVER_BUILDER.push(\"Server Configs\");\n\n SERVER_BUILDER.pop();\n SERVER_SPEC = SERVER_BUILDER.build();\n }\n}" }, { "identifier": "CreateBicBitModFluids", "path": "src/main/java/createbicyclesbitterballen/index/CreateBicBitModFluids.java", "snippet": "public class CreateBicBitModFluids {\n public static final DeferredRegister<Fluid> REGISTRY = DeferredRegister.create(ForgeRegistries.FLUIDS, CreateBicBitMod.MODID);\n public static final RegistryObject<FlowingFluid> FRYING_OIL = REGISTRY.register(\"frying_oil\", () -> new FryingOilFluid.Source());\n public static final RegistryObject<FlowingFluid> FLOWING_FRYING_OIL = REGISTRY.register(\"flowing_frying_oil\", () -> new FryingOilFluid.Flowing());\n public static final RegistryObject<FlowingFluid> STAMPPOT = REGISTRY.register(\"stamppot\", () -> new StamppotFluid.Source());\n public static final RegistryObject<FlowingFluid> FLOWING_STAMPPOT = REGISTRY.register(\"flowing_stamppot\", () -> new StamppotFluid.Flowing());\n\n @Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientSideHandler {\n @SubscribeEvent\n public static void clientSetup(FMLClientSetupEvent event) {\n ItemBlockRenderTypes.setRenderLayer(FRYING_OIL.get(), RenderType.translucent());\n ItemBlockRenderTypes.setRenderLayer(FLOWING_FRYING_OIL.get(), RenderType.translucent());\n ItemBlockRenderTypes.setRenderLayer(STAMPPOT.get(), RenderType.translucent());\n ItemBlockRenderTypes.setRenderLayer(FLOWING_STAMPPOT.get(), RenderType.translucent());\n }\n }\n}" }, { "identifier": "FluidTypesRegistry", "path": "src/main/java/createbicyclesbitterballen/index/FluidTypesRegistry.java", "snippet": "public class FluidTypesRegistry {\n public static final DeferredRegister<FluidType> REGISTRY = DeferredRegister.create(ForgeRegistries.Keys.FLUID_TYPES, CreateBicBitMod.MODID);\n public static final RegistryObject<FluidType> STAMPPOT_TYPE = REGISTRY.register(\"stamppot\", () -> new StamppotFluidType());\n public static final RegistryObject<FluidType> FRYING_OIL_TYPE = REGISTRY.register(\"frying_oil\", () -> new FryingOilFluidType());\n}" }, { "identifier": "BlockRegistry", "path": "src/main/java/createbicyclesbitterballen/index/BlockRegistry.java", "snippet": "public class BlockRegistry {\n\tpublic static final BlockEntry<MechanicalFryer> MECHANICAL_FRYER =\n\t\t\tREGISTRATE.block(\"mechanical_fryer\", MechanicalFryer::new)\n\t\t\t.initialProperties(SharedProperties::copperMetal)\n\t\t\t.properties(p -> p.noOcclusion().strength(2.0f))\n\t\t\t.transform(pickaxeOnly())\n\t\t\t.blockstate(BlockStateGen.horizontalBlockProvider(true))\n\t\t\t.transform(BlockStressDefaults.setImpact(4.0))\n\t\t\t.item(AssemblyOperatorBlockItem::new)\n\t\t\t.transform(customItemModel())\n\t\t\t.register();\n\n\n\n\t\tpublic static void register() {\n\n\t}\n}" } ]
import java.util.Random; import com.simibubi.create.foundation.item.ItemDescription; import com.simibubi.create.foundation.item.KineticStats; import com.simibubi.create.foundation.item.TooltipModifier; import createbicyclesbitterballen.index.BlockEntityRegistry; import createbicyclesbitterballen.config.ConfigRegistry; import createbicyclesbitterballen.index.CreateBicBitModFluids; import createbicyclesbitterballen.index.FluidTypesRegistry; import createbicyclesbitterballen.index.*; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.fml.DistExecutor; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.config.ModConfig; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import com.simibubi.create.foundation.item.TooltipHelper.Palette; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.common.MinecraftForge; import createbicyclesbitterballen.index.BlockRegistry; import com.simibubi.create.foundation.data.CreateRegistrate;
1,479
package createbicyclesbitterballen; @Mod("create_bic_bit") public class CreateBicBitMod { public static final Logger LOGGER = LogManager.getLogger(CreateBicBitMod.class); public static final String MODID = "create_bic_bit"; public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(MODID); @Deprecated public static final Random RANDOM = new Random(); static { REGISTRATE.setTooltipModifierFactory(item -> { return new ItemDescription.Modifier(item, Palette.STANDARD_CREATE) .andThen(TooltipModifier.mapNull(KineticStats.create(item))); }); } public CreateBicBitMod() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus forgeEventBus = MinecraftForge.EVENT_BUS; MinecraftForge.EVENT_BUS.register(this); // Register components using Registrate SoundsRegistry.prepare(); BlockRegistry.register(); CreateBicBitModItems.register(); CreateBicBitModTabs.register(modEventBus); RecipeRegistry.register(modEventBus); BlockEntityRegistry.register(); PonderIndex.register();
package createbicyclesbitterballen; @Mod("create_bic_bit") public class CreateBicBitMod { public static final Logger LOGGER = LogManager.getLogger(CreateBicBitMod.class); public static final String MODID = "create_bic_bit"; public static final CreateRegistrate REGISTRATE = CreateRegistrate.create(MODID); @Deprecated public static final Random RANDOM = new Random(); static { REGISTRATE.setTooltipModifierFactory(item -> { return new ItemDescription.Modifier(item, Palette.STANDARD_CREATE) .andThen(TooltipModifier.mapNull(KineticStats.create(item))); }); } public CreateBicBitMod() { IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus bus = FMLJavaModLoadingContext.get().getModEventBus(); IEventBus forgeEventBus = MinecraftForge.EVENT_BUS; MinecraftForge.EVENT_BUS.register(this); // Register components using Registrate SoundsRegistry.prepare(); BlockRegistry.register(); CreateBicBitModItems.register(); CreateBicBitModTabs.register(modEventBus); RecipeRegistry.register(modEventBus); BlockEntityRegistry.register(); PonderIndex.register();
CreateBicBitModFluids.REGISTRY.register(bus);
2
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,560
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) {
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) {
2
2023-11-10 21:39:16+00:00
2k
vadremix/journee
services/user-management-service/src/main/java/com/worldjournee/usermanagementservice/controller/UserController.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": "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 com.worldjournee.usermanagementservice.model.User; import com.worldjournee.usermanagementservice.service.UserService; import jakarta.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; 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;
732
package com.worldjournee.usermanagementservice.controller; @RestController @RequestMapping("/api/v1/create-user") public class UserController {
package com.worldjournee.usermanagementservice.controller; @RestController @RequestMapping("/api/v1/create-user") public class UserController {
private final UserService userService;
1
2023-11-13 21:40:58+00:00
2k
daobab-projects/orm-performance-comparator
src/main/java/io/daobab/performance/jpa/JpaController.java
[ { "identifier": "Actor", "path": "src/main/java/io/daobab/performance/hibernate/entity/Actor.java", "snippet": "@Entity\n@Table(name = \"actor\")\n@Getter\n@Setter\n@EqualsAndHashCode\npublic class Actor implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"actor_id\")\n private int id;\n\n @Column(name = \"first_name\")\n private String firstName;\n\n @Column(name = \"last_name\")\n private String lastName;\n\n @Column(name = \"last_update\")\n @UpdateTimestamp\n private LocalDateTime lastUpdate;\n\n\n//\t@ManyToMany(fetch=FetchType.LAZY, mappedBy=\"actors\",\n//\t\t cascade= {CascadeType.PERSIST, CascadeType.MERGE,\n//\t\t CascadeType.DETACH, CascadeType.REFRESH})\n//\t\t\t@JsonIgnore\n//\tList<Film> films = new ArrayList<>();\n\n\n//\tpublic void addFilm(Film film) {\t\t\t//INUTILE ??\n//\t\tfilms.add(film);\n//\t}\n\n\n}" }, { "identifier": "CustomerAddress", "path": "src/main/java/io/daobab/performance/jpa/model/CustomerAddress.java", "snippet": "public interface CustomerAddress {\n String getFirstName();\n\n String getLastName();\n\n String getAddress();\n\n String getCity();\n}" }, { "identifier": "ActorJpaService", "path": "src/main/java/io/daobab/performance/jpa/repository/ActorJpaService.java", "snippet": "@Repository\npublic interface ActorJpaService extends JpaRepository<Actor, Integer> {\n\n @Query(\"select a from Actor a where a.id=:id\")\n Actor findActorById(@Param(\"id\") int id);\n\n}" }, { "identifier": "CustomerJpaService", "path": "src/main/java/io/daobab/performance/jpa/repository/CustomerJpaService.java", "snippet": "@Repository\npublic interface CustomerJpaService extends JpaRepository<Payment, Integer> {\n\n @Query(\"select c.firstName as firstName, c.lastName as lastName, c.address.address as address, c.address.city.city as city from Customer c \")\n List<CustomerAddress> getCustomerAddresses();\n\n}" }, { "identifier": "PaymentJpaService", "path": "src/main/java/io/daobab/performance/jpa/repository/PaymentJpaService.java", "snippet": "@Repository\npublic interface PaymentJpaService extends JpaRepository<Payment, Integer> {\n\n @Query(\"select sum(p.amount) from Payment p where p.customer.customerId=:id\")\n Double getCustomerPaymentSum(@Param(\"id\") int id);\n\n}" } ]
import io.daobab.performance.hibernate.entity.Actor; import io.daobab.performance.jpa.model.CustomerAddress; import io.daobab.performance.jpa.repository.ActorJpaService; import io.daobab.performance.jpa.repository.CustomerJpaService; import io.daobab.performance.jpa.repository.PaymentJpaService; import lombok.RequiredArgsConstructor; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List;
729
package io.daobab.performance.jpa; @RestController @RequestMapping(path = "/jpa", produces = MediaType.APPLICATION_JSON_VALUE) @RequiredArgsConstructor public class JpaController {
package io.daobab.performance.jpa; @RestController @RequestMapping(path = "/jpa", produces = MediaType.APPLICATION_JSON_VALUE) @RequiredArgsConstructor public class JpaController {
private final ActorJpaService actorService;
2
2023-11-12 21:43:51+00:00
2k
lastnightinparis/tinkoff-investement-bot
bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/service/users/UserServiceImpl.java
[ { "identifier": "ResourceNotFoundException", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/exception/system/ResourceNotFoundException.java", "snippet": "public class ResourceNotFoundException extends TradingBotException {\n\n private ResourceType type;\n private QueryType queryType;\n private Collection<String> values;\n public ResourceNotFoundException(String message) {\n super(message);\n }\n\n public ResourceNotFoundException(ResourceType type, QueryType queryType, Object value) {\n this(type, queryType, List.of(value.toString()));\n }\n\n public ResourceNotFoundException(ResourceType type, QueryType queryType, String value) {\n this(type, queryType, List.of(value));\n }\n\n public ResourceNotFoundException(ResourceType type, QueryType queryType, Collection<String> values) {\n this.type = type;\n this.queryType = queryType;\n this.values = List.copyOf(values);\n }\n\n @Override\n public String getMessage() {\n return String.format(\"Failed to get [%s] with %s [%s]\", type, queryType.getQueryName(), values);\n }\n}" }, { "identifier": "User", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/domain/User.java", "snippet": "@Data\n@Entity\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Table(name = \"users\")\npublic class User {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"chat_id\")\n private Long chatId;\n\n @Column(name = \"username\")\n private String username;\n\n @Column(name = \"tg_username\")\n private String tgUsername;\n\n @Column(name = \"is_active\")\n private boolean active;\n\n @Column(name = \"is_blocked\")\n private boolean blocked;\n\n @Column(name = \"is_connected_account\")\n private boolean connectedInvestAccount;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"bot_state\")\n private BotState botState;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"prev_bot_state\")\n private BotState previousBotState;\n\n @Column(name = \"registered_at\")\n private Instant registeredAt;\n\n @Column(name = \"last_activity_at\")\n private Instant lastActivityAt;\n}" }, { "identifier": "BotState", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/bot/BotState.java", "snippet": "public enum BotState {\n BOT_VERSION_COMMAND, HELP_COMMAND,\n\n START, FIRST_START,\n\n TRADING_MENU, NOTIFICATION_MENU, ACCOUNT_SETTINGS, HELP, BACK,\n\n START_TRADING, CHOOSE_STRATEGY_ACTION, ENTER_TRADING_TICKER, CHOOSE_STRATEGY_PARAM,\n ENTER_ADDITIONAL_PARAM,\n\n TRADINGS_LIST, STRATEGIES_LIST,\n\n CREATE_NOTIFICATION_EVENT, NOTIFICATION_EVENT_LIST,\n\n INVEST_ACCOUNT_ACTION, ENTER_TOKEN\n}" }, { "identifier": "QueryType", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/exceptions/QueryType.java", "snippet": "@Getter\npublic enum QueryType {\n ID(\"ids\"),\n CHAT_ID(\"chat_ids\"),\n ;\n\n private final String queryName;\n QueryType(String queryName) {\n this.queryName = queryName;\n }\n}" }, { "identifier": "ResourceType", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/model/enums/exceptions/ResourceType.java", "snippet": "public enum ResourceType {\n USER,\n ;\n}" }, { "identifier": "UserRepository", "path": "bot-service-boot/src/main/java/com/itmo/tinkoffinvestementbot/repository/UserRepository.java", "snippet": "@Repository\npublic interface UserRepository extends JpaRepository<User, Long> {\n\n Optional<User> findByChatId(long chatId);\n\n Optional<User> findByTgUsername(String tgUsername);\n\n boolean existsByChatId(long chatId);\n\n @Query(value = \"SELECT u.chat_id FROM users u WHERE u.user_role = 'ADMIN_ROLE'\", nativeQuery = true)\n List<Long> findAdminChatIds();\n}" } ]
import com.itmo.tinkoffinvestementbot.exception.system.ResourceNotFoundException; import com.itmo.tinkoffinvestementbot.model.domain.User; import com.itmo.tinkoffinvestementbot.model.enums.bot.BotState; import com.itmo.tinkoffinvestementbot.model.enums.exceptions.QueryType; import com.itmo.tinkoffinvestementbot.model.enums.exceptions.ResourceType; import com.itmo.tinkoffinvestementbot.repository.UserRepository; import lombok.RequiredArgsConstructor; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import java.time.Instant; import java.util.List; import java.util.Optional;
1,430
package com.itmo.tinkoffinvestementbot.service.users; @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService { private final UserRepository userRepository; @Override public List<User> findAll() { return userRepository.findAll(); } @Override public Optional<User> findUserByChatId(long chatId) { return userRepository.findByChatId(chatId); } @Override public Optional<User> findUserByTgUsername(String tgUsername) { return userRepository.findByTgUsername(tgUsername); } @Override public List<Long> getAdminChatIds() { return userRepository.findAdminChatIds(); } @Override public User getUserById(Long id) { return userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.ID, id)); } @Override public User getUserByChatId(Long chatId) { return findUserByChatId(chatId) .orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.CHAT_ID, chatId)); } @Override public User save(User user) { User userFromDb; if (user.getId() != null) { userFromDb = getUserByChatId(user.getChatId()); BeanUtils.copyProperties(user, userFromDb, "id"); } else { userFromDb = User.builder() .chatId(user.getChatId()) .username(user.getUsername()) .tgUsername(user.getTgUsername()) .active(false) .blocked(false) .connectedInvestAccount(false)
package com.itmo.tinkoffinvestementbot.service.users; @Service @RequiredArgsConstructor public class UserServiceImpl implements UserService { private final UserRepository userRepository; @Override public List<User> findAll() { return userRepository.findAll(); } @Override public Optional<User> findUserByChatId(long chatId) { return userRepository.findByChatId(chatId); } @Override public Optional<User> findUserByTgUsername(String tgUsername) { return userRepository.findByTgUsername(tgUsername); } @Override public List<Long> getAdminChatIds() { return userRepository.findAdminChatIds(); } @Override public User getUserById(Long id) { return userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.ID, id)); } @Override public User getUserByChatId(Long chatId) { return findUserByChatId(chatId) .orElseThrow(() -> new ResourceNotFoundException(ResourceType.USER, QueryType.CHAT_ID, chatId)); } @Override public User save(User user) { User userFromDb; if (user.getId() != null) { userFromDb = getUserByChatId(user.getChatId()); BeanUtils.copyProperties(user, userFromDb, "id"); } else { userFromDb = User.builder() .chatId(user.getChatId()) .username(user.getUsername()) .tgUsername(user.getTgUsername()) .active(false) .blocked(false) .connectedInvestAccount(false)
.botState(BotState.FIRST_START)
2
2023-11-13 09:28:00+00:00
2k
toxicity188/InventoryAPI
plugin/src/main/java/kor/toxicity/inventory/generator/FontObjectImpl.java
[ { "identifier": "GuiObject", "path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiObject.java", "snippet": "public interface GuiObject {\n GuiObject EMPTY = new GuiObject() {\n @Override\n public @NotNull GuiObjectGenerator getGenerator() {\n throw new UnsupportedOperationException(\"This is a empty object.\");\n }\n\n @Override\n public @NotNull Component asComponent() {\n return Component.empty();\n }\n\n @Override\n public @NotNull GuiObject append(@NotNull GuiObject object) {\n return object;\n }\n };\n @NotNull GuiObjectGenerator getGenerator();\n @NotNull Component asComponent();\n @NotNull GuiObject append(@NotNull GuiObject object);\n}" }, { "identifier": "GuiObjectGenerator", "path": "api/src/main/java/kor/toxicity/inventory/api/gui/GuiObjectGenerator.java", "snippet": "public interface GuiObjectGenerator {\n int getAscent();\n int getHeight();\n @NotNull GuiObjectBuilder builder();\n @NotNull Key getFontKey();\n}" }, { "identifier": "AdventureUtil", "path": "plugin/src/main/java/kor/toxicity/inventory/util/AdventureUtil.java", "snippet": "public class AdventureUtil {\n private static final Key SPACE_KEY = Key.key(\"inventory:space\");\n private AdventureUtil() {\n throw new SecurityException();\n }\n public static String parseChar(int i) {\n if (i <= 0xFFFF) return Character.toString((char) i);\n else {\n var t = i - 0x10000;\n return Character.toString((t >>> 10) + 0xD800) + Character.toString((t & ((1 << 10) - 1)) + 0xDC00);\n }\n }\n\n public static Component getSpaceFont(int i) {\n return Component.text(parseChar(i + 0xD0000)).font(SPACE_KEY);\n }\n}" } ]
import kor.toxicity.inventory.api.gui.GuiObject; import kor.toxicity.inventory.api.gui.GuiObjectGenerator; import kor.toxicity.inventory.util.AdventureUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.Style; import net.kyori.adventure.text.format.TextDecoration; import org.jetbrains.annotations.NotNull;
798
package kor.toxicity.inventory.generator; public class FontObjectImpl implements GuiObject { private static final Component SPACE_COMPONENT = Component.text(' '); private final FontObjectGeneratorImpl objectGenerator; private final Component component; public FontObjectImpl(FontObjectGeneratorImpl objectGenerator, String text, Style style, int space, int xOffset) { this.objectGenerator = objectGenerator; var comp = Component.empty().append(AdventureUtil.getSpaceFont(xOffset)); var spaceComp = AdventureUtil.getSpaceFont(space); var charArray = text.toCharArray(); var i = 0; for (char c : charArray) { if (c == ' ') { comp = comp.append(SPACE_COMPONENT.font(objectGenerator.getFontKey())); i += 4; } else { var charWidth = objectGenerator.getFont().getFontWidth().get(c); var t = charWidth != null ? charWidth.apply(objectGenerator.getHeight()) : 0; if (style.hasDecoration(TextDecoration.BOLD)) t++; if (style.hasDecoration(TextDecoration.ITALIC)) t++; comp = comp.append(Component.text(c).style(style.font(objectGenerator.getFontKey())) .append(AdventureUtil.getSpaceFont(-t)) .append(spaceComp)); i += space; } } component = comp.append(AdventureUtil.getSpaceFont(-i)); } @Override
package kor.toxicity.inventory.generator; public class FontObjectImpl implements GuiObject { private static final Component SPACE_COMPONENT = Component.text(' '); private final FontObjectGeneratorImpl objectGenerator; private final Component component; public FontObjectImpl(FontObjectGeneratorImpl objectGenerator, String text, Style style, int space, int xOffset) { this.objectGenerator = objectGenerator; var comp = Component.empty().append(AdventureUtil.getSpaceFont(xOffset)); var spaceComp = AdventureUtil.getSpaceFont(space); var charArray = text.toCharArray(); var i = 0; for (char c : charArray) { if (c == ' ') { comp = comp.append(SPACE_COMPONENT.font(objectGenerator.getFontKey())); i += 4; } else { var charWidth = objectGenerator.getFont().getFontWidth().get(c); var t = charWidth != null ? charWidth.apply(objectGenerator.getHeight()) : 0; if (style.hasDecoration(TextDecoration.BOLD)) t++; if (style.hasDecoration(TextDecoration.ITALIC)) t++; comp = comp.append(Component.text(c).style(style.font(objectGenerator.getFontKey())) .append(AdventureUtil.getSpaceFont(-t)) .append(spaceComp)); i += space; } } component = comp.append(AdventureUtil.getSpaceFont(-i)); } @Override
public @NotNull GuiObjectGenerator getGenerator() {
1
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,488
package com.erapor.erapor.service; @Service public class StudentsService { @Autowired StudentsRepository studentsRepository; @Autowired ValuesRepository valuesRepository; @Autowired Converter converter;
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){
2
2023-11-11 19:40:43+00:00
2k
ebandal/jDwgParser
src/structure/header/FileHeader.java
[ { "identifier": "DwgVersion", "path": "src/structure/DwgVersion.java", "snippet": "public enum DwgVersion {\n R13 (1), // AC1012\n R14 (2), // AC1014\n R15 (3),\n R2000 (3), // AC1015\n R18 (4),\n R2004 (4), // AC1018\n R21 (5),\n R2007 (5), // AC1021\n R2010 (6), // AC1024\n R2013 (7), // AC1027\n R2018 (8), // AC1032\n ;\n \n private int verNum;\n \n DwgVersion(int verNum) {\n this.verNum = verNum;\n }\n \n private DwgVersion(DwgVersion ver) {\n this.verNum = ver.verNum;\n }\n \n public boolean only(DwgVersion ver) {\n if (this.verNum == ver.verNum)\n return true;\n else\n return false;\n }\n \n public boolean between(DwgVersion ver1, DwgVersion ver2) {\n if (this.verNum >= ver1.verNum && this.verNum <= ver2.verNum)\n return true;\n else \n return false;\n }\n\n public boolean from(DwgVersion ver) {\n if (this.verNum > ver.verNum)\n return true;\n else \n return false;\n }\n \n public boolean until(DwgVersion ver) {\n if (this.verNum <= ver.verNum)\n return true;\n else \n return false;\n }\n}" }, { "identifier": "SectionLocator", "path": "src/structure/SectionLocator.java", "snippet": "public class SectionLocator {\n public byte number;\n public int seeker;\n public int size;\n}" }, { "identifier": "DataSectionPageHeader", "path": "src/structure/sectionpage/header/DataSectionPageHeader.java", "snippet": "public class DataSectionPageHeader {\n public int type;\n public int sectionNumber;\n public int compressDataSize;\n public int decompressedPageSize;\n public int startOffset;\n public int pageHeaderChecksum;\n public int dataChecksum;\n}" }, { "identifier": "SystemSectionPageHeader", "path": "src/structure/sectionpage/header/SystemSectionPageHeader.java", "snippet": "public class SystemSectionPageHeader {\n public int type;\n public int decompressedSize;\n public int compressedSize;\n public int compressionType;\n public int checksum;\n}" } ]
import java.util.List; import structure.DwgVersion; import structure.SectionLocator; import structure.sectionpage.header.DataSectionPageHeader; import structure.sectionpage.header.SystemSectionPageHeader;
727
package structure.header; public class FileHeader { public String versionId; public DwgVersion ver; public int imageSeeker; // R15 public int previewSeeker; // R2004 public byte appVer; // R2004 public byte appMrVer; // R2004 public short codePage; // R15, R2004 // SECTION-LOCATOR RECORDS
package structure.header; public class FileHeader { public String versionId; public DwgVersion ver; public int imageSeeker; // R15 public int previewSeeker; // R2004 public byte appVer; // R2004 public byte appMrVer; // R2004 public short codePage; // R15, R2004 // SECTION-LOCATOR RECORDS
public List<SectionLocator> sectionLocatorList; // R15
1
2023-11-11 13:57:18+00:00
2k
KomnisEvangelos/GeoApp
app/src/main/java/gr/ihu/geoapp/ui/profile/ProfileFragment.java
[ { "identifier": "RegularUser", "path": "app/src/main/java/gr/ihu/geoapp/models/users/RegularUser.java", "snippet": "public class RegularUser implements User{\n\n private static RegularUser single_instance = null;\n private String fullName = null;\n private String email = null;\n private String password = null;\n private String dateOfBirth = null;\n private String profession = null;\n private String Diploma = null;\n\n\n public static synchronized RegularUser getInstance()\n {\n if (single_instance == null)\n single_instance = new RegularUser();\n\n return single_instance;\n }\n\n private RegularUser(){\n\n }\n\n @Override\n public com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> login() {\n Repository repository = new Repository();\n\n return repository.checkUser(email,password);\n }\n\n @Override\n public com.google.android.gms.tasks.Task<com.google.firebase.auth.AuthResult> register() {\n\n Repository repository = new Repository();\n\n return repository.createUser(email,password);\n }\n\n @Override\n public void logout() {\n FirebaseAuth.getInstance().signOut();\n }\n\n\n @Override\n public void fetchData() {\n\n }\n\n //Getters and Setters\n public String getFullName() {\n return fullName;\n }\n\n public void setFullName(String fullName) {\n this.fullName = fullName;\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 public String getDateOfBirth() {\n return dateOfBirth;\n }\n\n public void setDateOfBirth(String dateOfBirth) {\n this.dateOfBirth = dateOfBirth;\n }\n\n public String getProfession() {\n return profession;\n }\n\n public void setProfession(String profession) {\n this.profession = profession;\n }\n\n public String getDiploma() {\n return Diploma;\n }\n\n public void setDiploma(String diploma) {\n Diploma = diploma;\n }\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 @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 user.login().addOnSuccessListener(new OnSuccessListener<AuthResult>() {\n @Override\n public void onSuccess(AuthResult authResult) {\n Toast.makeText(getApplicationContext(),\"Login successful\",Toast.LENGTH_SHORT).show();\n navigateToMainActivity();\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n Toast.makeText(getApplicationContext(),\"Login failed. Try again.\",Toast.LENGTH_SHORT).show();\n Log.d(\"FirebaseError\",e.getMessage());\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 private void navigateToMainActivity(){\n Intent intent = new Intent(getApplicationContext(), MainActivity.class);\n startActivity(intent);\n finish();\n }\n\n private void navigateToRegisterActivity(){\n Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);\n startActivity(intent);\n finish();\n }\n\n}" } ]
import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.google.firebase.auth.FirebaseAuth; import java.util.Optional; import gr.ihu.geoapp.databinding.FragmentProfileBinding; import gr.ihu.geoapp.models.users.RegularUser; import gr.ihu.geoapp.ui.signin.SignInActivity;
1,531
package gr.ihu.geoapp.ui.profile; public class ProfileFragment extends Fragment { private FragmentProfileBinding binding; private ImageView profileImageView; private TextView nameTextView; private TextView emailTextView; private TextView birthdayTextView; private TextView professionTextView; private TextView diplomaTextView; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ProfileViewModel profileViewModel = new ViewModelProvider(this).get(ProfileViewModel.class); binding = FragmentProfileBinding.inflate(inflater, container, false); View root = binding.getRoot(); profileImageView = binding.profileImageView; nameTextView = binding.nameTextView; emailTextView = binding.emailTextView; birthdayTextView = binding.birthdayTextView; professionTextView = binding.professionTextView; diplomaTextView = binding.diplomaTextView; RegularUser user = RegularUser.getInstance(); nameTextView.setText(Optional.ofNullable(user.getFullName()).orElse("No data found")); emailTextView.setText(Optional.ofNullable(user.getEmail()).orElse("No data found")); birthdayTextView.setText(Optional.ofNullable(user.getDateOfBirth()).orElse("No data found")); professionTextView.setText(Optional.ofNullable(user.getProfession()).orElse("No data found")); diplomaTextView.setText(Optional.ofNullable(user.getDiploma()).orElse("No data found")); Button logoutButton = binding.logoutButton; logoutButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { RegularUser.getInstance().logout();
package gr.ihu.geoapp.ui.profile; public class ProfileFragment extends Fragment { private FragmentProfileBinding binding; private ImageView profileImageView; private TextView nameTextView; private TextView emailTextView; private TextView birthdayTextView; private TextView professionTextView; private TextView diplomaTextView; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ProfileViewModel profileViewModel = new ViewModelProvider(this).get(ProfileViewModel.class); binding = FragmentProfileBinding.inflate(inflater, container, false); View root = binding.getRoot(); profileImageView = binding.profileImageView; nameTextView = binding.nameTextView; emailTextView = binding.emailTextView; birthdayTextView = binding.birthdayTextView; professionTextView = binding.professionTextView; diplomaTextView = binding.diplomaTextView; RegularUser user = RegularUser.getInstance(); nameTextView.setText(Optional.ofNullable(user.getFullName()).orElse("No data found")); emailTextView.setText(Optional.ofNullable(user.getEmail()).orElse("No data found")); birthdayTextView.setText(Optional.ofNullable(user.getDateOfBirth()).orElse("No data found")); professionTextView.setText(Optional.ofNullable(user.getProfession()).orElse("No data found")); diplomaTextView.setText(Optional.ofNullable(user.getDiploma()).orElse("No data found")); Button logoutButton = binding.logoutButton; logoutButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { RegularUser.getInstance().logout();
Intent intent = new Intent(getActivity(), SignInActivity.class);
1
2023-11-10 17:43:18+00:00
2k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/manager/init/start/CommandRegister.java
[ { "identifier": "GrimAPI", "path": "src/main/java/ac/grim/grimac/GrimAPI.java", "snippet": "@Getter\npublic enum GrimAPI {\n INSTANCE;\n\n private final PlayerDataManager playerDataManager = new PlayerDataManager();\n private final InitManager initManager = new InitManager();\n private final TickManager tickManager = new TickManager();\n private final DiscordManager discordManager = new DiscordManager();\n\n private GrimAC plugin;\n\n public void load(final GrimAC plugin) {\n this.plugin = plugin;\n initManager.load();\n }\n\n public void start(final GrimAC plugin) {\n this.plugin = plugin;\n initManager.start();\n }\n\n public void stop(final GrimAC plugin) {\n this.plugin = plugin;\n initManager.stop();\n }\n}" }, { "identifier": "GrimDebug", "path": "src/main/java/ac/grim/grimac/commands/GrimDebug.java", "snippet": "@CommandAlias(\"grim|grimac\")\npublic class GrimDebug extends BaseCommand {\n @Subcommand(\"debug\")\n @CommandPermission(\"grim.debug\")\n @CommandCompletion(\"@players\")\n public void onDebug(CommandSender sender, @Optional OnlinePlayer target) {\n Player player = null;\n if (sender instanceof Player) player = (Player) sender;\n\n GrimPlayer grimPlayer = parseTarget(sender, player, target);\n if (grimPlayer == null) return;\n\n if (sender instanceof ConsoleCommandSender) { // Just debug to console to reduce complexity...\n grimPlayer.checkManager.getDebugHandler().toggleConsoleOutput();\n } else { // This sender is a player\n grimPlayer.checkManager.getDebugHandler().toggleListener(player);\n }\n }\n\n private GrimPlayer parseTarget(CommandSender sender, Player player, OnlinePlayer target) {\n Player targetPlayer = target == null ? player : target.getPlayer();\n if (player == null && target == null) {\n sender.sendMessage(ChatColor.RED + \"You must specify a target as the console!\");\n return null;\n }\n\n GrimPlayer grimPlayer = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(targetPlayer);\n if (grimPlayer == null) sender.sendMessage(ChatColor.RED + \"This player is exempt from all checks!\");\n\n return grimPlayer;\n }\n\n @Subcommand(\"consoledebug\")\n @CommandPermission(\"grim.consoledebug\")\n @CommandCompletion(\"@players\")\n public void onConsoleDebug(CommandSender sender, @Optional OnlinePlayer target) {\n Player player = null;\n if (sender instanceof Player) player = (Player) sender;\n\n GrimPlayer grimPlayer = parseTarget(sender, player, target);\n if (grimPlayer == null) return;\n\n boolean isOutput = grimPlayer.checkManager.getDebugHandler().toggleConsoleOutput();\n\n sender.sendMessage(\"Console output for \" + grimPlayer.bukkitPlayer.getName() + \" is now \" + isOutput);\n }\n}" }, { "identifier": "GrimPerf", "path": "src/main/java/ac/grim/grimac/commands/GrimPerf.java", "snippet": "@CommandAlias(\"grim|grimac\")\npublic class GrimPerf extends BaseCommand {\n @Subcommand(\"perf|performance\")\n @CommandPermission(\"grim.performance\")\n public void onPerformance(CommandSender sender) {\n /*double nano = MovementCheckRunner.executor.getLongComputeTime() * 20 * GrimAPI.INSTANCE.getPlayerDataManager().size();\n // Convert this into seconds\n double seconds = nano / 1e9;\n\n sender.sendMessage(\"Nanoseconds per prediction: \" + MovementCheckRunner.executor.getComputeTime());\n sender.sendMessage(\"Estimated load (threads): \" + seconds);\n sender.sendMessage(\"Prediction threads: \" + MovementCheckRunner.executor.getPoolSize());\n sender.sendMessage(\"Players online: \" + GrimAPI.INSTANCE.getPlayerDataManager().size());*/\n sender.sendMessage(\"This command is currently broken.\");\n }\n}" }, { "identifier": "Initable", "path": "src/main/java/ac/grim/grimac/manager/init/Initable.java", "snippet": "public interface Initable {\n void start();\n}" } ]
import ac.grim.grimac.GrimAPI; import ac.grim.grimac.commands.GrimDebug; import ac.grim.grimac.commands.GrimPerf; import ac.grim.grimac.manager.init.Initable; import co.aikar.commands.PaperCommandManager;
1,029
package ac.grim.grimac.manager.init.start; public class CommandRegister implements Initable { @Override public void start() { // This does not make Grim require paper // It only enables new features such as asynchronous tab completion on paper
package ac.grim.grimac.manager.init.start; public class CommandRegister implements Initable { @Override public void start() { // This does not make Grim require paper // It only enables new features such as asynchronous tab completion on paper
PaperCommandManager commandManager = new PaperCommandManager(GrimAPI.INSTANCE.getPlugin());
0
2023-11-11 05:14:12+00:00
2k
StanCEmpire/Enquestment
src/main/java/stancempire/enquestment/events/UserEvents.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": "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}" }, { "identifier": "SBRequestOpenGui", "path": "src/main/java/stancempire/enquestment/network/packets/SBRequestOpenGui.java", "snippet": "public class SBRequestOpenGui\n{\n\n private ModScreen screen;\n /**\n * Constructor for initialising the packet on the client\n */\n public SBRequestOpenGui(ModScreen pScreen)\n {\n\n this.screen = pScreen;\n\n }\n\n /**\n * Encodes data to the packet\n */\n public void encode(FriendlyByteBuf buf)\n {\n\n buf.writeEnum(this.screen);\n\n }\n\n /**\n * Constructor for decoding data on the server\n */\n public SBRequestOpenGui(FriendlyByteBuf buf)\n {\n\n this.screen = buf.readEnum(ModScreen.class);\n\n }\n\n /**\n * Handles packet once recieved by the server\n */\n public void handle(NetworkEvent.Context ctx)\n {\n\n ctx.enqueueWork(() ->\n {\n\n if(this.screen != null)\n {\n\n NetworkManager.NETWORK_INSTANCE.send(PacketDistributor.PLAYER.with(ctx::getSender), new CBOpenGui(this.screen));\n\n }\n\n });\n\n }\n\n\n}" }, { "identifier": "ModScreen", "path": "src/main/java/stancempire/enquestment/network/util/ModScreen.java", "snippet": "public enum ModScreen\n{\n /**Test screen*/\n TEST\n\n}" } ]
import net.neoforged.bus.api.SubscribeEvent; import net.neoforged.neoforge.event.TickEvent; import stancempire.enquestment.client.ClientSetup; import stancempire.enquestment.network.NetworkManager; import stancempire.enquestment.network.packets.SBRequestOpenGui; import stancempire.enquestment.network.util.ModScreen;
989
package stancempire.enquestment.events; /** * <p>CLIENT CODE</p> * Class for handling user input events */ public class UserEvents { /** * Checks for custom keybinds */ @SubscribeEvent public void onKeyPressed(TickEvent.ClientTickEvent event) { if(event.phase == TickEvent.Phase.END) //Prevent logic from being executed twice { while(ClientSetup.EMENU_KEY.get().consumeClick()) //EMENU key {
package stancempire.enquestment.events; /** * <p>CLIENT CODE</p> * Class for handling user input events */ public class UserEvents { /** * Checks for custom keybinds */ @SubscribeEvent public void onKeyPressed(TickEvent.ClientTickEvent event) { if(event.phase == TickEvent.Phase.END) //Prevent logic from being executed twice { while(ClientSetup.EMENU_KEY.get().consumeClick()) //EMENU key {
NetworkManager.NETWORK_INSTANCE.sendToServer(new SBRequestOpenGui(ModScreen.TEST));
3
2023-11-11 13:16:04+00:00
2k
ImShyMike/QuestCompassPlus
src/main/java/shymike/questcompassplus/mixin/PlayerSpawnPositionMixin.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": "WaypointManager", "path": "src/main/java/shymike/questcompassplus/utils/WaypointManager.java", "snippet": "public class WaypointManager {\n public static void create(MinecraftClient mc, double x, double y, double z) {\n\t\tVec3d playerPos = mc.player.getPos();\n\t\t\n\t\tdouble distance = Math.round(DistanceCalculator.getDistance2D(playerPos.x, playerPos.z, x, z));\n\t\tRenderUtils.setCoordinates(x,y,z);\n\t\tRenderUtils.line1 = \"Compass Position: \" + (int)x + \" \" + (int)y + \" \" + (int)z;\n\t\tif (Config.chatFeedback) {\n\t\t\tif (Config.waypointCopy) {\n\t\t\t\t\tChatUtils.send(Text.literal(\"Compass Position: x=\" + (int)Config.x + \", y=\" + (int)Config.y + \", z=\" + (int)Config.z + \", distance=\" + (int)distance).styled(style -> style\n\t\t\t\t\t\t\t.withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, \"/jm wpedit [name:\\\"Quest Location\\\", x:\"+(int)Config.x+\", y:\"+(int)Config.y+\", z:\"+(int)Config.z+\", dim:minecraft:overworld]\"))\n\t\t\t\t\t\t\t.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal(\"Click to make waypoint!\")))));\n\t\t\t\t} else if (Config.chatFeedback) {\n\t\t\t \tChatUtils.send(Text.literal(\"Compass Position: x=\" + (int)Config.x + \", y=\" + (int)Config.y + \", z=\" + (int)Config.z + \", distance=\" + (int)distance).styled(style -> style\n\t\t\t \t\t\t.withClickEvent(new ClickEvent(ClickEvent.Action.COPY_TO_CLIPBOARD, (int)Config.x+\" \"+(int)Config.y+\" \"+(int)Config.z))\n\t\t\t \t\t\t.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal(\"Click to copy coordinates to clipboard!\")))));\n\t\t\t\t}\n\t\t}\n\t\t\n\t\t// TODO: actual waypoints\n\t}\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.WaypointManager; import shymike.questcompassplus.utils.ServerUtils; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.MinecraftClient; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.network.packet.s2c.play.PlayerSpawnPositionS2CPacket; 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 net.minecraft.util.math.BlockPos;
1,238
package shymike.questcompassplus.mixin; @Environment(EnvType.CLIENT) @Mixin(ClientPlayNetworkHandler.class) public class PlayerSpawnPositionMixin { private double xL = 0, yL = 0, zL = 0; private MinecraftClient mc = MinecraftClient.getInstance(); @Inject(method = "onPlayerSpawnPosition", at = @At("RETURN")) private void onPlayerSpawnPosition(PlayerSpawnPositionS2CPacket packet, CallbackInfo ci) { BlockPos pos = packet.getPos(); double x = pos.getX(), y = pos.getY(), z = pos.getZ(); Config.setCoordinates(x,y,z); if (ServerUtils.isOnMonumenta()) { // Anti spam if (x != xL || y != yL || z != zL) { this.xL = x; this.yL = y; this.zL = z;
package shymike.questcompassplus.mixin; @Environment(EnvType.CLIENT) @Mixin(ClientPlayNetworkHandler.class) public class PlayerSpawnPositionMixin { private double xL = 0, yL = 0, zL = 0; private MinecraftClient mc = MinecraftClient.getInstance(); @Inject(method = "onPlayerSpawnPosition", at = @At("RETURN")) private void onPlayerSpawnPosition(PlayerSpawnPositionS2CPacket packet, CallbackInfo ci) { BlockPos pos = packet.getPos(); double x = pos.getX(), y = pos.getY(), z = pos.getZ(); Config.setCoordinates(x,y,z); if (ServerUtils.isOnMonumenta()) { // Anti spam if (x != xL || y != yL || z != zL) { this.xL = x; this.yL = y; this.zL = z;
WaypointManager.create(mc, x, y, z);
1
2023-11-14 15:56:39+00:00
2k
kawainime/IOT-Smart_Farming
IOT_Farm_V.2/src/Core/Background/Task_Schedule.java
[ { "identifier": "Load_Data", "path": "IOT_Farm_V.2/src/Core/SQL_Lite3/Load_Data.java", "snippet": "public class Load_Data \n{\n public static String load_condition(String condition)\n {\n String value = null;\n \n String SQL = \"SELECT \"+condition+\" FROM Report WHERE Record_ID = 413;\";\n \n Connection connection = Lite_Connector.connect();\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(condition);\n }\n \n connection.close();\n \n return value;\n }\n catch(Exception ERROR)\n {\n Bugs_Log.exceptions(SQL);\n \n System.out.println(ERROR);\n \n try \n {\n connection.close();\n }\n catch(SQLException ex) \n {\n Logger.getLogger(Load_Data.class.getName()).log(Level.SEVERE, null, ex);\n }\n \n return \"null\";\n }\n\n }\n}" }, { "identifier": "jLabel14", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel14;" }, { "identifier": "jLabel15", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel15;" }, { "identifier": "jLabel16", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel16;" }, { "identifier": "jLabel18", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel18;" }, { "identifier": "jLabel2", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel2;" }, { "identifier": "jLabel21", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel21;" }, { "identifier": "jLabel24", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel24;" }, { "identifier": "jLabel27", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel27;" }, { "identifier": "jLabel7", "path": "IOT_Farm_V.2/src/UI/Globle_weather.java", "snippet": "public static javax.swing.JLabel jLabel7;" } ]
import Core.SQL_Lite3.Load_Data; import static UI.Globle_weather.jLabel14; import static UI.Globle_weather.jLabel15; import static UI.Globle_weather.jLabel16; import static UI.Globle_weather.jLabel18; import static UI.Globle_weather.jLabel2; import static UI.Globle_weather.jLabel21; import static UI.Globle_weather.jLabel24; import static UI.Globle_weather.jLabel27; import static UI.Globle_weather.jLabel7; import java.util.Timer; import java.util.TimerTask;
775
package Core.Background; public class Task_Schedule { public static void load_data() { jLabel2.setText(Load_Data.load_condition("Weather")); jLabel27.setText(Load_Data.load_condition("Weather")+","+Load_Data.load_condition("Weather_description")); jLabel24.setText(Load_Data.load_condition("Feel_Like")+" F"); jLabel18.setText(Load_Data.load_condition("Wind_Speed")+" km/h"); jLabel21.setText(Load_Data.load_condition("Pressure")+" MB"); jLabel14.setText("Max Temperature : "+Load_Data.load_condition("Max_Temp")+" F"); jLabel15.setText("Min Temperature : "+Load_Data.load_condition("Min_Temp")+ " F");
package Core.Background; public class Task_Schedule { public static void load_data() { jLabel2.setText(Load_Data.load_condition("Weather")); jLabel27.setText(Load_Data.load_condition("Weather")+","+Load_Data.load_condition("Weather_description")); jLabel24.setText(Load_Data.load_condition("Feel_Like")+" F"); jLabel18.setText(Load_Data.load_condition("Wind_Speed")+" km/h"); jLabel21.setText(Load_Data.load_condition("Pressure")+" MB"); jLabel14.setText("Max Temperature : "+Load_Data.load_condition("Max_Temp")+" F"); jLabel15.setText("Min Temperature : "+Load_Data.load_condition("Min_Temp")+ " F");
jLabel7.setText("Temperature In F : "+Load_Data.load_condition("Temperature")+ " F");
9
2023-11-11 08:23:10+00:00
2k
Outer-Fields/item-server
src/main/java/io/mindspice/itemserver/services/LeaderBoardService.java
[ { "identifier": "PlayerScore", "path": "src/main/java/io/mindspice/itemserver/schema/PlayerScore.java", "snippet": "public class PlayerScore {\n @JsonProperty(\"name\") public final String playerName;\n @JsonProperty(\"won\") public int wins = 0;\n @JsonProperty(\"lost\") public int losses = 0;\n\n public PlayerScore(String playerName) {\n this.playerName = playerName;\n }\n\n @JsonProperty(\"win_ratio\")\n public double getWinRatio() {\n if (wins == 0 && losses == 0) { return 0.0; }\n return BigDecimal.valueOf((double) wins / (wins + losses)).setScale(3, RoundingMode.HALF_UP).doubleValue();\n }\n\n public void addResult(boolean isWin) {\n if (isWin) { wins++; } else { losses++; }\n }\n\n public int getWins() {\n return wins;\n }\n\n public double getSortMetric() {\n double winRatioWeight = 0.8;\n double numberOfGamesWeight = 0.2;\n int totalGames = wins + losses;\n return (getWinRatio() * winRatioWeight) + (totalGames * numberOfGamesWeight);\n }\n\n public String toString() {\n return \"Player: \" + playerName + \"Wins: \" + wins + \" | Losses: \" + losses + \" | Win Ratio: \" + getWinRatio();\n }\n}" }, { "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}" } ]
import io.mindspice.databaseservice.client.api.OkraGameAPI; import io.mindspice.databaseservice.client.schema.MatchResult; import io.mindspice.itemserver.schema.PlayerScore; import io.mindspice.itemserver.util.CustomLogger; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.ZoneId; import java.util.Comparator; import java.util.HashMap; import java.util.List;
1,006
package io.mindspice.itemserver.services; public class LeaderBoardService { private final OkraGameAPI gameAPI;
package io.mindspice.itemserver.services; public class LeaderBoardService { private final OkraGameAPI gameAPI;
public final CustomLogger logger;
1
2023-11-14 14:56:37+00:00
2k
KvRae/Mobile-Exemple-Java-Android
Project/app/src/main/java/com/example/pharmacie2/Views/Activities/SignUpActivity.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.annotation.SuppressLint; 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,380
package com.example.pharmacie2.Views.Activities; public class SignUpActivity extends AppCompatActivity { TextView signInBtn; Button buttonSignUp; private EditText editTextName; private EditText editTextEmail; private EditText editTextPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); editTextName = findViewById(R.id.editTextName); editTextEmail = findViewById(R.id.editTextEmail); editTextPassword = findViewById(R.id.editTextPassword); buttonSignUp = findViewById(R.id.buttonSignUp); buttonSignUp.setOnClickListener(v -> { String name = editTextName.getText().toString().trim(); String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); // Check if the email is already registered new CheckEmailTask().execute(name, email, password); }); signInBtn = findViewById(R.id.textViewSignInLink); signInBtn.setOnClickListener( e -> { Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); finish(); Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show(); } ); } private class CheckEmailTask extends AsyncTask<String, Void, Boolean> { private String[] params; @Override protected Boolean doInBackground(String... params) { this.params = params; // Stored the parameters String name = params[0]; String email = params[1]; String password = params[2]; PharmacyDB userDatabase = PharmacyDB.getInstance(getApplicationContext()); UserDao userDao = userDatabase.userDao(); // Check if the email is already registered
package com.example.pharmacie2.Views.Activities; public class SignUpActivity extends AppCompatActivity { TextView signInBtn; Button buttonSignUp; private EditText editTextName; private EditText editTextEmail; private EditText editTextPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); editTextName = findViewById(R.id.editTextName); editTextEmail = findViewById(R.id.editTextEmail); editTextPassword = findViewById(R.id.editTextPassword); buttonSignUp = findViewById(R.id.buttonSignUp); buttonSignUp.setOnClickListener(v -> { String name = editTextName.getText().toString().trim(); String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); // Check if the email is already registered new CheckEmailTask().execute(name, email, password); }); signInBtn = findViewById(R.id.textViewSignInLink); signInBtn.setOnClickListener( e -> { Intent intent = new Intent(this, SignInActivity.class); startActivity(intent); finish(); Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show(); } ); } private class CheckEmailTask extends AsyncTask<String, Void, Boolean> { private String[] params; @Override protected Boolean doInBackground(String... params) { this.params = params; // Stored the parameters String name = params[0]; String email = params[1]; String password = params[2]; PharmacyDB userDatabase = PharmacyDB.getInstance(getApplicationContext()); UserDao userDao = userDatabase.userDao(); // Check if the email is already registered
User existingUser = userDao.getUserByEmail(email);
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);
1
2023-11-16 10:12:20+00:00
2k
Mightinity/store-management-system
src/main/java/com/systeminventory/controller/productCardController.java
[ { "identifier": "DeleteProductListener", "path": "src/main/java/com/systeminventory/interfaces/DeleteProductListener.java", "snippet": "public interface DeleteProductListener {\n public void clickDeleteProductListener(Product product);\n}" }, { "identifier": "DetailsProductListener", "path": "src/main/java/com/systeminventory/interfaces/DetailsProductListener.java", "snippet": "public interface DetailsProductListener {\n public void clickDetailsProductListener(Product product);\n}" }, { "identifier": "EditProductListener", "path": "src/main/java/com/systeminventory/interfaces/EditProductListener.java", "snippet": "public interface EditProductListener {\n public void clickEditProductListener(Product product);\n}" }, { "identifier": "Product", "path": "src/main/java/com/systeminventory/model/Product.java", "snippet": "public class Product {\n private String productName;\n private String imageSource;\n private String productOriginalPrice;\n private String productSellingPrice;\n private String productStock;\n private String keyProduct;\n private String idProduct;\n\n\n\n public String getProductName() {\n return productName;\n }\n\n public void setProductName(String productName) {\n this.productName = productName;\n }\n\n public String getImageSource() {\n return imageSource;\n }\n\n public void setImageSource(String imageSource) {\n this.imageSource = imageSource;\n }\n\n public String getProductSellingPrice() {\n return productSellingPrice;\n }\n\n public void setProductSellingPrice(String productSellingPrice) {\n this.productSellingPrice = productSellingPrice;\n }\n\n public String getProductStock() {\n return productStock;\n }\n\n public void setProductStock(String productStock) {\n this.productStock = productStock;\n }\n\n public String getKeyProduct() {\n return keyProduct;\n }\n\n public void setKeyProduct(String keyProduct) {\n this.keyProduct = keyProduct;\n }\n\n public String getProductOriginalPrice() {\n return productOriginalPrice;\n }\n\n public void setProductOriginalPrice(String productOriginalPrice) {\n this.productOriginalPrice = productOriginalPrice;\n }\n\n public String getIdProduct() {\n return idProduct;\n }\n\n public void setIdProduct(String idProduct) {\n this.idProduct = idProduct;\n }\n}" } ]
import com.systeminventory.interfaces.DeleteProductListener; import com.systeminventory.interfaces.DetailsProductListener; import com.systeminventory.interfaces.EditProductListener; import com.systeminventory.model.Product; 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.Pane; import java.io.File; import java.io.IOException;
717
package com.systeminventory.controller; public class productCardController { @FXML private ImageView productCardImage; @FXML private Label productCardPrice; @FXML private Label productCardTitle; @FXML private Label productCardStock; @FXML private Pane deleteButtonProduct; @FXML private Pane editButtonProduct; @FXML private Pane infoButtonProduct; @FXML private Label keyProduct; private Product product; private DeleteProductListener deleteProductListener;
package com.systeminventory.controller; public class productCardController { @FXML private ImageView productCardImage; @FXML private Label productCardPrice; @FXML private Label productCardTitle; @FXML private Label productCardStock; @FXML private Pane deleteButtonProduct; @FXML private Pane editButtonProduct; @FXML private Pane infoButtonProduct; @FXML private Label keyProduct; private Product product; private DeleteProductListener deleteProductListener;
private EditProductListener editProductListener;
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,329
package io.dsntk.server.rest.controllers; /** * Java RPC controller. */ @Slf4j @RestController @RequestMapping(RequestMappings.M_RPC_SERVER) public class RpcController { private final RpcService rpcService; /** Initializes RPC controller. */ public RpcController(RpcService rpcService) { this.rpcService = rpcService; } /** * Returns system info. * * @return System info DTO wrapped in ResultDTO. */ @PostMapping(RequestMappings.M_V1 + RequestMappings.M_RPC_EVALUATE)
package io.dsntk.server.rest.controllers; /** * Java RPC controller. */ @Slf4j @RestController @RequestMapping(RequestMappings.M_RPC_SERVER) public class RpcController { private final RpcService rpcService; /** Initializes RPC controller. */ public RpcController(RpcService rpcService) { this.rpcService = rpcService; } /** * Returns system info. * * @return System info DTO wrapped in ResultDTO. */ @PostMapping(RequestMappings.M_V1 + RequestMappings.M_RPC_EVALUATE)
public ResultDto<ValueDto> evaluate(@RequestBody RpcParams params) throws RpcException {
2
2023-11-10 18:06:05+00:00
2k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/modules/ArrowDmg.java
[ { "identifier": "MeteorRejectsAddon", "path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java", "snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(\"Rejects\", Items.BARRIER.getDefaultStack());\n public static final HudGroup HUD_GROUP = new HudGroup(\"Rejects\");\n\n @Override\n public void onInitialize() {\n LOG.info(\"Initializing Meteor Rejects Addon\");\n\n // Modules\n Modules modules = Modules.get();\n\n modules.add(new BetterAimbot());\n modules.add(new NewerNewChunks());\n modules.add(new BaseFinderNew());\n modules.add(new Shield());\n modules.add(new TestModule());\n modules.add(((new HitboxDesync())));\n modules.add(new Announcer());\n modules.add(new PacketLogger());\n modules.add(new ManualCrystal());\n modules.add(new TweakedAutoTool());\n modules.add(new MacroAnchorAuto());\n modules.add(new AutoMend());\n modules.add(new BowBomb());\n modules.add(new AutoCityPlus());\n modules.add(new PistonAura());\n modules.add(new CevBreaker());\n\n modules.add(new AimAssist());\n modules.add(new AntiBot());\n modules.add(new AntiCrash());\n modules.add(new AntiSpawnpoint());\n modules.add(new AntiVanish());\n modules.add(new ArrowDmg());\n modules.add(new AutoBedTrap());\n modules.add(new AutoCraft());\n modules.add(new AutoExtinguish());\n modules.add(new AutoFarm());\n modules.add(new AutoGrind());\n modules.add(new AutoLogin());\n modules.add(new AutoPot());\n modules.add(new AutoSoup());\n modules.add(new AutoTNT());\n modules.add(new AutoWither());\n modules.add(new BoatGlitch());\n modules.add(new BlockIn());\n modules.add(new BoatPhase());\n modules.add(new Boost());\n modules.add(new BungeeCordSpoof());\n modules.add(new ChatBot());\n modules.add(new ChestAura());\n modules.add(new ChorusExploit());\n modules.add(new ColorSigns());\n modules.add(new Confuse());\n modules.add(new CoordLogger());\n modules.add(new CustomPackets());\n modules.add(new ExtraElytra());\n modules.add(new FullFlight());\n modules.add(new GamemodeNotifier());\n modules.add(new GhostMode());\n modules.add(new Glide());\n modules.add(new InstaMine());\n modules.add(new ItemGenerator());\n modules.add(new InteractionMenu());\n modules.add(new Jetpack());\n modules.add(new KnockbackPlus());\n modules.add(new Lavacast());\n modules.add(new MossBot());\n modules.add(new NewChunks());\n modules.add(new NoJumpDelay());\n modules.add(new ObsidianFarm());\n modules.add(new OreSim());\n modules.add(new PacketFly());\n modules.add(new Painter());\n modules.add(new Rendering());\n modules.add(new RoboWalk());\n modules.add(new ShieldBypass());\n modules.add(new SilentDisconnect());\n modules.add(new SkeletonESP());\n modules.add(new SoundLocator());\n modules.add(new TreeAura());\n modules.add(new VehicleOneHit());\n\n // Commands\n Commands.add(new CenterCommand());\n Commands.add(new ClearChatCommand());\n Commands.add(new GhostCommand());\n Commands.add(new GiveCommand());\n Commands.add(new HeadsCommand());\n Commands.add(new KickCommand());\n Commands.add(new LocateCommand());\n Commands.add(new PanicCommand());\n Commands.add(new ReconnectCommand());\n Commands.add(new ServerCommand());\n Commands.add(new SaveSkinCommand());\n Commands.add(new SeedCommand());\n Commands.add(new SetBlockCommand());\n Commands.add(new SetVelocityCommand());\n Commands.add(new TeleportCommand());\n Commands.add(new TerrainExport());\n Commands.add(new EntityDesyncCommand());\n Commands.add(new BaseFinderNewCommands());\n Commands.add(new NewChunkCounter());\n\n // HUD\n Hud hud = Systems.get(Hud.class);\n hud.register(RadarHud.INFO);\n\n // Themes\n GuiThemes.add(new MeteorRoundedGuiTheme());\n }\n\n @Override\n public void onRegisterCategories() {\n Modules.registerCategory(CATEGORY);\n }\n\n @Override\n public String getWebsite() {\n return \"https://github.com/JohnTWD/meteor-rejects-vanillacpvp\";\n }\n\n @Override\n public GithubRepo getRepo() {\n return new GithubRepo(\"JohnTWD\", \"meteor-rejects-vanilla-cpvp\");\n }\n\n @Override\n public String getCommit() {\n String commit = FabricLoader\n .getInstance()\n .getModContainer(\"meteor-rejects\")\n .get().getMetadata()\n .getCustomValue(\"github:sha\")\n .getAsString();\n LOG.info(String.format(\"Rejects version: %s\", commit));\n return commit.isEmpty() ? null : commit.trim();\n }\n\n public String getPackage() {\n return \"anticope.rejects\";\n }\n}" }, { "identifier": "StopUsingItemEvent", "path": "src/main/java/anticope/rejects/events/StopUsingItemEvent.java", "snippet": "public class StopUsingItemEvent {\n private static final StopUsingItemEvent INSTANCE = new StopUsingItemEvent();\n\n public ItemStack itemStack;\n\n public static StopUsingItemEvent get(ItemStack itemStack) {\n INSTANCE.itemStack = itemStack;\n return INSTANCE;\n }\n}" } ]
import anticope.rejects.MeteorRejectsAddon; import anticope.rejects.events.StopUsingItemEvent; import meteordevelopment.meteorclient.settings.BoolSetting; import meteordevelopment.meteorclient.settings.IntSetting; import meteordevelopment.meteorclient.settings.Setting; import meteordevelopment.meteorclient.settings.SettingGroup; import meteordevelopment.meteorclient.systems.modules.Module; import meteordevelopment.orbit.EventHandler; import net.minecraft.client.network.ClientPlayerEntity; import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.network.packet.c2s.play.ClientCommandC2SPacket; import net.minecraft.network.packet.c2s.play.PlayerMoveC2SPacket;
1,595
package anticope.rejects.modules; public class ArrowDmg extends Module { private final SettingGroup sgGeneral = settings.getDefaultGroup(); public final Setting<Integer> packets = sgGeneral.add(new IntSetting.Builder() .name("packets") .description("Amount of packets to send. More packets = higher damage.") .defaultValue(200) .min(2) .sliderMax(2000) .build() ); public final Setting<Boolean> tridents = sgGeneral.add(new BoolSetting.Builder() .name("tridents") .description("When enabled, tridents fly much further. Doesn't seem to affect damage or Riptide. WARNING: You can easily lose your trident by enabling this option!") .defaultValue(false) .build() ); public ArrowDmg() {
package anticope.rejects.modules; public class ArrowDmg extends Module { private final SettingGroup sgGeneral = settings.getDefaultGroup(); public final Setting<Integer> packets = sgGeneral.add(new IntSetting.Builder() .name("packets") .description("Amount of packets to send. More packets = higher damage.") .defaultValue(200) .min(2) .sliderMax(2000) .build() ); public final Setting<Boolean> tridents = sgGeneral.add(new BoolSetting.Builder() .name("tridents") .description("When enabled, tridents fly much further. Doesn't seem to affect damage or Riptide. WARNING: You can easily lose your trident by enabling this option!") .defaultValue(false) .build() ); public ArrowDmg() {
super(MeteorRejectsAddon.CATEGORY, "arrow-damage", "Massively increases arrow damage, but also consumes a lot of hunger and reduces accuracy. Does not work with crossbows and seems to be patched on Paper servers.");
0
2023-11-13 08:11:28+00:00
2k
cosmah/database
src/main/java/com/example/application/service/WorkerService.java
[ { "identifier": "UserNotFoundException", "path": "src/main/java/com/example/application/exceptions/UserNotFoundException.java", "snippet": "public class UserNotFoundException extends RuntimeException {\n public UserNotFoundException(String message) {\n super(message);\n }\n}" }, { "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": "WorkerRepository", "path": "src/main/java/com/example/application/repository/WorkerRepository.java", "snippet": "public interface WorkerRepository extends JpaRepository<Worker, Long>{\n void deleteWorkerById(Long id);\n\n Optional<Worker> findWorkerById(Long id);\n\n}" } ]
import com.example.application.exceptions.UserNotFoundException; import com.example.application.model.Worker; import com.example.application.repository.WorkerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.UUID;
738
package com.example.application.service; @Service public class WorkerService { private final WorkerRepository workerRepository; @Autowired public WorkerService(WorkerRepository workerRepository) { this.workerRepository = workerRepository; }
package com.example.application.service; @Service public class WorkerService { private final WorkerRepository workerRepository; @Autowired public WorkerService(WorkerRepository workerRepository) { this.workerRepository = workerRepository; }
public Worker addWorker(Worker worker){
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;
1,074
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?")) { Main.changedScene("main"); } } @FXML protected void HomeAction(MouseEvent e) { Main.changedScene("home"); } @FXML protected void FuncAction(MouseEvent e) { Main.changedScene("func"); } @FXML protected void MedAction(MouseEvent e) { Main.changedScene("med"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("client"); } @FXML private TableColumn tcDateRecord; @FXML private TableColumn tcIdRecord; @FXML private TableColumn tcMedRecord; @FXML private TableColumn tcPriceRecord; @FXML private TableColumn tcQuantRecord; @FXML private TableColumn tcUserRecord; @FXML private TableView tvRecord; public void tableRecord()throws SQLException { List<RecordTable> order = new ArrayList<>(); String consultaSQLregistro = "SELECT * FROM registros";
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?")) { Main.changedScene("main"); } } @FXML protected void HomeAction(MouseEvent e) { Main.changedScene("home"); } @FXML protected void FuncAction(MouseEvent e) { Main.changedScene("func"); } @FXML protected void MedAction(MouseEvent e) { Main.changedScene("med"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("client"); } @FXML private TableColumn tcDateRecord; @FXML private TableColumn tcIdRecord; @FXML private TableColumn tcMedRecord; @FXML private TableColumn tcPriceRecord; @FXML private TableColumn tcQuantRecord; @FXML private TableColumn tcUserRecord; @FXML private TableView tvRecord; public void tableRecord()throws SQLException { List<RecordTable> order = new ArrayList<>(); String consultaSQLregistro = "SELECT * FROM registros";
Statement statement = connection.createStatement();
2
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,382
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ class BMgrTest { @Test void bMgrTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk);
package cs.adb.wzh.bufferManager; /** * @author Wang Zihui * @date 2023/11/12 **/ class BMgrTest { @Test void bMgrTest() throws Exception { Buffer bf = new Buffer(8); Disk disk = new Disk(); BMgr bMgr = new BMgr(bf, disk);
for (BCB p = bMgr.getHead(); p.getFrameId() != -1; p = p.getNext()) {
2
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,562
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(); public static final Side[] sides = new Side[]{Side.BOTTOM, Side.TOP, Side.NORTH, Side.SOUTH, Side.WEST, Side.EAST}; public static double terrainAtlasWidth = TextureFX.tileWidthTerrain * Global.TEXTURE_ATLAS_WIDTH_TILES; public static String version; public static boolean isDev; public static String renderState = "gui"; static { version = FabricLoader.getInstance().getModContainer(MOD_ID).get().getMetadata().getVersion().getFriendlyString(); isDev = version.equals("${version}") || version.contains("dev"); } @Override public void beforeGameStart() { if (isDev){ LOGGER.info("DragonFly " + version + " loading debug assets");
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(); public static final Side[] sides = new Side[]{Side.BOTTOM, Side.TOP, Side.NORTH, Side.SOUTH, Side.WEST, Side.EAST}; public static double terrainAtlasWidth = TextureFX.tileWidthTerrain * Global.TEXTURE_ATLAS_WIDTH_TILES; public static String version; public static boolean isDev; public static String renderState = "gui"; static { version = FabricLoader.getInstance().getModContainer(MOD_ID).get().getMetadata().getVersion().getFriendlyString(); isDev = version.equals("${version}") || version.contains("dev"); } @Override public void beforeGameStart() { if (isDev){ LOGGER.info("DragonFly " + version + " loading debug assets");
DebugMain.init();
0
2023-11-16 01:10:52+00:00
2k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/config/caffeine/CaffeineConfiguration.java
[ { "identifier": "CaffeineCondition", "path": "src/main/java/top/sharehome/springbootinittemplate/config/caffeine/condition/CaffeineCondition.java", "snippet": "public class CaffeineCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {\n String property = context.getEnvironment().getProperty(\"caffeine.enable\");\n return StringUtils.equals(\"true\", property);\n }\n\n}" }, { "identifier": "CaffeineProperties", "path": "src/main/java/top/sharehome/springbootinittemplate/config/caffeine/properties/CaffeineProperties.java", "snippet": "@Data\n@ConfigurationProperties(prefix = \"caffeine\")\npublic class CaffeineProperties {\n\n /**\n * 是否启动\n */\n private Boolean enable = false;\n\n /**\n * 最后一次写入或访问后经过固定时间过期,单位:秒\n */\n private Long expired = 1800L;\n\n /**\n * 缓存初始容量\n */\n private Integer initCapacity = 256;\n\n /**\n * 缓存最大容量,超过之后会按照最近最少策略进行缓存剔除\n */\n private Integer maxCapacity = 10000;\n\n /**\n * 是否允许空值null作为缓存的value\n */\n private Boolean allowNullValue = true;\n\n}" }, { "identifier": "RedissonCondition", "path": "src/main/java/top/sharehome/springbootinittemplate/config/redisson/condition/RedissonCondition.java", "snippet": "public class RedissonCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {\n String redissonSingleProperty = context.getEnvironment().getProperty(\"redisson.single-server-config.enable-single\");\n String redissonClusterProperty = context.getEnvironment().getProperty(\"redisson.cluster-servers-config.enable-cluster\");\n return StringUtils.equals(\"true\", redissonSingleProperty) || StringUtils.equals(\"true\", redissonClusterProperty);\n }\n\n}" } ]
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import top.sharehome.springbootinittemplate.config.caffeine.condition.CaffeineCondition; import top.sharehome.springbootinittemplate.config.caffeine.properties.CaffeineProperties; import top.sharehome.springbootinittemplate.config.redisson.condition.RedissonCondition; import javax.annotation.PostConstruct; import java.util.concurrent.TimeUnit;
683
package top.sharehome.springbootinittemplate.config.caffeine; /** * Caffeine配置 * * @author AntonyCheng */ @Configuration @EnableConfigurationProperties(CaffeineProperties.class) @AllArgsConstructor @Slf4j
package top.sharehome.springbootinittemplate.config.caffeine; /** * Caffeine配置 * * @author AntonyCheng */ @Configuration @EnableConfigurationProperties(CaffeineProperties.class) @AllArgsConstructor @Slf4j
@Conditional(CaffeineCondition.class)
0
2023-11-12 07:49:59+00:00
2k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/render/opengl/OpenGLShaderProgram.java
[ { "identifier": "ShaderProgram", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/shader/ShaderProgram.java", "snippet": "public interface ShaderProgram extends SafeCloseable {\n}" }, { "identifier": "ShaderStage", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/shader/ShaderStage.java", "snippet": "public interface ShaderStage extends SafeCloseable {\n /** The type of stage. */\n enum Type {\n /** Stage that executes for every vertex in the mesh. */\n VERTEX,\n\n /** Stage that executes for every rasterized pixel. */\n FRAGMENT\n }\n\n Type getType();\n}" }, { "identifier": "ShaderUniform", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/shader/ShaderUniform.java", "snippet": "public interface ShaderUniform {\n /**\n * Sets the variable to a {@code float} value.\n *\n * @param f value to set\n */\n void setFloat(float f);\n\n /**\n * Sets the variable to a {@code vec2} value.\n *\n * @param v value to set\n */\n void setVec2(Vector2fc v);\n\n /**\n * Sets the variable to a {@code vec3} value.\n *\n * @param v value to set\n */\n void setVec3(Vector3fc v);\n\n /**\n * Sets the variable to a {@code vec4} value.\n *\n * @param v value to set\n */\n void setVec4(Vector4fc v);\n\n /**\n * Sets the variable to a {@code mat4} value.\n *\n * @param m value to set\n */\n void setMat4(Matrix4fc m);\n\n /**\n * Sets the variable to a {@code int} value.\n *\n * @param i value to set\n */\n void setInt(int i);\n\n /**\n * Sets the variable to a texture value. The slot corresponds to the slot\n * index the texture is bound using\n * {@link com.github.rmheuer.azalea.render.pipeline.ActivePipeline#bindTexture(int, Texture)}.\n *\n * @param slotIdx texture slot to pass into the shader\n */\n void setTexture(int slotIdx);\n}" } ]
import com.github.rmheuer.azalea.render.shader.ShaderProgram; import com.github.rmheuer.azalea.render.shader.ShaderStage; import com.github.rmheuer.azalea.render.shader.ShaderUniform; import org.joml.Matrix4fc; import org.joml.Vector2fc; import org.joml.Vector3fc; import org.joml.Vector4fc; import org.lwjgl.system.MemoryStack; import java.nio.FloatBuffer; import java.util.HashMap; import java.util.Map; import static org.lwjgl.opengl.GL33C.*;
725
package com.github.rmheuer.azalea.render.opengl; public final class OpenGLShaderProgram implements ShaderProgram { private final int id; private final Map<String, ShaderUniform> uniforms;
package com.github.rmheuer.azalea.render.opengl; public final class OpenGLShaderProgram implements ShaderProgram { private final int id; private final Map<String, ShaderUniform> uniforms;
public OpenGLShaderProgram(ShaderStage[] stages) {
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,104
package es.uhu.etsi.tallerhexagonal.tiendahexa.configurador; @Configuration public class TiendaHexaConfiguracion { @Bean public ClienteStore clienteStore ( ClienteRepository clienteRepository) { return new ConversorStoreSpringJpa(clienteRepository); } @Bean public ClienteService clienteService ( ClienteStore clienteStore ) {
package es.uhu.etsi.tallerhexagonal.tiendahexa.configurador; @Configuration public class TiendaHexaConfiguracion { @Bean public ClienteStore clienteStore ( ClienteRepository clienteRepository) { return new ConversorStoreSpringJpa(clienteRepository); } @Bean public ClienteService clienteService ( ClienteStore clienteStore ) {
return new ClienteServiceImpl(clienteStore);
1
2023-11-18 12:57:56+00:00
2k
orijer/IvritInterpreter
src/FlowController.java
[ { "identifier": "GeneralFileRuntimeException", "path": "src/IvritExceptions/GeneralFileRuntimeException.java", "snippet": "public class GeneralFileRuntimeException extends UncheckedIOException {\r\n /**\r\n * Constructor.\r\n * @param cause - What caused this exception.\r\n */\r\n public GeneralFileRuntimeException(IOException cause) {\r\n super(\"התרחשה שגיאה כללית בזמן הרצת הקובץ.\", cause);\r\n }\r\n \r\n}\r" }, { "identifier": "UserInput", "path": "src/UserInput/UserInput.java", "snippet": "public class UserInput {\r\n //this is true IFF the user is currently allowed to send input:\r\n private volatile boolean isUserInputAllowed;\r\n //The last input from the user (if there wasn't any input yet, it is null):\r\n private String lastUserInput;\r\n\r\n public UserInput() {\r\n this.isUserInputAllowed = false;\r\n this.lastUserInput = null;\r\n }\r\n\r\n /**\r\n * @return the last input from the user.\r\n * If there wasn't any input yet- we return null\r\n */\r\n public String getLastUserInput() {\r\n return this.lastUserInput;\r\n }\r\n\r\n /**\r\n * Updates this object after receiving an input from the user\r\n * @param newInput - The new last input of the user.\r\n * @throws UnsupportedOperationException when a new input was received from the user while this object was not expecting it.\r\n */\r\n public void newInputReceived(String newInput) {\r\n if (this.isUserInputAllowed) {\r\n this.lastUserInput = newInput;\r\n this.isUserInputAllowed = false;\r\n } else {\r\n throw new UnsupportedOperationException(\"התקבל קלט משתמש ללא הכנה מוקדמת לכך\");\r\n }\r\n\r\n }\r\n\r\n /**\r\n * @return true IFF the user can currently send input.\r\n */\r\n public boolean getIsUserInputAllowed() {\r\n return this.isUserInputAllowed;\r\n }\r\n\r\n /**\r\n * Enables to user to send input.\r\n */\r\n public void allowUserInput() {\r\n this.isUserInputAllowed = true;\r\n }\r\n\r\n /**\r\n * Does nothing until a new input is received from the user.\r\n */\r\n public void waitForNewUserInput() {\r\n allowUserInput();\r\n\r\n CountDownLatch latch = new CountDownLatch(1);\r\n UserInputWorker worker = new UserInputWorker(this, latch);\r\n worker.execute();\r\n\r\n try {\r\n latch.await();\r\n } catch (InterruptedException exception) {\r\n exception.printStackTrace();\r\n }\r\n\r\n }\r\n}\r" }, { "identifier": "RestartableReader", "path": "src/IvritStreams/RestartableReader.java", "snippet": "public interface RestartableReader extends Closeable{\r\n /**\r\n * @return the next code line (not jump flags, comment) of the file.\r\n */\r\n public String readLine() throws IOException;\r\n\r\n /**\r\n * Restarts the reader at the first line.\r\n */\r\n public void restart() throws IOException;\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.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import IvritExceptions.GeneralFileRuntimeException; import UserInput.UserInput; import IvritStreams.RestartableReader; import IvritStreams.RestartableBufferedReader;
1,504
/** * Handles controlling the flow of the Interpretor. */ public class FlowController { private UserInput userInput; //The GUI of the console that the Interpreter uses: private IvritInterpreterGUI gui; /** * Constructor. */ public FlowController() { this.userInput = new UserInput(); this.gui = new IvritInterpreterGUI(this.userInput); } /** * Contains the logic for starting the interpreting process. * @throws GeneralFileRuntimeException when an exception that cannot be traces happened during runtime. */ public void startIvritInterpreter(boolean isFirstRun) { //We first try to load the file to interpret: File sourceFile; try { sourceFile = handleFileLoad(isFirstRun); if (sourceFile == null) //sourceFile is null IFF the user requested to end the program. return; } catch (Exception exception) { //If we get an exception, print it and try again: System.out.println("נתקלנו בשגיאה לא מוכרת בזמן השגת כתובת ההרצה"); System.out.println("ננסה מחדש:"); startIvritInterpreter(isFirstRun); return; } //A simple test to see that the loading works correctly:
/** * Handles controlling the flow of the Interpretor. */ public class FlowController { private UserInput userInput; //The GUI of the console that the Interpreter uses: private IvritInterpreterGUI gui; /** * Constructor. */ public FlowController() { this.userInput = new UserInput(); this.gui = new IvritInterpreterGUI(this.userInput); } /** * Contains the logic for starting the interpreting process. * @throws GeneralFileRuntimeException when an exception that cannot be traces happened during runtime. */ public void startIvritInterpreter(boolean isFirstRun) { //We first try to load the file to interpret: File sourceFile; try { sourceFile = handleFileLoad(isFirstRun); if (sourceFile == null) //sourceFile is null IFF the user requested to end the program. return; } catch (Exception exception) { //If we get an exception, print it and try again: System.out.println("נתקלנו בשגיאה לא מוכרת בזמן השגת כתובת ההרצה"); System.out.println("ננסה מחדש:"); startIvritInterpreter(isFirstRun); return; } //A simple test to see that the loading works correctly:
try (RestartableReader reader = new RestartableBufferedReader(sourceFile)) {
3
2023-11-17 09:15:07+00:00
2k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmSalarySlipTemplateOptionController.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": "HrmSalarySlipTemplateOption", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/PO/HrmSalarySlipTemplateOption.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@TableName(\"wk_hrm_salary_slip_template_option\")\n@ApiModel(value = \"HrmSalarySlipTemplateOption对象\", description = \"工资条模板项\")\npublic class HrmSalarySlipTemplateOption implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long id;\n\n @ApiModelProperty(value = \"模板id\")\n @JsonSerialize(using = ToStringSerializer.class)\n private Long templateId;\n\n @ApiModelProperty(value = \"薪资项名称\")\n private String name;\n\n @ApiModelProperty(value = \"选项类型 1 分类 2 薪资项\")\n private Integer type;\n\n @ApiModelProperty(value = \"薪资项code\")\n private Integer code;\n\n @ApiModelProperty(value = \"备注\")\n private String remark;\n\n @ApiModelProperty(value = \"父级分类id\")\n @JsonSerialize(using = ToStringSerializer.class)\n private Long pid;\n\n @ApiModelProperty(value = \"是否隐藏 0 否 1 是\")\n private Integer isHide;\n\n @ApiModelProperty(value = \"排序\")\n private Integer sort;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createTime;\n\n @TableField(fill = FieldFill.INSERT)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long createUserId;\n\n @TableField(fill = FieldFill.UPDATE)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long updateUserId;\n\n @TableField(fill = FieldFill.UPDATE)\n private LocalDateTime updateTime;\n\n @ApiModelProperty(value = \"语言包map\")\n @TableField(exist = false)\n private Map<String, String> languageKeyMap;\n\n @TableField(exist = false)\n private List<HrmSalarySlipTemplateOption> optionList;\n\n\n}" }, { "identifier": "IHrmSalarySlipTemplateOptionService", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/service/IHrmSalarySlipTemplateOptionService.java", "snippet": "public interface IHrmSalarySlipTemplateOptionService extends BaseService<HrmSalarySlipTemplateOption> {\n\n /**\n * 查询工资模板项\n *\n * @param templateId\n * @return\n */\n List<HrmSalarySlipTemplateOption> queryTemplateOptionByTemplateId(Long templateId);\n}" } ]
import com.kakarote.core.common.Result; import com.kakarote.hrm.entity.PO.HrmSalarySlipTemplateOption; import com.kakarote.hrm.service.IHrmSalarySlipTemplateOptionService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List;
1,485
package com.kakarote.hrm.controller; /** * <p> * 工资条模板项 前端控制器 * </p> * * @author hmb * @since 2020-11-03 */ @RestController @RequestMapping("/hrmSalarySlipTemplateOption") @Api(tags = "工资条-工资条模板项接口") public class HrmSalarySlipTemplateOptionController { @Autowired private IHrmSalarySlipTemplateOptionService slipTemplateOptionService; @PostMapping("/queryTemplateOptionByTemplateId/{templateId}") @ApiOperation("查询工资模板项")
package com.kakarote.hrm.controller; /** * <p> * 工资条模板项 前端控制器 * </p> * * @author hmb * @since 2020-11-03 */ @RestController @RequestMapping("/hrmSalarySlipTemplateOption") @Api(tags = "工资条-工资条模板项接口") public class HrmSalarySlipTemplateOptionController { @Autowired private IHrmSalarySlipTemplateOptionService slipTemplateOptionService; @PostMapping("/queryTemplateOptionByTemplateId/{templateId}") @ApiOperation("查询工资模板项")
public Result<List<HrmSalarySlipTemplateOption>> queryTemplateOptionByTemplateId(@PathVariable("templateId") Long templateId) {
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;
688
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;
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;
private ChatMaxToken chatMaxToken = ChatMaxToken.MEDIUM;
0
2023-10-18 06:29:13+00:00
2k
djkcyl/Shamrock
qqinterface/src/main/java/tencent/im/msg/im_msg_body.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": "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": "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": "PBRepeatMessageField", "path": "qqinterface/src/main/java/com/tencent/mobileqq/pb/PBRepeatMessageField.java", "snippet": "public final class PBRepeatMessageField<T extends MessageMicro<T>> extends PBField<List<T>> {\n public PBRepeatMessageField(Class<T> cls) {\n\n }\n\n public void add(T t) {\n\n }\n\n public T get(int pos) {\n return null;\n }\n\n public List<T> get() {\n return null;\n }\n\n public boolean isEmpty() {\n return false;\n }\n\n public void set(int i2, T t) {\n }\n\n public void set(List<T> list) {\n }\n\n public int size() {\n return 0;\n }\n\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.PBBytesField; import com.tencent.mobileqq.pb.PBField; import com.tencent.mobileqq.pb.PBRepeatMessageField; import com.tencent.mobileqq.pb.PBStringField; import com.tencent.mobileqq.pb.PBUInt32Field; import com.tencent.mobileqq.pb.PBUInt64Field;
1,571
package tencent.im.msg; public class im_msg_body { public static class MsgBody extends MessageMicro<MsgBody> { public final PBBytesField msg_content; public final PBBytesField msg_encrypt_content; public RichText rich_text = new RichText(); public MsgBody() { ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY; this.msg_content = PBField.initBytes(byteStringMicro); this.msg_encrypt_content = PBField.initBytes(byteStringMicro); } } public static class RichText extends MessageMicro<RichText> { //public im_msg_body$Attr attr = new im_msg_body$Attr();
package tencent.im.msg; public class im_msg_body { public static class MsgBody extends MessageMicro<MsgBody> { public final PBBytesField msg_content; public final PBBytesField msg_encrypt_content; public RichText rich_text = new RichText(); public MsgBody() { ByteStringMicro byteStringMicro = ByteStringMicro.EMPTY; this.msg_content = PBField.initBytes(byteStringMicro); this.msg_encrypt_content = PBField.initBytes(byteStringMicro); } } public static class RichText extends MessageMicro<RichText> { //public im_msg_body$Attr attr = new im_msg_body$Attr();
public final PBRepeatMessageField<Elem> elems = PBField.initRepeatMessage(Elem.class);
4
2023-10-20 10:43:47+00:00
2k
ballerina-platform/module-ballerinax-copybook
commons/src/main/java/io/ballerina/lib/copybook/commons/schema/LengthCalculator.java
[ { "identifier": "isAlphaNumeric", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isAlphaNumeric(String pictureString) {\n // ex: PIC XXX\n return Pattern.compile(\"^X+$\").matcher(pictureString).find();\n}" }, { "identifier": "isAlphaNumericWithCardinality", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isAlphaNumericWithCardinality(String pictureString) {\n // ex: PIC X(9)\n return Pattern.compile(\"^X\\\\(\\\\d+\\\\)$\").matcher(pictureString).find();\n}" }, { "identifier": "isDecimal", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isDecimal(String pictureString) {\n // ex: PIC 99.99 or -99.99 or +99.99\n return Pattern.compile(\"^[+-]?9+\\\\.9+$\").matcher(pictureString).find();\n}" }, { "identifier": "isDecimalWithCardinality", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isDecimalWithCardinality(String pictureString) {\n // ex: PIC 9(9).333 or -9(9).333 or +9(9).333\n return Pattern.compile(\"^[+-]?9\\\\(\\\\d+\\\\)\\\\.9+$\").matcher(pictureString).find();\n}" }, { "identifier": "isDecimalWithSuppressedZeros", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isDecimalWithSuppressedZeros(String pictureString) {\n // PIC Z(9)99.99\n return Pattern.compile(\"^Z\\\\(\\\\d+\\\\)9+.9+$\").matcher(pictureString).find();\n}" }, { "identifier": "isInt", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isInt(String pictureString) {\n // ex: PIC 999\n return Pattern.compile(\"^9+$\").matcher(pictureString).find();\n}" }, { "identifier": "isIntWithCardinality", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isIntWithCardinality(String pictureString) {\n // ex: PIC 9(2)\n return Pattern.compile(\"^9\\\\(\\\\d+\\\\)$\").matcher(pictureString).find();\n}" }, { "identifier": "isSignRememberedIntWithCardinality", "path": "commons/src/main/java/io/ballerina/lib/copybook/commons/schema/PictureStringValidator.java", "snippet": "static boolean isSignRememberedIntWithCardinality(String pictureString) {\n // ex: PIC S9(2)\n return Pattern.compile(\"^S9\\\\(\\\\d+\\\\)$\").matcher(pictureString).find();\n}" } ]
import java.util.regex.Matcher; import java.util.regex.Pattern; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isAlphaNumeric; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isAlphaNumericWithCardinality; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isDecimal; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isDecimalWithCardinality; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isDecimalWithSuppressedZeros; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isInt; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isIntWithCardinality; import static io.ballerina.lib.copybook.commons.schema.PictureStringValidator.isSignRememberedIntWithCardinality;
1,116
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class LengthCalculator { private LengthCalculator() { } static int calculateFractionLength(String pictureString) { if (!isDecimal(pictureString) && !isDecimalWithCardinality(pictureString) && !isDecimalWithSuppressedZeros( pictureString)) { return 0; } Matcher matcher = Pattern.compile("^.*\\.(?<fraction>9+)$").matcher(pictureString); if (matcher.find()) { return matcher.group("fraction").length(); } return 0; } static int calculateReadLength(String pictureString) { if (isAlphaNumeric(pictureString) || isInt(pictureString) || isDecimal(pictureString)) { return pictureString.length(); }
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.lib.copybook.commons.schema; class LengthCalculator { private LengthCalculator() { } static int calculateFractionLength(String pictureString) { if (!isDecimal(pictureString) && !isDecimalWithCardinality(pictureString) && !isDecimalWithSuppressedZeros( pictureString)) { return 0; } Matcher matcher = Pattern.compile("^.*\\.(?<fraction>9+)$").matcher(pictureString); if (matcher.find()) { return matcher.group("fraction").length(); } return 0; } static int calculateReadLength(String pictureString) { if (isAlphaNumeric(pictureString) || isInt(pictureString) || isDecimal(pictureString)) { return pictureString.length(); }
if (isAlphaNumericWithCardinality(pictureString)) {
1
2023-10-24 04:51:53+00:00
2k
ballerina-platform/copybook-tools
copybook-cli/src/main/java/io/ballerina/tools/copybook/utils/Utils.java
[ { "identifier": "DiagnosticMessages", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/diagnostic/DiagnosticMessages.java", "snippet": "public enum DiagnosticMessages {\n COPYBOOK_TYPE_GEN_100(\"COPYBOOK_TYPE_GEN_100\", \"Copybook types generation failed: The input file path argument\" +\n \" is missing. Please provide the path of the Copybook definition file with -i or --input flag.\",\n DiagnosticSeverity.ERROR),\n COPYBOOK_TYPE_GEN_102(\"COPYBOOK_TYPE_GEN_102\", \"Copybook types generation failed: %s\", DiagnosticSeverity.ERROR),\n COPYBOOK_TYPE_GEN_103(\"COPYBOOK_TYPE_GEN_103\", \"Failed to create output directory: %s\", DiagnosticSeverity.ERROR);\n private final String code;\n private final String description;\n private final DiagnosticSeverity severity;\n\n DiagnosticMessages(String code, String description, DiagnosticSeverity severity) {\n this.code = code;\n this.description = description;\n this.severity = severity;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public DiagnosticSeverity getSeverity() {\n return severity;\n }\n}" }, { "identifier": "CopybookTypeGenerationException", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/exception/CopybookTypeGenerationException.java", "snippet": "public class CopybookTypeGenerationException extends Exception {\n private final Diagnostic diagnostic;\n\n public CopybookTypeGenerationException(DiagnosticMessages diagnosticMessage, Location location, String... args) {\n super(generateDescription(diagnosticMessage, args));\n this.diagnostic = createDiagnostic(diagnosticMessage, location, args);\n }\n\n public String getMessage() {\n return this.diagnostic.toString();\n }\n\n private static String generateDescription(DiagnosticMessages message, String... args) {\n return String.format(message.getDescription(), (Object[]) args);\n }\n\n private static Diagnostic createDiagnostic(DiagnosticMessages diagnosticMessage, Location location,\n String... args) {\n DiagnosticInfo diagnosticInfo = new DiagnosticInfo(diagnosticMessage.getCode(),\n generateDescription(diagnosticMessage, args), diagnosticMessage.getSeverity());\n if (location == null) {\n location = NullLocation.getInstance();\n }\n return DiagnosticFactory.createDiagnostic(diagnosticInfo, location);\n }\n}" }, { "identifier": "PERIOD", "path": "copybook-cli/src/main/java/io/ballerina/tools/copybook/generator/GeneratorConstants.java", "snippet": "public static final String PERIOD = \".\";" } ]
import static io.ballerina.tools.copybook.generator.GeneratorConstants.PERIOD; import io.ballerina.tools.copybook.diagnostic.DiagnosticMessages; import io.ballerina.tools.copybook.exception.CopybookTypeGenerationException; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Locale; import java.util.Objects;
1,274
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.tools.copybook.utils; public class Utils { private Utils() { } public static boolean createOutputDirectory(Path outputPath) { File outputDir = new File(outputPath.toString()); if (!outputDir.exists()) { return outputDir.mkdirs(); } return true; } public static void writeFile(Path filePath, String content) throws CopybookTypeGenerationException { try (FileWriter writer = new FileWriter(filePath.toString(), StandardCharsets.UTF_8)) { writer.write(content); } catch (IOException e) { throw new CopybookTypeGenerationException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.getMessage()); } } public static String resolveSchemaFileName(Path outPath, String fileName) { if (outPath != null && Files.exists(outPath)) { final File[] listFiles = new File(String.valueOf(outPath)).listFiles(); if (listFiles != null) { fileName = checkAvailabilityOfGivenName(fileName, listFiles); } } return fileName; } private static String checkAvailabilityOfGivenName(String schemaName, File[] listFiles) { for (File file : listFiles) { if (System.console() != null && file.getName().equals(schemaName)) { String userInput = System.console().readLine("There is already a file named '" + file.getName() + "' in the target location. Do you want to overwrite the file? [y/N] "); if (!Objects.equals(userInput.toLowerCase(Locale.ENGLISH), "y")) { schemaName = setGeneratedFileName(listFiles, schemaName); } } } return schemaName; } private static String setGeneratedFileName(File[] listFiles, String fileName) { int duplicateCount = 0; for (File listFile : listFiles) { String listFileName = listFile.getName(); if (listFileName.contains(".") && ((listFileName.split("\\.")).length >= 2) && (listFileName.split("\\.")[0].equals(fileName.split("\\.")[0]))) { duplicateCount++; } }
/* * Copyright (c) 2023, WSO2 LLC. (http://www.wso2.com) All Rights Reserved. * * WSO2 LLC. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.ballerina.tools.copybook.utils; public class Utils { private Utils() { } public static boolean createOutputDirectory(Path outputPath) { File outputDir = new File(outputPath.toString()); if (!outputDir.exists()) { return outputDir.mkdirs(); } return true; } public static void writeFile(Path filePath, String content) throws CopybookTypeGenerationException { try (FileWriter writer = new FileWriter(filePath.toString(), StandardCharsets.UTF_8)) { writer.write(content); } catch (IOException e) { throw new CopybookTypeGenerationException(DiagnosticMessages.COPYBOOK_TYPE_GEN_102, null, e.getMessage()); } } public static String resolveSchemaFileName(Path outPath, String fileName) { if (outPath != null && Files.exists(outPath)) { final File[] listFiles = new File(String.valueOf(outPath)).listFiles(); if (listFiles != null) { fileName = checkAvailabilityOfGivenName(fileName, listFiles); } } return fileName; } private static String checkAvailabilityOfGivenName(String schemaName, File[] listFiles) { for (File file : listFiles) { if (System.console() != null && file.getName().equals(schemaName)) { String userInput = System.console().readLine("There is already a file named '" + file.getName() + "' in the target location. Do you want to overwrite the file? [y/N] "); if (!Objects.equals(userInput.toLowerCase(Locale.ENGLISH), "y")) { schemaName = setGeneratedFileName(listFiles, schemaName); } } } return schemaName; } private static String setGeneratedFileName(File[] listFiles, String fileName) { int duplicateCount = 0; for (File listFile : listFiles) { String listFileName = listFile.getName(); if (listFileName.contains(".") && ((listFileName.split("\\.")).length >= 2) && (listFileName.split("\\.")[0].equals(fileName.split("\\.")[0]))) { duplicateCount++; } }
return fileName.split("\\.")[0] + PERIOD + duplicateCount + PERIOD + fileName.split("\\.")[1];
2
2023-10-24 05:00:08+00:00
2k
zhaoeryu/eu-backend
eu-admin/src/main/java/cn/eu/system/service/ISysRoleService.java
[ { "identifier": "IEuService", "path": "eu-common-core/src/main/java/cn/eu/common/base/service/IEuService.java", "snippet": "public interface IEuService<T> extends IService<T> {\n\n}" }, { "identifier": "PageResult", "path": "eu-common-core/src/main/java/cn/eu/common/model/PageResult.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PageResult<T> {\n\n private List<T> records;\n private Long total;\n\n public static <T> PageResult<T> of(List<T> records, Long total) {\n return new PageResult<>(records, total);\n }\n\n public static <T> PageResult<T> of(List<T> records) {\n PageInfo<T> pageInfo = new PageInfo<>(records);\n return of(pageInfo.getList(), pageInfo.getTotal());\n }\n\n}" }, { "identifier": "SysRole", "path": "eu-admin/src/main/java/cn/eu/system/domain/SysRole.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"sys_role\")\npublic class SysRole extends BaseEntity {\n\n private static final long serialVersionUID = 1L;\n\n @ExcelIgnore\n @TableId(type = IdType.AUTO)\n private Integer id;\n /** 角色KEY */\n @ExcelProperty(\"角色key\")\n @NotBlank(message = \"角色key不能为空\")\n private String roleKey;\n /** 角色名称 */\n @ExcelProperty(\"角色名称\")\n @NotBlank(message = \"角色名称不能为空\")\n private String roleName;\n /** 角色描述 */\n @ExcelProperty(\"角色描述\")\n private String description;\n /**\n * 角色状态\n * @see SysRoleStatus#getValue()\n */\n @ExcelProperty(value = \"角色状态\", converter = SysRoleStatusConverter.class)\n private Integer status;\n /**\n * 数据权限\n */\n @ExcelIgnore\n private Integer dataScope;\n}" }, { "identifier": "ImportResult", "path": "eu-admin/src/main/java/cn/eu/system/model/dto/ImportResult.java", "snippet": "@Data\npublic class ImportResult {\n\n /**\n * 更新数据量\n */\n private Integer updateCount;\n\n /**\n * 新增数据量\n */\n private Integer addCount;\n\n}" }, { "identifier": "SysRoleDto", "path": "eu-admin/src/main/java/cn/eu/system/model/dto/SysRoleDto.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class SysRoleDto extends SysRole {\n\n /**\n * 操作类型\n * 1: 菜单权限\n * 2: 数据权限\n */\n private Integer operAction;\n\n private List<Integer> menuIds;\n\n private List<Integer> deptIds;\n}" }, { "identifier": "SysRoleQueryCriteria", "path": "eu-admin/src/main/java/cn/eu/system/model/query/SysRoleQueryCriteria.java", "snippet": "@Data\npublic class SysRoleQueryCriteria {\n\n @Query(type = Query.Type.LIKE)\n private String roleName;\n\n}" } ]
import cn.eu.common.base.service.IEuService; import cn.eu.common.model.PageResult; import cn.eu.system.domain.SysRole; import cn.eu.system.model.dto.ImportResult; import cn.eu.system.model.dto.SysRoleDto; import cn.eu.system.model.query.SysRoleQueryCriteria; import org.springframework.data.domain.Pageable; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List;
966
package cn.eu.system.service; /** * @author zhaoeryu * @since 2023/5/31 */ public interface ISysRoleService extends IEuService<SysRole> { PageResult<SysRole> page(SysRoleQueryCriteria criteria, Pageable pageable); List<SysRole> list(SysRoleQueryCriteria criteria); List<String> getRolePermissionByUserId(String userId); List<SysRole> getRolesByUserId(String userId); List<Integer> getRoleIdsByUserId(String userId); void createRole(SysRoleDto entity); void updateRole(SysRoleDto entity); List<Integer> getMenuIdsByRoleId(Integer roleId); List<Integer> getDeptIdsByRoleId(Integer roleId); void exportTemplate(HttpServletResponse response) throws IOException;
package cn.eu.system.service; /** * @author zhaoeryu * @since 2023/5/31 */ public interface ISysRoleService extends IEuService<SysRole> { PageResult<SysRole> page(SysRoleQueryCriteria criteria, Pageable pageable); List<SysRole> list(SysRoleQueryCriteria criteria); List<String> getRolePermissionByUserId(String userId); List<SysRole> getRolesByUserId(String userId); List<Integer> getRoleIdsByUserId(String userId); void createRole(SysRoleDto entity); void updateRole(SysRoleDto entity); List<Integer> getMenuIdsByRoleId(Integer roleId); List<Integer> getDeptIdsByRoleId(Integer roleId); void exportTemplate(HttpServletResponse response) throws IOException;
ImportResult importData(MultipartFile file, Integer importMode) throws IOException;
3
2023-10-20 07:08:37+00:00
2k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/client/GTCMCreativeTabs.java
[ { "identifier": "texter", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextHandler.java", "snippet": "public static String texter(String aTextLine, String aKey) {\n\n /**\n * If not in Dev mode , return vanilla forge method directly.\n */\n if (TwistSpaceTechnology.isInDevMode) {\n if (LangMap.get(aKey) == null) {\n TwistSpaceTechnology.LOG.info(\"Texter get a new key - TextLine: \" + aKey + \" - \" + aTextLine);\n LangMapNeedToWrite.put(aKey, aTextLine);\n return aTextLine;\n } else {\n return translateToLocalFormatted(aKey);\n }\n } else if (null != translateToLocalFormatted(aKey)) {\n return translateToLocalFormatted(aKey);\n }\n return \"texterError: \" + aTextLine;\n}" }, { "identifier": "BasicItems", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/item/items/BasicItems.java", "snippet": "public final class BasicItems {\n\n public static final Item MetaItem01 = new ItemAdder01(\n \"MetaItem01Base\",\n \"MetaItem01\",\n GTCMCreativeTabs.tabMetaItem01).setTextureName(\"gtnhcommunitymod:MetaItem01/0\");\n\n public static final Item MetaItemRune = new ItemAdderRune(\n \"MetaItemRuneBase\",\n \"MetaItemRune\",\n GTCMCreativeTabs.tabMetaItem01).setTextureName(\"gtnhcommunitymod:MetaItem01/0\");\n\n public static final Item ProofOfHeroes = new ItemProofOfHeroes(\n \"英雄の証\",\n \"ProofOfHeroes\",\n GTCMCreativeTabs.tabMetaItem01).setTextureName(\"gtnhcommunitymod:ProofOfHeroes\");\n\n public static final Item MultiStructuresLinkTool = new ItemMultiStructuresLinkTool(\n \"Multi-Structures Link Tool\",\n \"MultiStructuresLinkTool\",\n GTCMCreativeTabs.tabMultiStructures);\n\n}" } ]
import static com.Nxer.TwistSpaceTechnology.util.TextHandler.texter; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import com.Nxer.TwistSpaceTechnology.common.item.items.BasicItems; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly;
658
package com.Nxer.TwistSpaceTechnology.client; public class GTCMCreativeTabs { /** * Creative Tab for MetaItem01 */ public static final CreativeTabs tabMetaItem01 = new CreativeTabs( texter("TST Meta Items 1", "itemGroup.TST Meta Items 1")) { @Override @SideOnly(Side.CLIENT) public Item getTabIconItem() {
package com.Nxer.TwistSpaceTechnology.client; public class GTCMCreativeTabs { /** * Creative Tab for MetaItem01 */ public static final CreativeTabs tabMetaItem01 = new CreativeTabs( texter("TST Meta Items 1", "itemGroup.TST Meta Items 1")) { @Override @SideOnly(Side.CLIENT) public Item getTabIconItem() {
return BasicItems.MetaItem01;
1
2023-10-16 09:57:15+00:00
2k
wyjsonGo/GoRouter
GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/processor/GenerateApplicationModuleProcessor.java
[ { "identifier": "APPLICATION", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String APPLICATION = \"android.app.Application\";" }, { "identifier": "APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX = \"%s\" + SEPARATOR + \"%s\" + SEPARATOR + \"AP\";" }, { "identifier": "APPLICATION_MODULE_PACKAGE_NAME", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String APPLICATION_MODULE_PACKAGE_NAME = PACKAGE_NAME + \".module.application\";" }, { "identifier": "CONFIGURATION", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String CONFIGURATION = \"android.content.res.Configuration\";" }, { "identifier": "CONTEXT", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String CONTEXT = \"android.content.Context\";" }, { "identifier": "FIELD_MAM", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String FIELD_MAM = \"mAM\";// mApplicationModule" }, { "identifier": "I_APPLICATION_MODULE_PACKAGE_NAME", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String I_APPLICATION_MODULE_PACKAGE_NAME = PACKAGE_NAME + \".interfaces.IApplicationModule\";" }, { "identifier": "METHOD_NAME_ON_CONFIGURATION_CHANGED", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_ON_CONFIGURATION_CHANGED = \"onConfigurationChanged\";" }, { "identifier": "METHOD_NAME_ON_CREATE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_ON_CREATE = \"onCreate\";" }, { "identifier": "METHOD_NAME_ON_LOAD_ASYNC", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_ON_LOAD_ASYNC = \"onLoadAsync\";" }, { "identifier": "METHOD_NAME_ON_LOW_MEMORY", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_ON_LOW_MEMORY = \"onLowMemory\";" }, { "identifier": "METHOD_NAME_ON_TERMINATE", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_ON_TERMINATE = \"onTerminate\";" }, { "identifier": "METHOD_NAME_ON_TRIM_MEMORY", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_ON_TRIM_MEMORY = \"onTrimMemory\";" }, { "identifier": "METHOD_NAME_SET_PRIORITY", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String METHOD_NAME_SET_PRIORITY = \"setPriority\";" }, { "identifier": "NONNULL", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String NONNULL = \"androidx.annotation.NonNull\";" }, { "identifier": "PREFIX_OF_LOGGER", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String PREFIX_OF_LOGGER = PROJECT + \"::Compiler \";" }, { "identifier": "WARNING_TIPS", "path": "GoRouter-Compiler/src/main/java/com/wyjson/router/compiler/utils/Constants.java", "snippet": "public static final String WARNING_TIPS = \"DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY GOROUTER.\";" } ]
import static com.wyjson.router.compiler.utils.Constants.APPLICATION; import static com.wyjson.router.compiler.utils.Constants.APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX; import static com.wyjson.router.compiler.utils.Constants.APPLICATION_MODULE_PACKAGE_NAME; import static com.wyjson.router.compiler.utils.Constants.CONFIGURATION; import static com.wyjson.router.compiler.utils.Constants.CONTEXT; import static com.wyjson.router.compiler.utils.Constants.FIELD_MAM; import static com.wyjson.router.compiler.utils.Constants.I_APPLICATION_MODULE_PACKAGE_NAME; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_CONFIGURATION_CHANGED; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_CREATE; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_LOAD_ASYNC; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_LOW_MEMORY; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_TERMINATE; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_ON_TRIM_MEMORY; import static com.wyjson.router.compiler.utils.Constants.METHOD_NAME_SET_PRIORITY; import static com.wyjson.router.compiler.utils.Constants.NONNULL; import static com.wyjson.router.compiler.utils.Constants.PREFIX_OF_LOGGER; import static com.wyjson.router.compiler.utils.Constants.WARNING_TIPS; import static javax.lang.model.element.Modifier.FINAL; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import com.google.auto.service.AutoService; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.wyjson.router.annotation.ApplicationModule; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror;
1,501
package com.wyjson.router.compiler.processor; @AutoService(Processor.class) public class GenerateApplicationModuleProcessor extends BaseProcessor { TypeMirror mApplication; TypeMirror mContext; TypeMirror mConfiguration; TypeElement mNONNULL; TypeElement mIApplicationModule; @Override public Set<String> getSupportedAnnotationTypes() { Set<String> set = new LinkedHashSet<>(); set.add(ApplicationModule.class.getCanonicalName()); return set; } @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); logger.info(moduleName + " >>> GenerateApplicationModuleProcessor init. <<<"); mApplication = elementUtils.getTypeElement(APPLICATION).asType(); mContext = elementUtils.getTypeElement(CONTEXT).asType(); mConfiguration = elementUtils.getTypeElement(CONFIGURATION).asType(); mNONNULL = elementUtils.getTypeElement(NONNULL); mIApplicationModule = elementUtils.getTypeElement(I_APPLICATION_MODULE_PACKAGE_NAME); } @Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { if (CollectionUtils.isEmpty(set)) return false; Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(ApplicationModule.class); if (CollectionUtils.isEmpty(elements)) return false; logger.info(moduleName + " >>> Found ApplicationModule, size is " + elements.size() + " <<<"); for (Element element : elements) { verify(element); String applicationModuleClassName = ((TypeElement) element).getQualifiedName().toString(); String className = String.format(APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX, generateClassName, element.getSimpleName().toString()); TypeSpec.Builder thisClass = TypeSpec.classBuilder(className) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(mIApplicationModule))
package com.wyjson.router.compiler.processor; @AutoService(Processor.class) public class GenerateApplicationModuleProcessor extends BaseProcessor { TypeMirror mApplication; TypeMirror mContext; TypeMirror mConfiguration; TypeElement mNONNULL; TypeElement mIApplicationModule; @Override public Set<String> getSupportedAnnotationTypes() { Set<String> set = new LinkedHashSet<>(); set.add(ApplicationModule.class.getCanonicalName()); return set; } @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); logger.info(moduleName + " >>> GenerateApplicationModuleProcessor init. <<<"); mApplication = elementUtils.getTypeElement(APPLICATION).asType(); mContext = elementUtils.getTypeElement(CONTEXT).asType(); mConfiguration = elementUtils.getTypeElement(CONFIGURATION).asType(); mNONNULL = elementUtils.getTypeElement(NONNULL); mIApplicationModule = elementUtils.getTypeElement(I_APPLICATION_MODULE_PACKAGE_NAME); } @Override public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) { if (CollectionUtils.isEmpty(set)) return false; Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(ApplicationModule.class); if (CollectionUtils.isEmpty(elements)) return false; logger.info(moduleName + " >>> Found ApplicationModule, size is " + elements.size() + " <<<"); for (Element element : elements) { verify(element); String applicationModuleClassName = ((TypeElement) element).getQualifiedName().toString(); String className = String.format(APPLICATION_MODULE_GENERATE_CLASS_NAME_SUFFIX, generateClassName, element.getSimpleName().toString()); TypeSpec.Builder thisClass = TypeSpec.classBuilder(className) .addModifiers(PUBLIC) .addSuperinterface(ClassName.get(mIApplicationModule))
.addJavadoc(WARNING_TIPS);
16
2023-10-18 13:52:07+00:00
2k
trpc-group/trpc-java
trpc-limiter/trpc-limiter-sentinel/src/test/java/com/tencent/trpc/limiter/sentinel/config/datasource/ZookeeperDatasourceConfigTest.java
[ { "identifier": "LimiterDataSourceException", "path": "trpc-core/src/main/java/com/tencent/trpc/core/exception/LimiterDataSourceException.java", "snippet": "public class LimiterDataSourceException extends LimiterException {\n\n public LimiterDataSourceException() {\n }\n\n public LimiterDataSourceException(String message) {\n super(message);\n }\n\n public LimiterDataSourceException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public LimiterDataSourceException(Throwable cause) {\n super(cause);\n }\n\n public LimiterDataSourceException(String message, Throwable cause,\n boolean enableSuppression,\n boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n\n}" }, { "identifier": "DatasourceConfigFactoryManger", "path": "trpc-limiter/trpc-limiter-sentinel/src/main/java/com/tencent/trpc/limiter/sentinel/config/datasource/factory/DatasourceConfigFactoryManger.java", "snippet": "public class DatasourceConfigFactoryManger {\n\n /**\n * Used for local caching of flow control rule data source configuration factory classes.\n */\n private static final ConcurrentHashMap<String, DatasourceConfigFactory> FACTORY_MAP = new ConcurrentHashMap<>();\n\n static {\n FACTORY_MAP.put(DatasourceType.LOCAL_FILE.getName(), new LocalFileDatasourceConfigFactory());\n FACTORY_MAP.put(DatasourceType.NACOS.getName(), new NacosDatasourceConfigFactory());\n FACTORY_MAP.put(DatasourceType.REDIS.getName(), new RedisDatasourceConfigFactory());\n FACTORY_MAP.put(DatasourceType.ZOOKEEPER.getName(), new ZookeeperDatasourceConfigFactory());\n }\n\n /**\n * Get the sentinel flow control rule data source configuration factory.\n *\n * @param name flow control rule data source name\n * @return flow control rule data source configuration factory\n */\n public static DatasourceConfigFactory getDatasourceConfigFactory(String name) {\n return FACTORY_MAP.get(name);\n }\n\n}" }, { "identifier": "DatasourceType", "path": "trpc-limiter/trpc-limiter-sentinel/src/main/java/com/tencent/trpc/limiter/sentinel/config/datasource/factory/DatasourceType.java", "snippet": "public enum DatasourceType {\n\n ZOOKEEPER(\"zookeeper\"),\n REDIS(\"redis\"),\n NACOS(\"nacos\"),\n LOCAL_FILE(\"file\");\n\n private String name;\n\n DatasourceType(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n}" } ]
import com.tencent.trpc.core.exception.LimiterDataSourceException; import com.tencent.trpc.limiter.sentinel.config.datasource.factory.DatasourceConfigFactoryManger; import com.tencent.trpc.limiter.sentinel.config.datasource.factory.DatasourceType; import java.io.File; import java.util.HashMap; import java.util.Map; import org.apache.curator.test.TestingServer; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
1,123
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.limiter.sentinel.config.datasource; /** * ZookeeperDatasourceConfig test class */ public class ZookeeperDatasourceConfigTest { private ZookeeperDatasourceConfig zookeeperDatasourceConfig; private TestingServer zkServer; @Before public void setUp() throws Exception { int port = 2183; zkServer = new TestingServer(port, new File("/tmp/sentinel")); zkServer.start(); Map<String, Object> configMap = new HashMap<>(); configMap.put("remote_address", "127.0.0.1:" + port); configMap.put("path", "/tmp/sentinel"); zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger .getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap); } @Test public void testRegister() { zookeeperDatasourceConfig.register(); } @Test public void testValidate1() { Map<String, Object> configMap = new HashMap<>(); configMap.put("path", "/tmp/sentinel"); zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger .getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap); try { zookeeperDatasourceConfig.validate(); } catch (Exception e) {
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.limiter.sentinel.config.datasource; /** * ZookeeperDatasourceConfig test class */ public class ZookeeperDatasourceConfigTest { private ZookeeperDatasourceConfig zookeeperDatasourceConfig; private TestingServer zkServer; @Before public void setUp() throws Exception { int port = 2183; zkServer = new TestingServer(port, new File("/tmp/sentinel")); zkServer.start(); Map<String, Object> configMap = new HashMap<>(); configMap.put("remote_address", "127.0.0.1:" + port); configMap.put("path", "/tmp/sentinel"); zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger .getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap); } @Test public void testRegister() { zookeeperDatasourceConfig.register(); } @Test public void testValidate1() { Map<String, Object> configMap = new HashMap<>(); configMap.put("path", "/tmp/sentinel"); zookeeperDatasourceConfig = (ZookeeperDatasourceConfig) DatasourceConfigFactoryManger .getDatasourceConfigFactory(DatasourceType.ZOOKEEPER.getName()).create(configMap); try { zookeeperDatasourceConfig.validate(); } catch (Exception e) {
Assert.assertTrue(e instanceof LimiterDataSourceException);
0
2023-10-19 10:54:11+00:00
2k
freedom-introvert/YouTubeSendCommentAntiFraud
YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/HistoryCommentListAdapter.java
[ { "identifier": "HistoryComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/HistoryComment.java", "snippet": "public abstract class HistoryComment extends Comment{\r\n public static final String STATE_NORMAL = \"NORMAL\";\r\n public static final String STATE_SHADOW_BAN = \"SHADOW_BAN\";\r\n public static final String STATE_DELETED = \"DELETED\";\r\n\r\n public String state;\r\n public Date sendDate;\r\n @Nullable\r\n public Comment anchorComment;\r\n @Nullable\r\n public Comment repliedComment;\r\n\r\n public HistoryComment(){}\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment) {\r\n this(commentText,commentId,state,sendDate);\r\n this.anchorComment = anchorComment;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment, @Nullable Comment repliedComment) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n this.anchorComment = anchorComment;\r\n this.repliedComment = repliedComment;\r\n }\r\n\r\n public abstract String getCommentSectionSourceId();\r\n\r\n public String getFormatDateFor_yMd(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n\r\n public String getFormatDateFor_yMdHms(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n}\r" }, { "identifier": "VoidDialogInterfaceOnClickListener", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/view/VoidDialogInterfaceOnClickListener.java", "snippet": "public class VoidDialogInterfaceOnClickListener implements DialogInterface.OnClickListener{\r\n @Override\r\n public void onClick(DialogInterface dialog, int which) {\r\n\r\n }\r\n}\r" } ]
import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import java.util.List; import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment; import icu.freedomintrovert.YTSendCommAntiFraud.view.VoidDialogInterfaceOnClickListener;
690
package icu.freedomintrovert.YTSendCommAntiFraud; public abstract class HistoryCommentListAdapter extends RecyclerView.Adapter<HistoryCommentListAdapter.ViewHolder> { Context context;
package icu.freedomintrovert.YTSendCommAntiFraud; public abstract class HistoryCommentListAdapter extends RecyclerView.Adapter<HistoryCommentListAdapter.ViewHolder> { Context context;
List<? extends HistoryComment> commentList;
0
2023-10-15 01:18:28+00:00
2k
New-Barams/This-Year-Ajaja-BE
src/test/java/com/newbarams/ajaja/module/user/application/RenewNicknameServiceTest.java
[ { "identifier": "MockTestSupport", "path": "src/test/java/com/newbarams/ajaja/common/support/MockTestSupport.java", "snippet": "@ExtendWith(MockitoExtension.class)\npublic abstract class MockTestSupport extends MonkeySupport {\n}" }, { "identifier": "ApplyChangePort", "path": "src/main/java/com/newbarams/ajaja/module/user/application/port/out/ApplyChangePort.java", "snippet": "public interface ApplyChangePort {\n\t/**\n\t * Persist user changes on DB\n\t * @param user target to apply changes\n\t */\n\tvoid apply(User user);\n}" }, { "identifier": "Email", "path": "src/main/java/com/newbarams/ajaja/module/user/domain/Email.java", "snippet": "@Getter\npublic class Email extends SelfValidating<Email> {\n\tprivate static final String EMAIL_REGEXP = \"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$\";\n\n\t@Pattern(regexp = EMAIL_REGEXP)\n\tprivate final String signUpEmail;\n\n\t@Pattern(regexp = EMAIL_REGEXP)\n\tprivate final String remindEmail;\n\n\tprivate final boolean verified;\n\n\t@ConstructorProperties({\"signUpEmail\", \"remindEmail\", \"verified\"})\n\tpublic Email(String signUpEmail, String remindEmail, boolean verified) {\n\t\tthis.signUpEmail = signUpEmail;\n\t\tthis.remindEmail = remindEmail;\n\t\tthis.verified = verified;\n\t\tthis.validateSelf();\n\t}\n\n\tpublic Email(String email) {\n\t\tthis(email, email, false);\n\t}\n\n\tvoid validateVerifiable(String email) {\n\t\tif (this.verified && isSameRemindEmail(email)) {\n\t\t\tthrow new AjajaException(UNABLE_TO_VERIFY_EMAIL);\n\t\t}\n\t}\n\n\tEmail verified(String email) {\n\t\treturn isSameRemindEmail(email) ? Email.verify(signUpEmail, remindEmail) : Email.verify(signUpEmail, email);\n\t}\n\n\tprivate static Email verify(String signUpEmail, String remindEmail) {\n\t\treturn new Email(signUpEmail, remindEmail, true);\n\t}\n\n\tprivate boolean isSameRemindEmail(String email) {\n\t\treturn remindEmail.equals(email);\n\t}\n}" }, { "identifier": "Nickname", "path": "src/main/java/com/newbarams/ajaja/module/user/domain/Nickname.java", "snippet": "@Getter\npublic class Nickname extends SelfValidating<Nickname> {\n\t@NotBlank\n\t@Size(max = 20)\n\tprivate final String nickname;\n\n\t@ConstructorProperties(\"nickname\")\n\tpublic Nickname(String nickname) {\n\t\tthis.nickname = nickname;\n\t\tthis.validateSelf();\n\t}\n\n\tpublic static Nickname renew() {\n\t\treturn new Nickname(RandomNicknameGenerator.generate());\n\t}\n}" }, { "identifier": "User", "path": "src/main/java/com/newbarams/ajaja/module/user/domain/User.java", "snippet": "@Getter\n@AllArgsConstructor\npublic class User {\n\tpublic enum ReceiveType {\n\t\tKAKAO, EMAIL, BOTH\n\t}\n\n\tprivate final UserId userId;\n\tprivate Nickname nickname;\n\tprivate Email email;\n\tprivate ReceiveType receiveType;\n\tprivate boolean deleted;\n\n\tpublic static User init(String email, Long oauthId) {\n\t\treturn new User(UserId.from(oauthId), Nickname.renew(), new Email(email), ReceiveType.KAKAO, false);\n\t}\n\n\tpublic void delete() {\n\t\tthis.deleted = true;\n\t}\n\n\tpublic void validateEmail(String requestEmail) {\n\t\temail.validateVerifiable(requestEmail);\n\t}\n\n\tpublic void verified(String validatedEmail) {\n\t\tthis.email = email.verified(validatedEmail);\n\t}\n\n\tpublic void updateNickname() {\n\t\tthis.nickname = Nickname.renew();\n\t}\n\n\tpublic void updateReceive(ReceiveType receiveType) {\n\t\tthis.receiveType = receiveType;\n\t}\n\n\tpublic Long getId() {\n\t\treturn userId.getId();\n\t}\n\n\tpublic Long getOauthId() {\n\t\treturn userId.getOauthId();\n\t}\n\n\tpublic String getEmail() {\n\t\treturn email.getSignUpEmail();\n\t}\n\n\tpublic String getRemindEmail() {\n\t\treturn email.getRemindEmail();\n\t}\n\n\tpublic boolean isVerified() {\n\t\treturn email.isVerified();\n\t}\n}" } ]
import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import com.newbarams.ajaja.common.support.MockTestSupport; import com.newbarams.ajaja.module.user.application.port.out.ApplyChangePort; import com.newbarams.ajaja.module.user.domain.Email; import com.newbarams.ajaja.module.user.domain.Nickname; import com.newbarams.ajaja.module.user.domain.User;
1,264
package com.newbarams.ajaja.module.user.application; class RenewNicknameServiceTest extends MockTestSupport { @InjectMocks private RenewNicknameService renewNicknameService; @Mock private RetrieveUserService retrieveUserService; @Mock private ApplyChangePort applyChangePort; @Test @DisplayName("닉네임 갱신을 요청하면 새로운 이름으로 변경되어야 한다.") void renew_Success_WithNewNickname() { // given User user = sut.giveMeBuilder(User.class)
package com.newbarams.ajaja.module.user.application; class RenewNicknameServiceTest extends MockTestSupport { @InjectMocks private RenewNicknameService renewNicknameService; @Mock private RetrieveUserService retrieveUserService; @Mock private ApplyChangePort applyChangePort; @Test @DisplayName("닉네임 갱신을 요청하면 새로운 이름으로 변경되어야 한다.") void renew_Success_WithNewNickname() { // given User user = sut.giveMeBuilder(User.class)
.set("email", new Email("Ajaja@me.com"))
2
2023-10-23 07:24:17+00:00
2k
eclipse-jgit/jgit
org.eclipse.jgit.test/tst/org/eclipse/jgit/lib/CommitConfigTest.java
[ { "identifier": "ConfigInvalidException", "path": "org.eclipse.jgit/src/org/eclipse/jgit/errors/ConfigInvalidException.java", "snippet": "public class ConfigInvalidException extends Exception {\n\tprivate static final long serialVersionUID = 1L;\n\n\t/**\n\t * Construct an invalid configuration error.\n\t *\n\t * @param message\n\t * why the configuration is invalid.\n\t */\n\tpublic ConfigInvalidException(String message) {\n\t\tsuper(message);\n\t}\n\n\t/**\n\t * Construct an invalid configuration error.\n\t *\n\t * @param message\n\t * why the configuration is invalid.\n\t * @param cause\n\t * root cause of the error.\n\t */\n\tpublic ConfigInvalidException(String message, Throwable cause) {\n\t\tsuper(message, cause);\n\t}\n}" }, { "identifier": "CleanupMode", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/CommitConfig.java", "snippet": "public enum CleanupMode implements ConfigEnum {\n\n\t/**\n\t * {@link #WHITESPACE}, additionally remove comment lines.\n\t */\n\tSTRIP,\n\n\t/**\n\t * Remove trailing whitespace and leading and trailing empty lines;\n\t * collapse multiple empty lines to a single one.\n\t */\n\tWHITESPACE,\n\n\t/**\n\t * Make no changes.\n\t */\n\tVERBATIM,\n\n\t/**\n\t * Omit everything from the first \"scissor\" line on, then apply\n\t * {@link #WHITESPACE}.\n\t */\n\tSCISSORS,\n\n\t/**\n\t * Use {@link #STRIP} for user-edited messages, otherwise\n\t * {@link #WHITESPACE}, unless overridden by a git config setting other\n\t * than DEFAULT.\n\t */\n\tDEFAULT;\n\n\t@Override\n\tpublic String toConfigValue() {\n\t\treturn name().toLowerCase(Locale.ROOT);\n\t}\n\n\t@Override\n\tpublic boolean matchConfigValue(String in) {\n\t\treturn toConfigValue().equals(in);\n\t}\n}" } ]
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.CommitConfig.CleanupMode; import org.junit.Test;
669
/* * Copyright (C) 2022, Thomas Wolf <thomas.wolf@paranor.ch> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.lib; public class CommitConfigTest { @Test public void testDefaults() throws Exception { CommitConfig cfg = parse("");
/* * Copyright (C) 2022, Thomas Wolf <thomas.wolf@paranor.ch> and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.lib; public class CommitConfigTest { @Test public void testDefaults() throws Exception { CommitConfig cfg = parse("");
assertEquals("Unexpected clean-up mode", CleanupMode.DEFAULT,
1
2023-10-20 15:09:17+00:00
2k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/client/renderer/CatfishRenderer.java
[ { "identifier": "CatfishModel", "path": "common/src/main/java/com/starfish_studios/naturalist/client/model/CatfishModel.java", "snippet": "@Environment(EnvType.CLIENT)\npublic class CatfishModel extends AnimatedGeoModel<Catfish> {\n @Override\n public ResourceLocation getModelResource(Catfish catfish) {\n return new ResourceLocation(Naturalist.MOD_ID, \"geo/catfish.geo.json\");\n }\n\n @Override\n public ResourceLocation getTextureResource(Catfish catfish) {\n return new ResourceLocation(Naturalist.MOD_ID, \"textures/entity/catfish.png\");\n }\n\n @Override\n public ResourceLocation getAnimationResource(Catfish catfish) {\n return new ResourceLocation(Naturalist.MOD_ID, \"animations/catfish.animation.json\");\n }\n}" }, { "identifier": "Catfish", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/Catfish.java", "snippet": "public class Catfish extends AbstractFish implements IAnimatable {\n private static final EntityDataAccessor<Integer> KILL_COOLDOWN = SynchedEntityData.defineId(Catfish.class, EntityDataSerializers.INT);\n\n private final AnimationFactory factory = GeckoLibUtil.createFactory(this);\n\n public Catfish(EntityType<? extends AbstractFish> entityType, Level level) {\n super(entityType, level);\n }\n\n public static AttributeSupplier.Builder createAttributes() {\n return Mob.createMobAttributes().add(Attributes.MAX_HEALTH, 6.0).add(Attributes.ATTACK_DAMAGE, 1.0D);\n }\n\n @Override\n protected void registerGoals() {\n super.registerGoals();\n this.goalSelector.addGoal(1, new MeleeAttackGoal(this, 1.0D, false)\n {\n public boolean canUse() {\n return super.canUse() && !isBaby() && getKillCooldown() == 0;\n }\n\n public void stop() {\n super.stop();\n setKillCooldown(2400);\n }\n });\n this.targetSelector.addGoal(1, new NearestAttackableTargetGoal<>(this, WaterAnimal.class, 10, true, false, (entity) -> entity.getType().is(NaturalistTags.EntityTypes.CATFISH_HOSTILES)));\n }\n\n @Override\n protected void defineSynchedData() {\n super.defineSynchedData();\n this.entityData.define(KILL_COOLDOWN, 0);\n }\n\n @Override\n public void addAdditionalSaveData(CompoundTag compound) {\n super.addAdditionalSaveData(compound);\n compound.putInt(\"KillCooldown\", this.getKillCooldown());\n }\n\n @Override\n public void readAdditionalSaveData(CompoundTag compound) {\n super.readAdditionalSaveData(compound);\n this.setKillCooldown(compound.getInt(\"KillCooldown\"));\n }\n\n public void setKillCooldown(int ticks) {\n this.entityData.set(KILL_COOLDOWN, ticks);\n }\n\n public int getKillCooldown() {\n return this.entityData.get(KILL_COOLDOWN);\n }\n\n @Override\n protected SoundEvent getFlopSound() {\n return NaturalistSoundEvents.CATFISH_FLOP.get();\n }\n @Override\n protected SoundEvent getAmbientSound() {\n return SoundEvents.SALMON_AMBIENT;\n }\n\n @Override\n protected SoundEvent getDeathSound() {\n return SoundEvents.SALMON_DEATH;\n }\n\n @Override\n protected SoundEvent getHurtSound(DamageSource damageSource) {\n return SoundEvents.SALMON_HURT;\n }\n\n @Override\n public ItemStack getBucketItemStack() {\n return new ItemStack(NaturalistItems.CATFISH_BUCKET.get());\n }\n\n private <E extends IAnimatable> PlayState predicate(AnimationEvent<E> event) {\n if (!this.isInWater()) {\n event.getController().setAnimation(new AnimationBuilder().loop(\"catfish.flop\"));\n } else {\n event.getController().setAnimation(new AnimationBuilder().loop(\"catfish.swim\"));\n }\n return PlayState.CONTINUE;\n }\n\n @Override\n public void registerControllers(AnimationData data) {\n data.setResetSpeedInTicks(5);\n data.addAnimationController(new AnimationController<>(this, \"controller\", 5, this::predicate));\n }\n\n @Override\n public AnimationFactory getFactory() {\n return factory;\n }\n}" } ]
import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import com.starfish_studios.naturalist.client.model.CatfishModel; import com.starfish_studios.naturalist.common.entity.Catfish; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.entity.EntityRendererProvider; import net.minecraft.resources.ResourceLocation; import org.jetbrains.annotations.Nullable; import software.bernie.geckolib3.renderers.geo.GeoEntityRenderer;
1,244
package com.starfish_studios.naturalist.client.renderer; @Environment(EnvType.CLIENT) public class CatfishRenderer extends GeoEntityRenderer<Catfish> { public CatfishRenderer(EntityRendererProvider.Context renderManager) {
package com.starfish_studios.naturalist.client.renderer; @Environment(EnvType.CLIENT) public class CatfishRenderer extends GeoEntityRenderer<Catfish> { public CatfishRenderer(EntityRendererProvider.Context renderManager) {
super(renderManager, new CatfishModel());
0
2023-10-16 21:54:32+00:00
2k
instana/otel-dc
host/src/main/java/com/instana/dc/host/impl/HostDcRegistry.java
[ { "identifier": "AbstractHostDc", "path": "host/src/main/java/com/instana/dc/host/AbstractHostDc.java", "snippet": "public abstract class AbstractHostDc extends AbstractDc implements IDc {\n private static final Logger logger = Logger.getLogger(AbstractHostDc.class.getName());\n\n private final String otelBackendUrl;\n private final boolean otelUsingHttp;\n private final int pollInterval;\n private final int callbackInterval;\n private final String serviceName;\n public final static String INSTRUMENTATION_SCOPE_PREFIX = \"otelcol/hostmetricsreceiver/\";\n\n private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();\n\n public AbstractHostDc(Map<String, String> properties, String hostSystem) {\n super(new HostRawMetricRegistry().getMap());\n\n String pollInt = properties.get(POLLING_INTERVAL);\n pollInterval = pollInt == null ? DEFAULT_POLL_INTERVAL : Integer.parseInt(pollInt);\n String callbackInt = properties.get(CALLBACK_INTERVAL);\n callbackInterval = callbackInt == null ? DEFAULT_CALLBACK_INTERVAL : Integer.parseInt(callbackInt);\n otelBackendUrl = properties.get(OTEL_BACKEND_URL);\n otelUsingHttp = \"true\".equalsIgnoreCase(properties.get(OTEL_BACKEND_USING_HTTP));\n String svcName = properties.get(OTEL_SERVICE_NAME);\n serviceName = svcName == null ? hostSystem : svcName;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n @Override\n public void initDC() throws Exception {\n Resource resource = getResourceAttributes();\n SdkMeterProvider sdkMeterProvider = this.getDefaultSdkMeterProvider(resource, otelBackendUrl, callbackInterval, otelUsingHttp, 10);\n OpenTelemetry openTelemetry = OpenTelemetrySdk.builder().setMeterProvider(sdkMeterProvider).build();\n initMeters(openTelemetry);\n registerMetrics();\n }\n\n private void initMeter(OpenTelemetry openTelemetry, String name) {\n Meter meter1 = openTelemetry.meterBuilder(INSTRUMENTATION_SCOPE_PREFIX + name).setInstrumentationVersion(\"1.0.0\").build();\n getMeters().put(name, meter1);\n }\n\n /* The purpose to overwrite this method is to comply with the \"hostmetrics\" receiver of\n * OpenTelemetry Contrib Collector.\n **/\n @Override\n public void initMeters(OpenTelemetry openTelemetry) {\n initMeter(openTelemetry, HostDcUtil.MeterName.CPU);\n initMeter(openTelemetry, HostDcUtil.MeterName.MEMORY);\n initMeter(openTelemetry, HostDcUtil.MeterName.NETWORK);\n initMeter(openTelemetry, HostDcUtil.MeterName.LOAD);\n initMeter(openTelemetry, HostDcUtil.MeterName.DISK);\n initMeter(openTelemetry, HostDcUtil.MeterName.FILESYSTEM);\n initMeter(openTelemetry, HostDcUtil.MeterName.PROCESSES);\n initMeter(openTelemetry, HostDcUtil.MeterName.PAGING);\n }\n\n\n @Override\n public void start() {\n exec.scheduleWithFixedDelay(this::collectData, 1, pollInterval, TimeUnit.SECONDS);\n }\n}" }, { "identifier": "DcException", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcException.java", "snippet": "public class DcException extends Exception {\n public DcException(String message) {\n super(message);\n }\n}" } ]
import java.util.HashMap; import java.util.Map; import com.instana.dc.host.AbstractHostDc; import com.instana.dc.DcException;
934
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class HostDcRegistry { /* Add all DataCollector implementations here: **/ private final Map<String, Class<? extends AbstractHostDc>> map = new HashMap<String, Class<? extends AbstractHostDc>>() {{ put("SIMP_HOST", SimpHostDc.class); }};
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.host.impl; public class HostDcRegistry { /* Add all DataCollector implementations here: **/ private final Map<String, Class<? extends AbstractHostDc>> map = new HashMap<String, Class<? extends AbstractHostDc>>() {{ put("SIMP_HOST", SimpHostDc.class); }};
public Class<? extends AbstractHostDc> findHostDc(String hostSystem) throws DcException {
1
2023-10-23 01:16:38+00:00
2k
quarkiverse/quarkus-antivirus
integration-tests/src/main/java/io/quarkiverse/antivirus/it/AntivirusResource.java
[ { "identifier": "Antivirus", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/Antivirus.java", "snippet": "@ApplicationScoped\n@JBossLog\npublic class Antivirus {\n\n @Inject\n private Instance<AntivirusEngine> engineInstances;\n\n /**\n * Perform virus scan and throw exception if a virus has been detected.\n *\n * @param filename the name of the file to scan\n * @param inputStream the inputStream containing the file contents\n * @return the List of all {@link AntivirusScanResult} from all engines\n */\n @SneakyThrows\n public List<AntivirusScanResult> scan(final String filename, final InputStream inputStream) {\n final List<AntivirusScanResult> results = new ArrayList<>();\n for (AntivirusEngine plugin : engineInstances) {\n if (plugin.isEnabled()) {\n final AntivirusScanResult result = plugin.scan(filename, inputStream);\n results.add(result);\n // reset the stream for the next scan\n inputStream.reset();\n }\n }\n\n // let user know nothing happened meaning they had all engines disabled\n if (results.isEmpty()) {\n log.warn(\"Antivirus extension found NO scanning engines to execute!\");\n }\n return results;\n }\n}" }, { "identifier": "AntivirusException", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/AntivirusException.java", "snippet": "public class AntivirusException extends RuntimeException {\n\n private final String fileName;\n\n public AntivirusException(final String fileName, final String message) {\n super(message);\n this.fileName = fileName;\n }\n\n public AntivirusException(final String fileName, final String message, final Throwable cause) {\n super(message, cause);\n this.fileName = fileName;\n }\n\n public String getFileName() {\n return fileName;\n }\n\n}" }, { "identifier": "AntivirusScanResult", "path": "runtime/src/main/java/io/quarkiverse/antivirus/runtime/AntivirusScanResult.java", "snippet": "@RegisterForReflection\n@Data\n@AllArgsConstructor\n@Builder\n@JBossLog\npublic class AntivirusScanResult {\n\n /**\n * Status code mirrors HTTP status codes for signaling what occurred so the downstream system can act. 200 = OK.\n */\n private int status;\n\n /**\n * Scan engine that produced this result.\n */\n private String engine;\n\n /**\n * Name of the file that was scanned.\n */\n private String fileName;\n\n /**\n * Human-readable message explaining what happened.\n */\n private String message;\n\n /**\n * Payload from the engine, for example if its an HTTP service it might be the JSON response raw.\n */\n private String payload;\n\n}" } ]
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.validation.Valid; import jakarta.ws.rs.BadRequestException; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import org.apache.commons.io.IOUtils; import org.jboss.resteasy.annotations.providers.multipart.MultipartForm; import io.quarkiverse.antivirus.runtime.Antivirus; import io.quarkiverse.antivirus.runtime.AntivirusException; import io.quarkiverse.antivirus.runtime.AntivirusScanResult;
958
package io.quarkiverse.antivirus.it; @Path("/antivirus") @ApplicationScoped public class AntivirusResource { @Inject Antivirus antivirus; @PUT @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) @Path("/upload") public List<AntivirusScanResult> upload(@MultipartForm @Valid final UploadRequest fileUploadRequest) { final String fileName = fileUploadRequest.getFileName(); final InputStream data = fileUploadRequest.getData(); try { // copy the stream to make it resettable final ByteArrayInputStream inputStream = new ByteArrayInputStream( IOUtils.toBufferedInputStream(data).readAllBytes()); // scan the file and check the results return antivirus.scan(fileName, inputStream);
package io.quarkiverse.antivirus.it; @Path("/antivirus") @ApplicationScoped public class AntivirusResource { @Inject Antivirus antivirus; @PUT @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) @Path("/upload") public List<AntivirusScanResult> upload(@MultipartForm @Valid final UploadRequest fileUploadRequest) { final String fileName = fileUploadRequest.getFileName(); final InputStream data = fileUploadRequest.getData(); try { // copy the stream to make it resettable final ByteArrayInputStream inputStream = new ByteArrayInputStream( IOUtils.toBufferedInputStream(data).readAllBytes()); // scan the file and check the results return antivirus.scan(fileName, inputStream);
} catch (AntivirusException | IOException e) {
1
2023-10-22 22:33:05+00:00
2k
Team3256/FRC_MockSeason_2023
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "OperatorConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public static class OperatorConstants {\n public static final int kDriverControllerPort = 0;\n}" }, { "identifier": "Autos", "path": "src/main/java/frc/robot/commands/Autos.java", "snippet": "public final class Autos {\n /** Example static factory for an autonomous command. */\n public static CommandBase exampleAuto(ExampleSubsystem subsystem) {\n return Commands.sequence(subsystem.exampleMethodCommand(), new ExampleCommand(subsystem));\n }\n\n private Autos() {\n throw new UnsupportedOperationException(\"This is a utility class!\");\n }\n}" }, { "identifier": "ExampleCommand", "path": "src/main/java/frc/robot/commands/ExampleCommand.java", "snippet": "public class ExampleCommand extends CommandBase {\n @SuppressWarnings({\"PMD.UnusedPrivateField\", \"PMD.SingularField\"})\n private final ExampleSubsystem m_subsystem;\n\n /**\n * Creates a new ExampleCommand.\n *\n * @param subsystem The subsystem used by this command.\n */\n public ExampleCommand(ExampleSubsystem subsystem) {\n m_subsystem = subsystem;\n // Use addRequirements() here to declare subsystem dependencies.\n addRequirements(subsystem);\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {}\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {}\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {}\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n return false;\n }\n}" }, { "identifier": "ExampleSubsystem", "path": "src/main/java/frc/robot/subsystems/ExampleSubsystem.java", "snippet": "public class ExampleSubsystem extends SubsystemBase {\n /** Creates a new ExampleSubsystem. */\n public ExampleSubsystem() {}\n\n /**\n * Example command factory method.\n *\n * @return a command\n */\n public CommandBase exampleMethodCommand() {\n // Inline construction of command goes here.\n // Subsystem::RunOnce implicitly requires `this` subsystem.\n return runOnce(\n () -> {\n /* one-time action goes here */\n });\n }\n\n /**\n * An example method querying a boolean state of the subsystem (for example, a digital sensor).\n *\n * @return value of some boolean subsystem state, such as a digital sensor.\n */\n public boolean exampleCondition() {\n // Query some boolean state, such as a digital sensor.\n return false;\n }\n\n @Override\n public void periodic() {\n // This method will be called once per scheduler run\n }\n\n @Override\n public void simulationPeriodic() {\n // This method will be called once per scheduler run during simulation\n }\n}" } ]
import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.robot.Constants.OperatorConstants; import frc.robot.commands.Autos; import frc.robot.commands.ExampleCommand; import frc.robot.subsystems.ExampleSubsystem;
1,167
// Copyright (c) 2023 FRC 3256 // https://github.com/Team3256 // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file at // the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { // The robot's subsystems and commands are defined here... private final ExampleSubsystem m_exampleSubsystem = new ExampleSubsystem(); // Replace with CommandPS4Controller or CommandJoystick if needed private final CommandXboxController m_driverController = new CommandXboxController(OperatorConstants.kDriverControllerPort); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { // Configure the trigger bindings configureBindings(); } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { // Schedule `ExampleCommand` when `exampleCondition` changes to `true` new Trigger(m_exampleSubsystem::exampleCondition)
// Copyright (c) 2023 FRC 3256 // https://github.com/Team3256 // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file at // the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { // The robot's subsystems and commands are defined here... private final ExampleSubsystem m_exampleSubsystem = new ExampleSubsystem(); // Replace with CommandPS4Controller or CommandJoystick if needed private final CommandXboxController m_driverController = new CommandXboxController(OperatorConstants.kDriverControllerPort); /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { // Configure the trigger bindings configureBindings(); } /** * Use this method to define your trigger->command mappings. Triggers can be created via the * {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary * predicate, or via the named factories in {@link * edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link * CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller * PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight * joysticks}. */ private void configureBindings() { // Schedule `ExampleCommand` when `exampleCondition` changes to `true` new Trigger(m_exampleSubsystem::exampleCondition)
.onTrue(new ExampleCommand(m_exampleSubsystem));
2
2023-10-23 21:29:35+00:00
2k
Matheus-FSantos/4log-products
src/java/controller/ProductController.java
[ { "identifier": "ProductService", "path": "WebApplication1/src/java/model/service/ProductService.java", "snippet": "public class ProductService {\n\n private final ProductRepository productRepository;\n \n public ProductService() {\n this.productRepository = new ProductRepository();\n }\n \n public List<Product> findAll() {\n return this.productRepository.findAll();\n }\n \n public void save(HttpServletRequest request) throws Exception {\n String productName = request.getParameter(\"name-input\");\n String productBrand = request.getParameter(\"brand-input\");\n Double productPrice = Double.valueOf(request.getParameter(\"price-input\"));\n \n Product newProduct = new Product(UUID.randomUUID().toString(), productName, productBrand, productPrice, new Date());\n \n this.productRepository.save(newProduct);\n }\n \n}" }, { "identifier": "Product", "path": "WebApplication1/src/java/model/domain/Product.java", "snippet": "@Entity\n@Table(name = \"product\")\n@NamedQueries({\n @NamedQuery(name = \"Product.findAll\", query = \"SELECT p FROM Product p\"),\n @NamedQuery(name = \"Product.findByLgCode\", query = \"SELECT p FROM Product p WHERE p.lgCode = :lgCode\"),\n @NamedQuery(name = \"Product.findByLgName\", query = \"SELECT p FROM Product p WHERE p.lgName = :lgName\"),\n @NamedQuery(name = \"Product.findByLgBrand\", query = \"SELECT p FROM Product p WHERE p.lgBrand = :lgBrand\"),\n @NamedQuery(name = \"Product.findByLgPrice\", query = \"SELECT p FROM Product p WHERE p.lgPrice = :lgPrice\"),\n @NamedQuery(name = \"Product.findByLgcreatedAt\", query = \"SELECT p FROM Product p WHERE p.lgcreatedAt = :lgcreatedAt\")})\npublic class Product implements Serializable {\n\n private static final long serialVersionUID = 1L;\n @Id\n @Basic(optional = false)\n @Column(name = \"lg_code\")\n private String lgCode;\n @Basic(optional = false)\n @Column(name = \"lg_name\")\n private String lgName;\n @Basic(optional = false)\n @Column(name = \"lg_brand\")\n private String lgBrand;\n @Basic(optional = false)\n @Column(name = \"lg_price\")\n private double lgPrice;\n @Basic(optional = false)\n @Column(name = \"lg_createdAt\")\n @Temporal(TemporalType.TIMESTAMP)\n private Date lgcreatedAt;\n\n public Product() {\n }\n\n public Product(String lgCode) {\n this.lgCode = lgCode;\n }\n\n public Product(String lgCode, String lgName, String lgBrand, double lgPrice, Date lgcreatedAt) {\n this.lgCode = lgCode;\n this.lgName = lgName;\n this.lgBrand = lgBrand;\n this.lgPrice = lgPrice;\n this.lgcreatedAt = lgcreatedAt;\n }\n\n public String getLgCode() {\n return lgCode;\n }\n\n public void setLgCode(String lgCode) {\n this.lgCode = lgCode;\n }\n\n public String getLgName() {\n return lgName;\n }\n\n public void setLgName(String lgName) {\n this.lgName = lgName;\n }\n\n public String getLgBrand() {\n return lgBrand;\n }\n\n public void setLgBrand(String lgBrand) {\n this.lgBrand = lgBrand;\n }\n\n public double getLgPrice() {\n return lgPrice;\n }\n\n public void setLgPrice(double lgPrice) {\n this.lgPrice = lgPrice;\n }\n\n public Date getLgcreatedAt() {\n return lgcreatedAt;\n }\n\n public void setLgcreatedAt(Date lgcreatedAt) {\n this.lgcreatedAt = lgcreatedAt;\n }\n\n @Override\n public int hashCode() {\n int hash = 0;\n hash += (lgCode != null ? lgCode.hashCode() : 0);\n return hash;\n }\n\n @Override\n public boolean equals(Object object) {\n // TODO: Warning - this method won't work in the case the id fields are not set\n if (!(object instanceof Product)) {\n return false;\n }\n Product other = (Product) object;\n if ((this.lgCode == null && other.lgCode != null) || (this.lgCode != null && !this.lgCode.equals(other.lgCode))) {\n return false;\n }\n return true;\n }\n\n @Override\n public String toString() {\n return \"Product{\" + \"lgCode=\" + lgCode + \", lgName=\" + lgName + \", lgBrand=\" + lgBrand + \", lgPrice=\" + lgPrice + \", lgcreatedAt=\" + lgcreatedAt + '}';\n } \n \n}" } ]
import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.service.ProductService; import model.domain.Product;
1,221
package controller; @WebServlet(name = "ProductsController", urlPatterns = {"/products"}) public class ProductController extends HttpServlet {
package controller; @WebServlet(name = "ProductsController", urlPatterns = {"/products"}) public class ProductController extends HttpServlet {
private final ProductService productService = new ProductService();
0
2023-10-19 17:09:59+00:00
2k
robaho/httpserver
src/test/java_default/HttpExchange/AutoCloseableHttpExchange.java
[ { "identifier": "URIBuilder", "path": "src/test/java/jdk/test/lib/net/URIBuilder.java", "snippet": "public class URIBuilder {\n\n public static URIBuilder newBuilder() {\n return new URIBuilder();\n }\n\n private String scheme;\n private String userInfo;\n private String host;\n private int port;\n private String path;\n private String query;\n private String fragment;\n\n private URIBuilder() {}\n\n public URIBuilder scheme(String scheme) {\n this.scheme = scheme;\n return this;\n }\n\n public URIBuilder userInfo(String userInfo) {\n this.userInfo = userInfo;\n return this;\n }\n\n public URIBuilder host(String host) {\n this.host = host;\n return this;\n }\n\n public URIBuilder host(InetAddress address) {\n String hostaddr = address.isAnyLocalAddress()\n ? \"localhost\" : address.getHostAddress();\n return host(hostaddr);\n }\n\n public URIBuilder loopback() {\n return host(InetAddress.getLoopbackAddress().getHostAddress());\n }\n\n public URIBuilder port(int port) {\n this.port = port;\n return this;\n }\n\n public URIBuilder path(String path) {\n this.path = path;\n return this;\n }\n\n public URIBuilder query(String query) {\n this.query = query;\n return this;\n }\n\n public URIBuilder fragment(String fragment) {\n this.fragment = fragment;\n return this;\n }\n\n public URI build() throws URISyntaxException {\n return new URI(scheme, userInfo, host, port, path, query, fragment);\n }\n\n public URI buildUnchecked() {\n try {\n return build();\n } catch (URISyntaxException e) {\n throw new IllegalArgumentException(e);\n }\n }\n\n public URL toURL() throws URISyntaxException, MalformedURLException {\n return build().toURL();\n }\n\n public URL toURLUnchecked() {\n try {\n return toURL();\n } catch (URISyntaxException | MalformedURLException e) {\n throw new IllegalArgumentException(e);\n }\n }\n}" }, { "identifier": "HttpExchangeAccess", "path": "src/test/java_default/HttpExchange/robaho/net/httpserver/HttpExchangeAccess.java", "snippet": "public class HttpExchangeAccess {\n public static boolean isClosed(com.sun.net.httpserver.HttpExchange exch) {\n synchronized (exch) {\n return ((HttpExchangeImpl) exch).getExchangeImpl().closed;\n }\n }\n}" } ]
import jdk.test.lib.net.URIBuilder; import robaho.net.httpserver.HttpExchangeAccess; import com.sun.net.httpserver.*; import java.io.IOException; import java.io.InputStream; import java.net.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean;
1,211
/* * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * @test * @bug 8203036 * @library /test/lib * @modules jdk.httpserver/sun.net.httpserver * @build jdk.httpserver/sun.net.httpserver.HttpExchangeAccess * AutoCloseableHttpExchange * @run main/othervm AutoCloseableHttpExchange * @summary Ensure that HttpExchange closes correctly when utilising the * AutoCloseable interface e.g. both request InputStream and response * OutputStream * are closed, if not already. */ public class AutoCloseableHttpExchange { static HttpServer testHttpServer; static AtomicBoolean exchangeCloseFail = new AtomicBoolean(false); static class Handler implements HttpHandler { private CountDownLatch latch; Handler(CountDownLatch latch) { this.latch = latch; } public void handle(HttpExchange t) throws IOException { InputStream is = t.getRequestBody(); try (HttpExchange e = t) { while (is.read() != -1) ; t.sendResponseHeaders(200, -1); } if (!HttpExchangeAccess.isClosed(t)) { exchangeCloseFail.set(true); } latch.countDown(); } } static void connectAndCheck(String realm) throws Exception {
/* * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * @test * @bug 8203036 * @library /test/lib * @modules jdk.httpserver/sun.net.httpserver * @build jdk.httpserver/sun.net.httpserver.HttpExchangeAccess * AutoCloseableHttpExchange * @run main/othervm AutoCloseableHttpExchange * @summary Ensure that HttpExchange closes correctly when utilising the * AutoCloseable interface e.g. both request InputStream and response * OutputStream * are closed, if not already. */ public class AutoCloseableHttpExchange { static HttpServer testHttpServer; static AtomicBoolean exchangeCloseFail = new AtomicBoolean(false); static class Handler implements HttpHandler { private CountDownLatch latch; Handler(CountDownLatch latch) { this.latch = latch; } public void handle(HttpExchange t) throws IOException { InputStream is = t.getRequestBody(); try (HttpExchange e = t) { while (is.read() != -1) ; t.sendResponseHeaders(200, -1); } if (!HttpExchangeAccess.isClosed(t)) { exchangeCloseFail.set(true); } latch.countDown(); } } static void connectAndCheck(String realm) throws Exception {
URL url = URIBuilder.newBuilder()
0
2023-10-15 15:56:58+00:00
2k
aabssmc/Skuishy
src/main/java/lol/aabss/skuishy/elements/expressions/skins/ExprPlayerSkin.java
[ { "identifier": "SkinWrapper", "path": "src/main/java/lol/aabss/skuishy/other/skins/SkinWrapper.java", "snippet": "public abstract class SkinWrapper {\n\n public static HashMap<Player, String> skinname = new HashMap<>();\n\n public static BufferedImage get(Player player, @Nullable Number size, boolean lay) throws Exception {\n BufferedImage textureImage = imgTexture(player);\n BufferedImage subImage = textureImage.getSubimage(8,8,8,8);\n assert size != null;\n BufferedImage face = new BufferedImage(size.intValue(), size.intValue(), subImage.getType());\n Graphics2D faceTmp = face.createGraphics();\n faceTmp.drawImage(textureImage, 0, 0, size.intValue(), size.intValue(), null);\n faceTmp.dispose();\n if (lay) {\n try {\n BufferedImage outerLayer = textureImage.getSubimage(40, 8, 8, 8);\n faceTmp.drawImage(outerLayer, 0, 0, size.intValue(), size.intValue(), null);\n faceTmp.dispose();\n } catch (Exception e) {\n throw new IllegalStateException(e);\n }\n }\n return face;\n }\n\n public static ProfileProperty getProfileProperties(Player p) {\n PlayerProfile playerProfile = p.getPlayerProfile();\n ProfileProperty prop = null;\n for (ProfileProperty property : playerProfile.getProperties()) {\n if (property.getName().equals(\"textures\")) {\n prop = property;\n break;\n }\n }\n return prop;\n }\n\n public static BufferedImage imgTexture(Player player) {\n try {\n URL url = player.getPlayerProfile().getTextures().getSkin();\n assert url != null;\n return ImageIO.read(url);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void setSkin(Player player, String skin){\n if (player.getName().equals(skin)){\n PlayerProfile e = player.getPlayerProfile();\n e.getTextures().clear();\n PlayerTextures t = e.getTextures();\n t.clear();\n e.setTextures(t);\n player.setPlayerProfile(e);\n skinname.remove(player, skin);\n }\n PlayerProfile newprofile = Bukkit.createProfile(skin);\n newprofile.complete();\n PlayerProfile profile = player.getPlayerProfile();\n profile.setProperties(newprofile.getProperties());\n player.setPlayerProfile(profile);\n if (!player.getName().equals(skin)){\n skinname.put(player, skin);\n }\n }\n\n}" }, { "identifier": "skinname", "path": "src/main/java/lol/aabss/skuishy/other/skins/SkinWrapper.java", "snippet": "public static HashMap<Player, String> skinname = new HashMap<>();" } ]
import ch.njol.skript.classes.Changer; import ch.njol.skript.doc.Description; import ch.njol.skript.doc.Examples; import ch.njol.skript.doc.Name; import ch.njol.skript.doc.Since; import ch.njol.skript.expressions.base.PropertyExpression; import ch.njol.skript.lang.Expression; import ch.njol.skript.lang.SkriptParser.ParseResult; import ch.njol.skript.registrations.Classes; import ch.njol.util.Kleenean; import ch.njol.util.coll.CollectionUtils; import lol.aabss.skuishy.other.skins.SkinWrapper; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.jetbrains.annotations.NotNull; import static lol.aabss.skuishy.other.skins.SkinWrapper.skinname;
1,048
package lol.aabss.skuishy.elements.expressions.skins; @Name("Skins - Player Skin") @Description("Get/Sets a player's skin") @Examples({ "set skin of player to \"Dinnerbone\"\n#Also sets the cape" }) @Since("1.4") public class ExprPlayerSkin extends PropertyExpression<Player, String> { static { register(ExprPlayerSkin.class, String.class, "[minecraft] skin", "players" ); } private Expression<Player> player; @Override protected String @NotNull [] get(@NotNull Event event, Player @NotNull [] source) { String name = skinname.get(source[0]) == null ? source[0].getName() : skinname.get(source[0]); return new String[]{name}; } @Override public void change(@NotNull Event event, Object @NotNull [] delta, Changer.@NotNull ChangeMode mode){ Player p = player.getSingle(event); if (mode == Changer.ChangeMode.SET) { assert p != null;
package lol.aabss.skuishy.elements.expressions.skins; @Name("Skins - Player Skin") @Description("Get/Sets a player's skin") @Examples({ "set skin of player to \"Dinnerbone\"\n#Also sets the cape" }) @Since("1.4") public class ExprPlayerSkin extends PropertyExpression<Player, String> { static { register(ExprPlayerSkin.class, String.class, "[minecraft] skin", "players" ); } private Expression<Player> player; @Override protected String @NotNull [] get(@NotNull Event event, Player @NotNull [] source) { String name = skinname.get(source[0]) == null ? source[0].getName() : skinname.get(source[0]); return new String[]{name}; } @Override public void change(@NotNull Event event, Object @NotNull [] delta, Changer.@NotNull ChangeMode mode){ Player p = player.getSingle(event); if (mode == Changer.ChangeMode.SET) { assert p != null;
SkinWrapper.setSkin(p, (String) delta[0]);
0
2023-10-24 23:48:14+00:00
2k
wevez/YT4J
src/Main.java
[ { "identifier": "YTDLOption", "path": "src/tech/tenamen/yt4j/YTDLOption.java", "snippet": "public class YTDLOption {\n\n private final YTDLType TYPE;\n private final YTDLQuality QUALITY;\n\n public YTDLOption(YTDLType TYPE, YTDLQuality QUALITY) {\n this.TYPE = TYPE;\n this.QUALITY = QUALITY;\n }\n\n public YTDLQuality getQuality() {\n return QUALITY;\n }\n\n public YTDLType getType() {\n return TYPE;\n }\n\n @Override\n public String toString() {\n return \"YTDownloadType{\" +\n \"TYPE=\" + TYPE +\n \", QUALITY=\" + QUALITY +\n '}';\n }\n\n public enum YTDLType {\n\n VIDEO_MP4,\n VIDEO_WEBM,\n AUDIO_WEBM,\n AUDIO_MP4;\n }\n\n public enum YTDLQuality {\n\n HIGHEST,\n LOWEST;\n }\n}" }, { "identifier": "YTSearchFilterOption", "path": "src/tech/tenamen/yt4j/YTSearchFilterOption.java", "snippet": "public enum YTSearchFilterOption {\n\n NONE(\"\"),\n VIDEO(\"EgIQAQ%3D%3D\");\n\n final String TAG;\n\n private YTSearchFilterOption(final String TAG) {\n this.TAG = TAG;\n }\n}" }, { "identifier": "YTVideo", "path": "src/tech/tenamen/yt4j/data/YTVideo.java", "snippet": "public class YTVideo extends YTData {\n\n private final String TITLE;\n private final String VIDEO_ID;\n private final YTPublisher PUBLISHER;\n private final String THUMBNAIL_URL;\n private final int LENGTH_SEC;\n private final int VIEW_COUNT;\n\n public YTVideo(\n final String TITLE,\n final YTPublisher PUBLISHER,\n final String VIDEO_ID,\n final String THUMBNAIL_URL,\n final int LENGTH_SEC,\n final int VIEW_COUNT\n ) {\n this.TITLE = TITLE;\n this.VIDEO_ID = VIDEO_ID;\n this.PUBLISHER = PUBLISHER;\n this.THUMBNAIL_URL = THUMBNAIL_URL;\n this.LENGTH_SEC = LENGTH_SEC;\n this.VIEW_COUNT = VIEW_COUNT;\n }\n\n public final String getTitle() {\n return this.TITLE;\n }\n\n public final String getVideoId() {\n return this.VIDEO_ID;\n }\n\n public final YTPublisher getPublisher() {\n return this.PUBLISHER;\n }\n\n public final String getThumbnailURL() {\n return this.THUMBNAIL_URL;\n }\n\n public final int getLengthSec() {\n return this.LENGTH_SEC;\n }\n\n public final int getViewCount() {\n return this.VIEW_COUNT;\n }\n\n @Override\n public String toString() {\n return String.format(\n \"title: %s, videoId: %s, publisher: %s, thumbnail URL: %s view count: %d, length sec: %d\",\n this.TITLE,\n this.VIDEO_ID,\n this.PUBLISHER.toString(),\n this.THUMBNAIL_URL,\n this.VIEW_COUNT,\n this.LENGTH_SEC\n );\n }\n}" } ]
import tech.tenamen.yt4j.YTDLOption; import tech.tenamen.yt4j.YTSearchFilterOption; import tech.tenamen.yt4j.data.YTVideo;
1,094
public class Main { public static void main(String[] args) { // Create an instance of CustomSC4J. HttpURLConnectionYT4J yt4J = new HttpURLConnectionYT4J(); if (false) { yt4J.getDownloadURL( downloadURL -> System.out.println(downloadURL), "cvZnQ8wN1OQ", new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST) ); return; } // Start searching with title "blue roar". yt4J.startSearch(result -> { // Start second search. yt4J.continueSearch(result2 -> { // Print all title and details in the search result. result2.forEach(r -> System.out.println(r.toString())); // Print the download URL of the lowest quality music of the first video in the search result yt4J.getDownloadURL( downloadURL -> System.out.println(downloadURL), (YTVideo) result.get(0), new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST) ); });
public class Main { public static void main(String[] args) { // Create an instance of CustomSC4J. HttpURLConnectionYT4J yt4J = new HttpURLConnectionYT4J(); if (false) { yt4J.getDownloadURL( downloadURL -> System.out.println(downloadURL), "cvZnQ8wN1OQ", new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST) ); return; } // Start searching with title "blue roar". yt4J.startSearch(result -> { // Start second search. yt4J.continueSearch(result2 -> { // Print all title and details in the search result. result2.forEach(r -> System.out.println(r.toString())); // Print the download URL of the lowest quality music of the first video in the search result yt4J.getDownloadURL( downloadURL -> System.out.println(downloadURL), (YTVideo) result.get(0), new YTDLOption(YTDLOption.YTDLType.AUDIO_MP4, YTDLOption.YTDLQuality.LOWEST) ); });
}, "blue roar", YTSearchFilterOption.VIDEO);
1
2023-10-22 07:36:16+00:00
2k
ImCodist/funny-bfdi
src/main/java/xyz/imcodist/funnybfdi/voice/FunnyBFDIVoice.java
[ { "identifier": "FunnyBFDI", "path": "src/main/java/xyz/imcodist/funnybfdi/FunnyBFDI.java", "snippet": "public class FunnyBFDI implements ModInitializer {\n public static final String MOD_ID = \"funnybfdi\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n @Override\n public void onInitialize() {\n MidnightConfig.init(MOD_ID, Config.class);\n }\n}" }, { "identifier": "MouthManager", "path": "src/main/java/xyz/imcodist/funnybfdi/other/MouthManager.java", "snippet": "public class MouthManager {\n private static final ArrayList<MouthState> playerMouths = new ArrayList<>();\n\n public static void tick() {\n if (!Config.enabled) {\n if (playerMouths.size() > 0) {\n playerMouths.clear();\n }\n\n return;\n }\n\n playerMouths.forEach(MouthState::tick);\n playerMouths.removeIf(mouthState -> mouthState.queueForDeletion);\n }\n\n public static void onPlayerChatted(Text message, UUID senderUUID) {\n if (!Config.enabled) return;\n\n MouthState mouthState = getOrCreatePlayerMouthState(senderUUID);\n\n mouthState.talkCharacter = 0;\n mouthState.talkText = message.getString();\n mouthState.updateMouthShape();\n\n mouthState.talking = true;\n }\n\n public static MouthState getOrCreatePlayerMouthState(UUID playerUUID) {\n MouthState getState = getPlayerMouthState(playerUUID);\n if (getState != null) return getState;\n\n\n MouthState newPlayerState = new MouthState();\n newPlayerState.playerUUID = playerUUID;\n playerMouths.add(newPlayerState);\n\n return newPlayerState;\n }\n\n public static MouthState getPlayerMouthState(UUID playerUUID) {\n for (MouthState mouthState : playerMouths) {\n if (mouthState.playerUUID.equals(playerUUID)) {\n return mouthState;\n }\n }\n\n return null;\n }\n\n public static class MouthState {\n public UUID playerUUID;\n\n public boolean queueForDeletion = false;\n\n public boolean talking = false;\n\n public String talkText = \"\";\n public int talkCharacter = 0;\n\n public String currentMouthShape = \"0\";\n public String transitionMouthShape = currentMouthShape;\n\n private double talkTimer = 0.0;\n\n public void tick() {\n if (talking) {\n talkTimer += 0.75 * Config.mouthSpeed;\n\n if (talkTimer >= 1.0) {\n if (talkCharacter >= talkText.length() - 1) {\n talking = false;\n queueForDeletion = true;\n }\n\n if (talkCharacter < talkText.length()) {\n talkCharacter += 1;\n if (talkCharacter >= talkText.length()) talkCharacter = talkText.length() - 1;\n\n updateMouthShape();\n }\n\n talkTimer -= 1.0;\n }\n\n if (Config.mouthTransitions) {\n if (currentMouthShape.equals(\"8\")) {\n transitionMouthShape = switch (transitionMouthShape) {\n case \"9\" -> \"7\";\n case \"7\", \"8\" -> \"8\";\n default -> \"9\";\n };\n } else {\n if (transitionMouthShape.equals(\"8\") || transitionMouthShape.equals(\"7\")) {\n transitionMouthShape = \"9\";\n } else if (transitionMouthShape.equals(\"3\") && !currentMouthShape.equals(\"3\")) {\n transitionMouthShape = \"2\";\n } else {\n transitionMouthShape = currentMouthShape;\n }\n }\n } else {\n transitionMouthShape = currentMouthShape;\n }\n }\n }\n\n public void updateMouthShape() {\n String character = String.valueOf(talkText.charAt(talkCharacter));\n\n transitionMouthShape = currentMouthShape;\n currentMouthShape = switch (character.toLowerCase()) {\n case \"a\", \"e\", \"u\" -> \"2\";\n case \"i\" -> \"3\";\n case \"o\", \"r\" -> \"8\";\n case \"m\", \"p\", \"b\" -> \"6\";\n case \"f\", \"v\" -> \"5\";\n case \"l\" -> \"4\";\n case \"t\", \"d\", \"k\", \"g\", \"n\", \"s\", \" \" -> \"0\";\n default -> \"1\";\n };\n }\n }\n}" } ]
import de.maxhenkel.voicechat.api.VoicechatApi; import de.maxhenkel.voicechat.api.VoicechatPlugin; import de.maxhenkel.voicechat.api.audio.AudioConverter; import de.maxhenkel.voicechat.api.events.ClientReceiveSoundEvent; import de.maxhenkel.voicechat.api.events.ClientSoundEvent; import de.maxhenkel.voicechat.api.events.EventRegistration; import net.minecraft.client.MinecraftClient; import net.minecraft.text.Text; import xyz.imcodist.funnybfdi.FunnyBFDI; import xyz.imcodist.funnybfdi.other.MouthManager;
1,468
package xyz.imcodist.funnybfdi.voice; public class FunnyBFDIVoice implements VoicechatPlugin { @Override public void initialize(VoicechatApi api) { VoicechatPlugin.super.initialize(api); FunnyBFDI.LOGGER.info("Loaded the voice chat stuffs thats cool nice!"); } @Override public void registerEvents(EventRegistration registration) { VoicechatPlugin.super.registerEvents(registration); registration.registerEvent(ClientReceiveSoundEvent.EntitySound.class, this::onClientReceivedSound); registration.registerEvent(ClientSoundEvent.class, this::onClientSendSound); } @Override public String getPluginId() { return FunnyBFDI.MOD_ID; } public void onClientReceivedSound(ClientReceiveSoundEvent.EntitySound event) { float volume = getVolume(event.getRawAudio(), event.getVoicechat()); if (volume < 100) return; String text = getMessage(volume); // this is a terrible way to do this but its incredibly easy
package xyz.imcodist.funnybfdi.voice; public class FunnyBFDIVoice implements VoicechatPlugin { @Override public void initialize(VoicechatApi api) { VoicechatPlugin.super.initialize(api); FunnyBFDI.LOGGER.info("Loaded the voice chat stuffs thats cool nice!"); } @Override public void registerEvents(EventRegistration registration) { VoicechatPlugin.super.registerEvents(registration); registration.registerEvent(ClientReceiveSoundEvent.EntitySound.class, this::onClientReceivedSound); registration.registerEvent(ClientSoundEvent.class, this::onClientSendSound); } @Override public String getPluginId() { return FunnyBFDI.MOD_ID; } public void onClientReceivedSound(ClientReceiveSoundEvent.EntitySound event) { float volume = getVolume(event.getRawAudio(), event.getVoicechat()); if (volume < 100) return; String text = getMessage(volume); // this is a terrible way to do this but its incredibly easy
MouthManager.onPlayerChatted(Text.of(text), event.getId());
1
2023-10-18 00:31:52+00:00
2k
ItzGreenCat/SkyImprover
src/main/java/me/greencat/skyimprover/feature/dungeonDeathMessage/DungeonDeathMessage.java
[ { "identifier": "Config", "path": "src/main/java/me/greencat/skyimprover/config/Config.java", "snippet": "public class Config extends MidnightConfig {\n @Comment(category = \"render\")\n public static Comment damageSplash;\n @Entry(category = \"render\")\n public static boolean damageSplashEnable = true;\n @Entry(category = \"render\")\n public static boolean damageSplashCompact = true;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 5.0F)\n public static float damageSplashOffset = 2.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 10.0F)\n public static float damageSplashDuration = 3.0F;\n @Entry(category = \"render\",isSlider = true,min = 0.0F,max = 2.0F)\n public static float damageSplashAnimationSpeed = 0.3F;\n\n @Comment(category = \"misc\")\n public static Comment rainTimer;\n @Entry(category = \"misc\")\n public static boolean rainTimerEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float rainTimerGuiOffsetY = 0.3F;\n @Comment(category = \"misc\")\n public static Comment ferocityCount;\n @Entry(category = \"misc\")\n public static boolean ferocityCountEnable = true;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetX = 0.3F;\n @Entry(category = \"misc\",isSlider = true,min = 0.0F,max = 1.0F)\n public static float ferocityCountGuiOffsetY = 0.4F;\n\n @Comment(category = \"dungeon\")\n public static Comment m3FreezeHelper;\n @Entry(category = \"dungeon\")\n public static boolean m3FreezeHelperEnable = true;\n\n @Comment(category = \"dungeon\")\n public static Comment dungeonDeathMessage;\n @Entry(category = \"dungeon\")\n public static boolean dungeonDeathMessageEnable = true;\n @Entry(category = \"dungeon\")\n public static String dungeonDeathMessageContent = \"BOOM!\";\n @Comment(category = \"dungeon\")\n public static Comment kuudraHelper;\n @Entry(category = \"dungeon\")\n public static boolean kuudraHelperEnable = true;\n}" }, { "identifier": "Module", "path": "src/main/java/me/greencat/skyimprover/feature/Module.java", "snippet": "public interface Module {\n void registerEvent();\n}" }, { "identifier": "LocationUtils", "path": "src/main/java/me/greencat/skyimprover/utils/LocationUtils.java", "snippet": "public class LocationUtils {\n public static boolean isOnSkyblock = false;\n public static boolean isInDungeons = false;\n public static boolean isInKuudra = false;\n public static final ObjectArrayList<String> STRING_SCOREBOARD = new ObjectArrayList<>();\n\n public static void update(){\n MinecraftClient minecraftClient = MinecraftClient.getInstance();\n updateScoreboard(minecraftClient);\n updatePlayerPresenceFromScoreboard(minecraftClient);\n }\n public static void updatePlayerPresenceFromScoreboard(MinecraftClient client) {\n List<String> sidebar = STRING_SCOREBOARD;\n\n FabricLoader fabricLoader = FabricLoader.getInstance();\n if (client.world == null || client.isInSingleplayer() || sidebar.isEmpty()) {\n isOnSkyblock = false;\n isInDungeons = false;\n isInKuudra = false;\n }\n\n if (sidebar.isEmpty() && !fabricLoader.isDevelopmentEnvironment()) return;\n String string = sidebar.toString();\n if(sidebar.isEmpty()){\n isInDungeons = false;\n isInKuudra = false;\n return;\n }\n if (sidebar.get(0).contains(\"SKYBLOCK\") || sidebar.get(0).contains(\"SKIBLOCK\")) {\n if (!isOnSkyblock) {\n isOnSkyblock = true;\n }\n } else {\n isOnSkyblock = false;\n }\n isInDungeons = isOnSkyblock && string.contains(\"The Catacombs\");\n isInKuudra = isOnSkyblock && string.contains(\"Kuudra\");\n }\n private static void updateScoreboard(MinecraftClient client) {\n try {\n STRING_SCOREBOARD.clear();\n\n ClientPlayerEntity player = client.player;\n if (player == null) return;\n\n Scoreboard scoreboard = player.getScoreboard();\n ScoreboardObjective objective = scoreboard.getObjectiveForSlot(1);\n ObjectArrayList<Text> textLines = new ObjectArrayList<>();\n ObjectArrayList<String> stringLines = new ObjectArrayList<>();\n\n for (ScoreboardPlayerScore score : scoreboard.getAllPlayerScores(objective)) {\n Team team = scoreboard.getPlayerTeam(score.getPlayerName());\n\n if (team != null) {\n Text textLine = Text.empty().append(team.getPrefix().copy()).append(team.getSuffix().copy());\n String strLine = team.getPrefix().getString() + team.getSuffix().getString();\n\n if (!strLine.trim().isEmpty()) {\n String formatted = Formatting.strip(strLine);\n\n textLines.add(textLine);\n stringLines.add(formatted);\n }\n }\n }\n\n if (objective != null) {\n stringLines.add(objective.getDisplayName().getString());\n textLines.add(Text.empty().append(objective.getDisplayName().copy()));\n\n Collections.reverse(stringLines);\n Collections.reverse(textLines);\n }\n STRING_SCOREBOARD.addAll(stringLines);\n } catch (NullPointerException ignored) {\n\n }\n }\n}" } ]
import me.greencat.skyimprover.config.Config; import me.greencat.skyimprover.feature.Module; import me.greencat.skyimprover.utils.LocationUtils; import net.fabricmc.fabric.api.client.message.v1.ClientReceiveMessageEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.entity.Entity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.text.Text;
1,573
package me.greencat.skyimprover.feature.dungeonDeathMessage; public class DungeonDeathMessage implements Module { @Override public void registerEvent() { ClientReceiveMessageEvents.ALLOW_GAME.register(DungeonDeathMessage::onChat); } private static boolean onChat(Text text, boolean overlay) { if(!Config.dungeonDeathMessageEnable){ return true; }
package me.greencat.skyimprover.feature.dungeonDeathMessage; public class DungeonDeathMessage implements Module { @Override public void registerEvent() { ClientReceiveMessageEvents.ALLOW_GAME.register(DungeonDeathMessage::onChat); } private static boolean onChat(Text text, boolean overlay) { if(!Config.dungeonDeathMessageEnable){ return true; }
LocationUtils.update();
2
2023-10-19 09:19:09+00:00
2k
zilliztech/kafka-connect-milvus
src/main/java/com/milvus/io/kafka/helper/MilvusClientHelper.java
[ { "identifier": "MilvusSinkConnectorConfig", "path": "src/main/java/com/milvus/io/kafka/MilvusSinkConnectorConfig.java", "snippet": "public class MilvusSinkConnectorConfig extends AbstractConfig {\n protected static final String URL = \"public.endpoint\";\n protected static final String TOKEN = \"token\";\n protected static final String COLLECTION_NAME = \"collection.name\";\n\n public MilvusSinkConnectorConfig(ConfigDef config, Map<String, String> parsedConfig) {\n super(config, parsedConfig);\n }\n\n public MilvusSinkConnectorConfig(Map<String, String> parsedConfig) {\n this(conf(), parsedConfig);\n }\n\n public static ConfigDef conf() {\n return new ConfigDef()\n .define(URL, ConfigDef.Type.STRING, \"\", ConfigDef.Importance.MEDIUM, \"Public Endpoint\")\n .define(TOKEN, ConfigDef.Type.PASSWORD, \"db_admin:****\", ConfigDef.Importance.HIGH, \"Token to connect milvus\")\n .define(COLLECTION_NAME, ConfigDef.Type.STRING, \"\", ConfigDef.Importance.MEDIUM, \"Collection name to save the topic messages\");\n }\n\n public String getUrl() {\n return getString(URL);\n }\n\n public Password getToken() {\n return getPassword(TOKEN);\n }\n\n public String getCollectionName(){return getString(COLLECTION_NAME);}\n}" }, { "identifier": "Utils", "path": "src/main/java/com/milvus/io/kafka/utils/Utils.java", "snippet": "public class Utils {\n private static final Logger log = LoggerFactory.getLogger(Utils.class);\n private static final SecretKey SECRET_KEY = generateSecretKey();\n\n public static String encryptToken(String token) {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, SECRET_KEY);\n\n byte[] encryptedBytes = cipher.doFinal(token.getBytes(StandardCharsets.UTF_8));\n return Base64.getEncoder().encodeToString(encryptedBytes);\n } catch (Exception e) {\n // Handle encryption errors\n log.error(\"encryption error\" + e.getMessage());\n return null;\n }\n }\n\n public static String decryptToken(String token) {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\");\n cipher.init(Cipher.DECRYPT_MODE, SECRET_KEY);\n\n byte[] encryptedBytes = Base64.getDecoder().decode(token);\n byte[] decryptedBytes = cipher.doFinal(encryptedBytes);\n\n return new String(decryptedBytes, StandardCharsets.UTF_8);\n } catch (Exception e) {\n // Handle decryption errors\n log.error(\"decryption error\" + e.getMessage());\n return null;\n }\n }\n\n public static SecretKey generateSecretKey() {\n try {\n KeyGenerator keyGenerator = KeyGenerator.getInstance(\"AES\");\n SecureRandom secureRandom = new SecureRandom();\n keyGenerator.init(128, secureRandom);\n return keyGenerator.generateKey();\n } catch (NoSuchAlgorithmException e) {\n log.error(e.getMessage());\n return null;\n }\n }\n\n}" } ]
import com.milvus.io.kafka.MilvusSinkConnectorConfig; import com.milvus.io.kafka.utils.Utils; import io.milvus.client.MilvusServiceClient; import io.milvus.param.ConnectParam;
836
package com.milvus.io.kafka.helper; public class MilvusClientHelper { public MilvusServiceClient createMilvusClient(MilvusSinkConnectorConfig config) { ConnectParam connectParam = ConnectParam.newBuilder() .withUri(config.getUrl())
package com.milvus.io.kafka.helper; public class MilvusClientHelper { public MilvusServiceClient createMilvusClient(MilvusSinkConnectorConfig config) { ConnectParam connectParam = ConnectParam.newBuilder() .withUri(config.getUrl())
.withToken(Utils.decryptToken(config.getToken().value()))
1
2023-10-18 02:11:08+00:00
2k
histevehu/12306
batch/src/main/java/com/steve/train/batch/controller/JobController.java
[ { "identifier": "CronJobReq", "path": "batch/src/main/java/com/steve/train/batch/req/CronJobReq.java", "snippet": "public class CronJobReq {\n private String group;\n private String name;\n private String description;\n private String cronExpression;\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer(\"CronJobDto{\");\n sb.append(\"cronExpression='\").append(cronExpression).append('\\'');\n sb.append(\", group='\").append(group).append('\\'');\n sb.append(\", name='\").append(name).append('\\'');\n sb.append(\", description='\").append(description).append('\\'');\n sb.append('}');\n return sb.toString();\n }\n\n public String getGroup() {\n return group;\n }\n\n public void setGroup(String group) {\n this.group = group;\n }\n\n public String getCronExpression() {\n return cronExpression;\n }\n\n public void setCronExpression(String cronExpression) {\n this.cronExpression = cronExpression;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "identifier": "CronJobResp", "path": "batch/src/main/java/com/steve/train/batch/resp/CronJobResp.java", "snippet": "@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class CronJobResp {\n private String group;\n\n private String name;\n\n private String description;\n\n private String state;\n\n private String cronExpression;\n\n @JsonFormat(pattern=\"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date nextFireTime;\n\n @JsonFormat(pattern=\"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")\n private Date preFireTime;\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer(\"CronJobDto{\");\n sb.append(\"cronExpression='\").append(cronExpression).append('\\'');\n sb.append(\", group='\").append(group).append('\\'');\n sb.append(\", name='\").append(name).append('\\'');\n sb.append(\", description='\").append(description).append('\\'');\n sb.append(\", state='\").append(state).append('\\'');\n sb.append(\", nextFireTime=\").append(nextFireTime);\n sb.append(\", preFireTime=\").append(preFireTime);\n sb.append('}');\n return sb.toString();\n }\n\n public String getGroup() {\n return group;\n }\n\n public void setGroup(String group) {\n this.group = group;\n }\n\n public String getCronExpression() {\n return cronExpression;\n }\n\n public void setCronExpression(String cronExpression) {\n this.cronExpression = cronExpression;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\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 Date getNextFireTime() {\n return nextFireTime;\n }\n\n public void setNextFireTime(Date nextFireTime) {\n this.nextFireTime = nextFireTime;\n }\n\n public Date getPreFireTime() {\n return preFireTime;\n }\n\n public void setPreFireTime(Date preFireTime) {\n this.preFireTime = preFireTime;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n}" }, { "identifier": "CommonResp", "path": "common/src/main/java/com/steve/train/common/resp/CommonResp.java", "snippet": "public class CommonResp<T> {\n\n /**\n * 业务上的成功或失败\n */\n private boolean success = true;\n\n /**\n * 返回信息\n */\n private String message;\n\n /**\n * 返回泛型数据,自定义类型\n */\n private T content;\n\n public CommonResp() {\n }\n\n public CommonResp(boolean success, String message, T content) {\n this.success = success;\n this.message = message;\n this.content = content;\n }\n\n public CommonResp(T content) {\n this.content = content;\n }\n\n public boolean getSuccess() {\n return success;\n }\n\n public void setSuccess(boolean success) {\n this.success = success;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public T getContent() {\n return content;\n }\n\n public void setContent(T content) {\n this.content = content;\n }\n\n @Override\n public String toString() {\n final StringBuffer sb = new StringBuffer(\"CommonResp{\");\n sb.append(\"success=\").append(success);\n sb.append(\", message='\").append(message).append('\\'');\n sb.append(\", content=\").append(content);\n sb.append('}');\n return sb.toString();\n }\n}" } ]
import com.steve.train.batch.req.CronJobReq; import com.steve.train.batch.resp.CronJobResp; import com.steve.train.common.resp.CommonResp; import org.quartz.*; import org.quartz.impl.matchers.GroupMatcher; import org.quartz.impl.triggers.CronTriggerImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Date; import java.util.List;
1,503
package com.steve.train.batch.controller; @RestController @RequestMapping(value = "/admin/job") public class JobController { private static Logger LOG = LoggerFactory.getLogger(JobController.class); @Autowired private SchedulerFactoryBean schedulerFactoryBean; @RequestMapping(value = "/run")
package com.steve.train.batch.controller; @RestController @RequestMapping(value = "/admin/job") public class JobController { private static Logger LOG = LoggerFactory.getLogger(JobController.class); @Autowired private SchedulerFactoryBean schedulerFactoryBean; @RequestMapping(value = "/run")
public CommonResp<Object> run(@RequestBody CronJobReq cronJobReq) throws SchedulerException {
2
2023-10-23 01:20:56+00:00
2k
artipie/maven-resolver-http3-plugin
mvn-resolver-transport-http3/src/main/java/com/artipie/aether/transport/http3/HttpTransporterFactory.java
[ { "identifier": "ChecksumExtractor", "path": "mvn-resolver-transport-http3/src/main/java/com/artipie/aether/transport/http3/checksum/ChecksumExtractor.java", "snippet": "public abstract class ChecksumExtractor {\n /**\n * Tries to extract checksums from response headers, if present, otherwise returns {@code null}.\n */\n public abstract Map<String, String> extractChecksums(HttpFields response);\n}" }, { "identifier": "Nexus2ChecksumExtractor", "path": "mvn-resolver-transport-http3/src/main/java/com/artipie/aether/transport/http3/checksum/Nexus2ChecksumExtractor.java", "snippet": "@Singleton\n@Named(Nexus2ChecksumExtractor.NAME)\npublic class Nexus2ChecksumExtractor extends ChecksumExtractor {\n public static final String NAME = \"nexus2\";\n\n @Override\n public Map<String, String> extractChecksums(HttpFields headers) {\n // Nexus-style, ETag: \"{SHA1{d40d68ba1f88d8e9b0040f175a6ff41928abd5e7}}\"\n\n HttpField field = headers.getField(HttpHeader.ETAG);\n String etag = field == null? null: field.getValue();\n\n if (etag != null) {\n int start = etag.indexOf(\"SHA1{\"), end = etag.indexOf(\"}\", start + 5);\n if (start >= 0 && end > start) {\n return Collections.singletonMap(\"SHA-1\", etag.substring(start + 5, end));\n }\n }\n return null;\n }\n}" }, { "identifier": "XChecksumChecksumExtractor", "path": "mvn-resolver-transport-http3/src/main/java/com/artipie/aether/transport/http3/checksum/XChecksumChecksumExtractor.java", "snippet": "@Singleton\n@Named(XChecksumChecksumExtractor.NAME)\npublic class XChecksumChecksumExtractor extends ChecksumExtractor {\n public static final String NAME = \"x-checksum\";\n\n @Override\n public Map<String, String> extractChecksums(HttpFields response) {\n String value;\n HashMap<String, String> result = new HashMap<>();\n // Central style: x-checksum-sha1: c74edb60ca2a0b57ef88d9a7da28f591e3d4ce7b\n value = extractChecksum(response, \"x-checksum-sha1\");\n if (value != null) {\n result.put(\"SHA-1\", value);\n }\n // Central style: x-checksum-md5: 9ad0d8e3482767c122e85f83567b8ce6\n value = extractChecksum(response, \"x-checksum-md5\");\n if (value != null) {\n result.put(\"MD5\", value);\n }\n if (!result.isEmpty()) {\n return result;\n }\n // Google style: x-goog-meta-checksum-sha1: c74edb60ca2a0b57ef88d9a7da28f591e3d4ce7b\n value = extractChecksum(response, \"x-goog-meta-checksum-sha1\");\n if (value != null) {\n result.put(\"SHA-1\", value);\n }\n // Central style: x-goog-meta-checksum-sha1: 9ad0d8e3482767c122e85f83567b8ce6\n value = extractChecksum(response, \"x-goog-meta-checksum-md5\");\n if (value != null) {\n result.put(\"MD5\", value);\n }\n\n return result.isEmpty() ? null : result;\n }\n\n private String extractChecksum(HttpFields response, String name) {\n HttpField header = response.getField(name);\n return header == null ? null : header.getValue();\n }\n}" } ]
import java.util.HashMap; import java.util.Map; import static java.util.Objects.requireNonNull; import com.artipie.aether.transport.http3.checksum.ChecksumExtractor; import com.artipie.aether.transport.http3.checksum.Nexus2ChecksumExtractor; import com.artipie.aether.transport.http3.checksum.XChecksumChecksumExtractor; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.repository.RemoteRepository; import org.eclipse.aether.spi.connector.transport.Transporter; import org.eclipse.aether.spi.connector.transport.TransporterFactory; import org.eclipse.aether.transfer.NoTransporterException; import javax.inject.Inject; import javax.inject.Named; import java.util.Collections;
1,250
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.artipie.aether.transport.http3; /** * A transporter factory for repositories using the {@code http:} or {@code https:} protocol. The provided transporters * support uploads to WebDAV servers and resumable downloads. */ @Named("http") public final class HttpTransporterFactory implements TransporterFactory {
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.artipie.aether.transport.http3; /** * A transporter factory for repositories using the {@code http:} or {@code https:} protocol. The provided transporters * support uploads to WebDAV servers and resumable downloads. */ @Named("http") public final class HttpTransporterFactory implements TransporterFactory {
private static Map<String, ChecksumExtractor> getManuallyCreatedExtractors() {
0
2023-10-23 12:16:24+00:00
2k
VineeTagarwaL-code/30-Java-Projects
shoppingcartecommercejava/src/com/shashi/service/impl/DemandServiceImpl.java
[ { "identifier": "DemandBean", "path": "shoppingcartecommercejava/src/com/shashi/beans/DemandBean.java", "snippet": "@SuppressWarnings(\"serial\")\npublic class DemandBean implements Serializable {\n\n\tprivate String userName;\n\tprivate String prodId;\n\tprivate int demandQty;\n\n\tpublic DemandBean() {\n\t\tsuper();\n\t}\n\n\tpublic DemandBean(String userName, String prodId, int demandQty) {\n\t\tsuper();\n\t\tthis.userName = userName;\n\t\tthis.prodId = prodId;\n\t\tthis.demandQty = demandQty;\n\t}\n\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\tpublic void setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\n\tpublic String getProdId() {\n\t\treturn prodId;\n\t}\n\n\tpublic void setProdId(String prodId) {\n\t\tthis.prodId = prodId;\n\t}\n\n\tpublic int getDemandQty() {\n\t\treturn demandQty;\n\t}\n\n\tpublic void setDemandQty(int demandQty) {\n\t\tthis.demandQty = demandQty;\n\t}\n\n}" }, { "identifier": "DemandService", "path": "shoppingcartecommercejava/src/com/shashi/service/DemandService.java", "snippet": "public interface DemandService {\n\n\tpublic boolean addProduct(String userId, String prodId, int demandQty);\n\n\tpublic boolean addProduct(DemandBean userDemandBean);\n\n\tpublic boolean removeProduct(String userId, String prodId);\n\n\tpublic List<DemandBean> haveDemanded(String prodId);\n\n}" }, { "identifier": "DBUtil", "path": "shoppingcartecommercejava/src/com/shashi/utility/DBUtil.java", "snippet": "public class DBUtil {\n\tprivate static Connection conn;\n\n\tpublic DBUtil() {\n\t}\n\n\tpublic static Connection provideConnection() {\n\n\t\ttry {\n\t\t\tif (conn == null || conn.isClosed()) {\n\t\t\t\tResourceBundle rb = ResourceBundle.getBundle(\"application\");\n\t\t\t\tString connectionString = rb.getString(\"db.connectionString\");\n\t\t\t\tString driverName = rb.getString(\"db.driverName\");\n\t\t\t\tString username = rb.getString(\"db.username\");\n\t\t\t\tString password = rb.getString(\"db.password\");\n\t\t\t\ttry {\n\t\t\t\t\tClass.forName(driverName);\n\t\t\t\t} catch (ClassNotFoundException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t\tconn = DriverManager.getConnection(connectionString, username, password);\n\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn conn;\n\t}\n\n\tpublic static void closeConnection(Connection con) {\n\t\t/*\n\t\t * try { if (con != null && !con.isClosed()) {\n\t\t * \n\t\t * con.close(); } } catch (SQLException e) { // TODO Auto-generated catch block\n\t\t * e.printStackTrace(); }\n\t\t */\n\t}\n\n\tpublic static void closeConnection(ResultSet rs) {\n\t\ttry {\n\t\t\tif (rs != null && !rs.isClosed()) {\n\t\t\t\ttry {\n\t\t\t\t\trs.close();\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static void closeConnection(PreparedStatement ps) {\n\t\ttry {\n\t\t\tif (ps != null && !ps.isClosed()) {\n\t\t\t\ttry {\n\t\t\t\t\tps.close();\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}" } ]
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.shashi.beans.DemandBean; import com.shashi.service.DemandService; import com.shashi.utility.DBUtil;
1,038
package com.shashi.service.impl; //This class is to process the demand items which are //not available at the time of purchase by any customer //the customer will receive mail once the product is avaible //back into the store public class DemandServiceImpl implements DemandService { @Override public boolean addProduct(String userId, String prodId, int demandQty) { boolean flag = false; //get the database connection
package com.shashi.service.impl; //This class is to process the demand items which are //not available at the time of purchase by any customer //the customer will receive mail once the product is avaible //back into the store public class DemandServiceImpl implements DemandService { @Override public boolean addProduct(String userId, String prodId, int demandQty) { boolean flag = false; //get the database connection
Connection con = DBUtil.provideConnection();
2
2023-10-22 10:39:43+00:00
2k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/payment/PaymentMapper.java
[ { "identifier": "Order", "path": "src/main/java/com/moabam/api/domain/payment/Order.java", "snippet": "@Embeddable\n@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Order {\n\n\t@Column(name = \"order_id\")\n\tprivate String id;\n\n\t@Column(name = \"order_name\", nullable = false)\n\tprivate String name;\n\n\t@Builder\n\tprivate Order(String name) {\n\t\tthis.name = requireNonNull(name);\n\t}\n\n\tpublic void updateId(String id) {\n\t\tthis.id = id;\n\t}\n}" }, { "identifier": "Payment", "path": "src/main/java/com/moabam/api/domain/payment/Payment.java", "snippet": "@Entity\n@Getter\n@Table(name = \"payment\", indexes = @Index(name = \"idx_order_id\", columnList = \"order_id\"))\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@EntityListeners(AuditingEntityListener.class)\npublic class Payment {\n\n\tprivate static final int MIN_AMOUNT = 0;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"member_id\", updatable = false, nullable = false)\n\tprivate Long memberId;\n\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@JoinColumn(name = \"product_id\", updatable = false, nullable = false)\n\tprivate Product product;\n\n\t@Column(name = \"coupon_wallet_id\")\n\tprivate Long couponWalletId;\n\n\t@Embedded\n\tprivate Order order;\n\n\t@Column(name = \"total_amount\", nullable = false)\n\tprivate int totalAmount;\n\n\t@Column(name = \"discount_amount\", nullable = false)\n\tprivate int discountAmount;\n\n\t@Column(name = \"payment_key\")\n\tprivate String paymentKey;\n\n\t@Enumerated(value = EnumType.STRING)\n\t@Column(name = \"status\", nullable = false)\n\tprivate PaymentStatus status;\n\n\t@CreatedDate\n\t@Column(name = \"created_at\", updatable = false, nullable = false)\n\tprivate LocalDateTime createdAt;\n\n\t@Column(name = \"requested_at\")\n\tprivate LocalDateTime requestedAt;\n\n\t@Column(name = \"approved_at\")\n\tprivate LocalDateTime approvedAt;\n\n\t@Builder\n\tpublic Payment(Long memberId, Product product, Long couponWalletId, Order order, int totalAmount,\n\t\tint discountAmount, PaymentStatus status) {\n\t\tthis.memberId = requireNonNull(memberId);\n\t\tthis.product = requireNonNull(product);\n\t\tthis.couponWalletId = couponWalletId;\n\t\tthis.order = requireNonNull(order);\n\t\tthis.totalAmount = validateAmount(totalAmount);\n\t\tthis.discountAmount = validateAmount(discountAmount);\n\t\tthis.status = requireNonNullElse(status, PaymentStatus.READY);\n\t}\n\n\tprivate int validateAmount(int amount) {\n\t\tif (amount < MIN_AMOUNT) {\n\t\t\tthrow new BadRequestException(INVALID_PAYMENT_AMOUNT);\n\t\t}\n\n\t\treturn amount;\n\t}\n\n\tpublic void validateInfo(Long memberId, int amount) {\n\t\tvalidateByMember(memberId);\n\t\tvalidateByTotalAmount(amount);\n\t}\n\n\tpublic void validateByMember(Long memberId) {\n\t\tif (!this.memberId.equals(memberId)) {\n\t\t\tthrow new BadRequestException(INVALID_MEMBER_PAYMENT);\n\t\t}\n\t}\n\n\tprivate void validateByTotalAmount(int amount) {\n\t\tif (this.totalAmount != amount) {\n\t\t\tthrow new BadRequestException(INVALID_PAYMENT_INFO);\n\t\t}\n\t}\n\n\tpublic boolean isCouponApplied() {\n\t\treturn !isNull(this.couponWalletId);\n\t}\n\n\tpublic void applyCoupon(CouponWallet couponWallet) {\n\t\tthis.couponWalletId = couponWallet.getId();\n\t\tthis.discountAmount = couponWallet.getCoupon().getPoint();\n\t\tthis.totalAmount = Math.max(MIN_AMOUNT, this.totalAmount - this.discountAmount);\n\t}\n\n\tpublic void request(String orderId) {\n\t\tthis.order.updateId(orderId);\n\t\tthis.requestedAt = LocalDateTime.now();\n\t}\n\n\tpublic void confirm(String paymentKey) {\n\t\tthis.paymentKey = paymentKey;\n\t\tthis.approvedAt = LocalDateTime.now();\n\t\tthis.status = PaymentStatus.DONE;\n\t}\n\n\tpublic void fail(String paymentKey) {\n\t\tthis.paymentKey = paymentKey;\n\t\tthis.status = PaymentStatus.ABORTED;\n\t}\n}" }, { "identifier": "Product", "path": "src/main/java/com/moabam/api/domain/product/Product.java", "snippet": "@Entity\n@Getter\n@Table(name = \"product\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Product extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Enumerated(value = EnumType.STRING)\n\t@Column(name = \"type\", nullable = false)\n\t@ColumnDefault(\"'BUG'\")\n\tprivate ProductType type;\n\n\t@Column(name = \"name\", nullable = false)\n\tprivate String name;\n\n\t@Column(name = \"price\", nullable = false)\n\tprivate int price;\n\n\t@Column(name = \"quantity\", nullable = false)\n\t@ColumnDefault(\"1\")\n\tprivate int quantity;\n\n\t@Builder\n\tprivate Product(ProductType type, String name, int price, Integer quantity) {\n\t\tthis.type = requireNonNullElse(type, ProductType.BUG);\n\t\tthis.name = requireNonNull(name);\n\t\tthis.price = validatePrice(price);\n\t\tthis.quantity = validateQuantity(requireNonNullElse(quantity, 1));\n\t}\n\n\tprivate int validatePrice(int price) {\n\t\tif (price < 0) {\n\t\t\tthrow new BadRequestException(INVALID_PRICE);\n\t\t}\n\n\t\treturn price;\n\t}\n\n\tprivate int validateQuantity(int quantity) {\n\t\tif (quantity < 1) {\n\t\t\tthrow new BadRequestException(INVALID_QUANTITY);\n\t\t}\n\n\t\treturn quantity;\n\t}\n}" } ]
import java.util.Optional; import com.moabam.api.domain.payment.Order; import com.moabam.api.domain.payment.Payment; import com.moabam.api.domain.product.Product; import com.moabam.api.dto.payment.ConfirmTossPaymentResponse; import com.moabam.api.dto.payment.PaymentResponse; import com.moabam.api.dto.payment.RequestConfirmPaymentResponse; import lombok.AccessLevel; import lombok.NoArgsConstructor;
1,534
package com.moabam.api.application.payment; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class PaymentMapper {
package com.moabam.api.application.payment; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class PaymentMapper {
public static Payment toPayment(Long memberId, Product product) {
2
2023-10-20 06:15:43+00:00
2k
Chocochip101/aws-kendra-demo
src/main/java/com/chocochip/awskendrademo/application/DemoController.java
[ { "identifier": "IndexRequestDTO", "path": "src/main/java/com/chocochip/awskendrademo/dto/IndexRequestDTO.java", "snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class IndexRequestDTO {\n private String name;\n private String clientToken;\n private String roleArn;\n private String description = \"\";\n\n @Builder\n public IndexRequestDTO(String name, String clientToken, String roleArn, String description) {\n this.name = name;\n this.clientToken = clientToken;\n this.roleArn = roleArn;\n this.description = description;\n }\n}" }, { "identifier": "S3DataSourceRequestDTO", "path": "src/main/java/com/chocochip/awskendrademo/dto/S3DataSourceRequestDTO.java", "snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class S3DataSourceRequestDTO {\n private String clientToken;\n private String dataSourceName;\n private String description;\n private String languageCode;\n private String roleArn;\n private String bucketName;\n private String s3PrefixMetaData;\n\n @Builder\n public S3DataSourceRequestDTO(String clientToken, String dataSourceName, String description, String languageCode,\n String roleArn, String bucketName, String s3PrefixMetaData) {\n this.clientToken = clientToken;\n this.dataSourceName = dataSourceName;\n this.description = description;\n this.languageCode = languageCode;\n this.roleArn = roleArn;\n this.bucketName = bucketName;\n this.s3PrefixMetaData = s3PrefixMetaData;\n }\n}" }, { "identifier": "SearchResultDTO", "path": "src/main/java/com/chocochip/awskendrademo/dto/SearchResultDTO.java", "snippet": "@NoArgsConstructor\n@Getter\n@Setter\npublic class SearchResultDTO {\n private String type;\n private String title;\n private String excerpt;\n private String uri;\n\n @Builder\n public SearchResultDTO(String type, String title, String excerpt, String uri) {\n this.type = type;\n this.title = title;\n this.excerpt = excerpt;\n this.uri = uri;\n }\n}" }, { "identifier": "KendraService", "path": "src/main/java/com/chocochip/awskendrademo/service/KendraService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class KendraService {\n private final KendraClient kendraClient;\n\n public String createIndex(IndexRequestDTO indexRequestDTO) {\n CreateIndexRequest createIndexRequest = CreateIndexRequest\n .builder()\n .name(indexRequestDTO.getName())\n .clientToken(indexRequestDTO.getClientToken())\n .roleArn(indexRequestDTO.getRoleArn())\n .description(indexRequestDTO.getDescription())\n .build();\n CreateIndexResponse index = kendraClient.createIndex(createIndexRequest);\n return index.id();\n }\n\n public void deleteIndex(String indexId) {\n DeleteIndexRequest deleteIndexRequest = DeleteIndexRequest\n .builder()\n .id(indexId)\n .build();\n kendraClient.deleteIndex(deleteIndexRequest);\n }\n}" }, { "identifier": "IndexService", "path": "src/main/java/com/chocochip/awskendrademo/service/IndexService.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class IndexService {\n private final KendraClient kendraClient;\n\n public List<SearchResultDTO> searchForDocuments(String query, String indexId) {\n QueryRequest queryRequest = QueryRequest\n .builder()\n .queryText(query)\n .indexId(indexId)\n .build();\n\n QueryResponse queryResponse = kendraClient.query(queryRequest);\n\n return queryResponse.resultItems().stream()\n .filter(item -> isValidResultType(item.type()))\n .map(item -> SearchResultDTO.builder()\n .type(item.type().toString())\n .title(item.documentTitle().text())\n .excerpt(item.documentExcerpt().text())\n .uri(item.documentURI())\n .build())\n .collect(Collectors.toList());\n }\n\n private boolean isValidResultType(QueryResultType type) {\n return type == QueryResultType.ANSWER || type == QueryResultType.QUESTION_ANSWER\n || type == QueryResultType.DOCUMENT;\n }\n\n public String addS3DataSource(S3DataSourceRequestDTO s3DataSourceRequestDTO, String indexId) {\n DataSourceConfiguration dataSourceConfiguration\n = getDataSourceConfiguration(s3DataSourceRequestDTO);\n\n CreateDataSourceRequest createDataSourceRequest = CreateDataSourceRequest\n .builder()\n .indexId(indexId)\n .name(s3DataSourceRequestDTO.getDataSourceName())\n .roleArn(s3DataSourceRequestDTO.getRoleArn())\n .description(s3DataSourceRequestDTO.getDescription())\n .clientToken(s3DataSourceRequestDTO.getClientToken())\n .configuration(dataSourceConfiguration)\n .type(DataSourceType.S3).build();\n CreateDataSourceResponse dataSource = kendraClient.createDataSource(createDataSourceRequest);\n return dataSource.id();\n }\n\n private DataSourceConfiguration getDataSourceConfiguration(S3DataSourceRequestDTO s3DataSourceRequestDTO) {\n DocumentsMetadataConfiguration documentsMetadataConfiguration = DocumentsMetadataConfiguration\n .builder()\n .s3Prefix(s3DataSourceRequestDTO.getS3PrefixMetaData())\n .build();\n\n S3DataSourceConfiguration s3DataSourceConfiguration = S3DataSourceConfiguration\n .builder()\n .documentsMetadataConfiguration(documentsMetadataConfiguration)\n .bucketName(s3DataSourceRequestDTO.getBucketName())\n .build();\n\n return DataSourceConfiguration\n .builder()\n .s3Configuration(s3DataSourceConfiguration)\n .build();\n }\n\n public void syncDataSource(String indexId, String dataSourceId) {\n StartDataSourceSyncJobRequest startDataSourceSyncJobRequest = StartDataSourceSyncJobRequest\n .builder()\n .indexId(indexId)\n .id(dataSourceId)\n .build();\n kendraClient.startDataSourceSyncJob(startDataSourceSyncJobRequest);\n }\n}" } ]
import com.chocochip.awskendrademo.dto.IndexRequestDTO; import com.chocochip.awskendrademo.dto.S3DataSourceRequestDTO; import com.chocochip.awskendrademo.dto.SearchResultDTO; import com.chocochip.awskendrademo.service.KendraService; import com.chocochip.awskendrademo.service.IndexService; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;
1,559
package com.chocochip.awskendrademo.application; @RestController @RequiredArgsConstructor public class DemoController { private final IndexService indexService; private final KendraService kendraService; @GetMapping("/search")
package com.chocochip.awskendrademo.application; @RestController @RequiredArgsConstructor public class DemoController { private final IndexService indexService; private final KendraService kendraService; @GetMapping("/search")
public ResponseEntity<List<SearchResultDTO>> search(
2
2023-10-23 15:47:15+00:00
2k
liukanshan1/PrivateTrace-Core
src/main/java/Priloc/geo/Utils.java
[ { "identifier": "Constant", "path": "src/main/java/Priloc/utils/Constant.java", "snippet": "public class Constant {\n public static final int FIXED_POINT = 8;\n public static final int THREAD = 12;\n public static final int KEY_LEN = 512;\n public static final int[] REDUCE = new int[]{2160000, 1820000, -5690000};\n\n public static final boolean IGNORE_DATE = true;\n public static final boolean REJECT_R_LESS_P5 = true;\n\n // 时间段大小\n public final static int INTERVAL = 10;\n // 每个时间段的移动最大距离\n public static final double RADIUS = 200.0;\n // TODO 优化 不同时间段的活跃距离\n public static final double[] COMPARE_DISTANCE = new double[]{1200 * 1200.0};\n public static final int[] PRUNE_NUM = new int[]{0, 2};\n // 控制形状拟合效果\n public static final int TRIANGLE_NUM = 100;\n public static final Circle.circleFilter FILTER = new Circle.distantFilter(); //new Circle.areaFilter();\n\n public static String toStr() {\n return \"Constant{\" +\n \"INTERVAL=\" + INTERVAL +\n \", RADIUS=\" + RADIUS +\n \", IGNORE_DATE=\" + IGNORE_DATE +\n \", REJECT_R_LESS_P5=\" + REJECT_R_LESS_P5 +\n \", COMPARE_DISTANCE=\" + Arrays.toString(COMPARE_DISTANCE) +\n \", PRUNE_NUM=\" + Arrays.toString(PRUNE_NUM) +\n \", TRIANGLE_NUM=\" + TRIANGLE_NUM +\n \", FILTER=\" + FILTER +\n '}';\n }\n}" }, { "identifier": "Pair", "path": "src/main/java/Priloc/utils/Pair.java", "snippet": "public class Pair<T1, T2> {\n\t\n public final T1 first;\n public final T2 second;\n\n public Pair(T1 first, T2 second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public String toString() {\n return \"Pair{\" +\n \"first=\" + first +\n \", second=\" + second +\n '}';\n }\n}" }, { "identifier": "Turple", "path": "src/main/java/Priloc/utils/Turple.java", "snippet": "public class Turple<T1, T2, T3> {\n public final T1 first;\n public final T2 second;\n public final T3 third;\n\n public Turple(T1 first, T2 second, T3 third) {\n this.first = first;\n this.second = second;\n this.third = third;\n }\n\n @Override\n public String toString() {\n return \"Turple{\" +\n \"first=\" + first +\n \", second=\" + second +\n \", third=\" + third +\n '}';\n }\n}" } ]
import Priloc.utils.Constant; import Priloc.utils.Pair; import Priloc.utils.Turple;
1,519
package Priloc.geo; public class Utils { private static final double X_PI = Math.PI * 3000.0 / 180.0; private static final double PI = Math.PI; private static final double A = 6378245.0; private static final double EE = 0.00669342162296594323; private static double transformLat(double lng, double lat) { double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0; return ret; } private static double transformLon(double lng, double lat) { double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0; return ret; } /** * WGS84转GCJ02(火星坐标系) * @param lng WGS84坐标系的经度 * @param lat WGS84坐标系的纬度 */ public static Pair<Double, Double> wgs84ToGcj02(double lng, double lat) { double dLat = transformLat(lng - 105.0, lat - 35.0); double dLng = transformLon(lng - 105.0, lat - 35.0); double radLat = lat / 180.0 * PI; double magic = Math.sin(radLat); magic = 1 - EE * magic * magic; double sqrtMagic = Math.sqrt(magic); dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI); dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * PI); double mgLat = lat + dLat; double mgLng = lng + dLng; return new Pair<>(mgLng, mgLat); } /** * GCJ02(火星坐标系)转XYZ * @param lng GCJ02坐标系的经度 * @param lat GCJ02坐标系的纬度 * 后期可增加高程信息优化精度 */
package Priloc.geo; public class Utils { private static final double X_PI = Math.PI * 3000.0 / 180.0; private static final double PI = Math.PI; private static final double A = 6378245.0; private static final double EE = 0.00669342162296594323; private static double transformLat(double lng, double lat) { double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0; return ret; } private static double transformLon(double lng, double lat) { double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0; return ret; } /** * WGS84转GCJ02(火星坐标系) * @param lng WGS84坐标系的经度 * @param lat WGS84坐标系的纬度 */ public static Pair<Double, Double> wgs84ToGcj02(double lng, double lat) { double dLat = transformLat(lng - 105.0, lat - 35.0); double dLng = transformLon(lng - 105.0, lat - 35.0); double radLat = lat / 180.0 * PI; double magic = Math.sin(radLat); magic = 1 - EE * magic * magic; double sqrtMagic = Math.sqrt(magic); dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI); dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * PI); double mgLat = lat + dLat; double mgLng = lng + dLng; return new Pair<>(mgLng, mgLat); } /** * GCJ02(火星坐标系)转XYZ * @param lng GCJ02坐标系的经度 * @param lat GCJ02坐标系的纬度 * 后期可增加高程信息优化精度 */
public static Turple<Double, Double, Double> gcj02ToXYZ(double lng, double lat) {
2
2023-10-22 06:28:51+00:00
2k
ErickMonteiroMDK/Advocacia_Beckhauser
src/main/java/com/advocacia/Advocacia_Beckhauser/services/AgendaService.java
[ { "identifier": "Agenda", "path": "src/main/java/com/advocacia/Advocacia_Beckhauser/models/Agenda.java", "snippet": "@Entity\npublic class Agenda extends EntityID \n{\n @Column(name = \"dataOcorrencia\", nullable = false)\n private LocalDate dataOcorrencia;\n\n\n @ManyToOne\n @JoinColumn(name = \"advogado_responsavel_id\", referencedColumnName = \"id\")\n private Advogado responsavel;\n\n @ManyToOne\n @JoinColumn(name = \"processo_id\", referencedColumnName = \"id\")\n private Processo numeroProcesso;\n\n\n @Column(nullable = false)\n private String situacao;\n\n @Column(nullable = false)\n private String fase;\n\n @Column(nullable = false)\n private String local;\n\n @Column(nullable = false)\n private String tipoPrazo;\n\n @Column(nullable = false)\n private LocalDate dataInicial;\n \n @Column(nullable = false)\n private Integer prazo;\n\n @Column(nullable = false)\n private LocalDate dataFatal;\n \n\n\n public LocalDate getDataOcorrencia() {\n return this.dataOcorrencia;\n }\n\n public void setDataOcorrencia(LocalDate dataOcorrencia) {\n this.dataOcorrencia = dataOcorrencia;\n }\n\n\n public Advogado getResponsavel() {\n return responsavel;\n }\n\n public void setResponsavel(Advogado responsavel) {\n this.responsavel = responsavel;\n }\n\n public Processo getNumeroProcesso() {\n return numeroProcesso;\n }\n\n public void setNumeroProcesso(Processo numeroProcesso) {\n this.numeroProcesso = numeroProcesso;\n }\n\n\n public String getSituacao() {\n return this.situacao;\n }\n\n public void setSituacao(String situacao) {\n this.situacao = situacao;\n }\n\n public String getFase() {\n return this.fase;\n }\n\n public void setFase(String fase) {\n this.fase = fase;\n }\n\n public String getLocal() {\n return this.local;\n }\n\n public void setLocal(String local) {\n this.local = local;\n }\n\n public String getTipoPrazo() {\n return this.tipoPrazo;\n }\n\n public void setTipoPrazo(String tipoPrazo) {\n this.tipoPrazo = tipoPrazo;\n }\n\n public LocalDate getDataInicial() {\n return this.dataInicial;\n }\n\n public void setDataInicial(LocalDate dataInicial) {\n this.dataInicial = dataInicial;\n }\n\n public Integer getPrazo() {\n return this.prazo;\n }\n\n public void setPrazo(Integer prazo) {\n this.prazo = prazo;\n }\n\n public LocalDate getDataFatal() {\n return this.dataFatal;\n }\n\n public void setDataFatal(LocalDate dataFatal) {\n this.dataFatal = dataFatal;\n }\n\n\n @Override\n public String toString() {\n return \"Agenda{\" +\n \"dataOcorrencia=\" + dataOcorrencia +\n \", responsavel=\" + responsavel +\n \", numeroProcesso=\" + numeroProcesso +\n \", situacao='\" + situacao + '\\'' +\n \", fase='\" + fase + '\\'' +\n \", local='\" + local + '\\'' +\n \", tipoPrazo='\" + tipoPrazo + '\\'' +\n \", dataInicial=\" + dataInicial +\n \", prazo=\" + prazo +\n \", dataFatal=\" + dataFatal +\n '}';\n }\n}" }, { "identifier": "AgendaRepository", "path": "src/main/java/com/advocacia/Advocacia_Beckhauser/repositories/AgendaRepository.java", "snippet": "@Repository\npublic interface AgendaRepository extends JpaRepository <Agenda, Long> {\n\n}" } ]
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.advocacia.Advocacia_Beckhauser.models.Agenda; import com.advocacia.Advocacia_Beckhauser.repositories.AgendaRepository;
1,079
package com.advocacia.Advocacia_Beckhauser.services; @Service public class AgendaService { @Autowired
package com.advocacia.Advocacia_Beckhauser.services; @Service public class AgendaService { @Autowired
private AgendaRepository repository;
1
2023-10-24 21:35:12+00:00
2k
Space125/tasklist
src/main/java/org/kurilov/tasklist/config/SecurityConfig.java
[ { "identifier": "JwtTokenFilter", "path": "src/main/java/org/kurilov/tasklist/web/security/JwtTokenFilter.java", "snippet": "@AllArgsConstructor\n@Slf4j\npublic class JwtTokenFilter extends GenericFilterBean {\n\n private final JwtTokenProvider jwtTokenProvider;\n\n @Override\n @SneakyThrows\n public void doFilter(final ServletRequest request,\n final ServletResponse response,\n final FilterChain chain) {\n String bearerToken = ((HttpServletRequest) request).getHeader(\"Authorization\");\n String token = null;\n if (bearerToken != null && bearerToken.startsWith(\"Bearer \")) {\n token = bearerToken.substring(7);\n }\n try {\n if (token != null && jwtTokenProvider.validateToken(token)) {\n try {\n Authentication authentication = jwtTokenProvider.getAuthentication(token);\n if (authentication != null) {\n SecurityContextHolder.getContext().setAuthentication(authentication);\n }\n } catch (ResourceNotFoundException e) {\n log.error(e.getMessage());\n }\n }\n } catch (ExpiredJwtException e) {\n log.error(\"Token expired: {}\", e.getMessage());\n }\n chain.doFilter(request, response);\n }\n}" }, { "identifier": "JwtTokenProvider", "path": "src/main/java/org/kurilov/tasklist/web/security/JwtTokenProvider.java", "snippet": "@Service\n@RequiredArgsConstructor\npublic class JwtTokenProvider {\n\n private final JwtProperties jwtProperties;\n\n private final UserDetailsService userDetailsService;\n private final UserService userService;\n private SecretKey key;\n\n @PostConstruct\n public void init() {\n this.key = Keys.hmacShaKeyFor(jwtProperties.getSecretKey().getBytes());\n }\n\n public String createAccessToken(final Long userId,\n final String username,\n final Set<Role> roles) {\n Instant validity = Instant.now().plus(jwtProperties.getAccessExpiration(), ChronoUnit.HOURS);\n return Jwts.builder()\n .claims()\n .subject(username)\n .add(\"id\", userId)\n .add(\"roles\", resolveRoles(roles))\n .and()\n .expiration(Date.from(validity))\n .signWith(key)\n .compact();\n }\n\n public String createRefreshToken(final Long userId, final String username) {\n Instant validity = Instant.now().plus(jwtProperties.getRefreshExpiration(), ChronoUnit.DAYS);\n return Jwts.builder()\n .claims()\n .subject(username)\n .add(\"id\", userId)\n .and()\n .expiration(Date.from(validity))\n .signWith(key)\n .compact();\n }\n\n public JwtResponse refreshUserToken(final String refreshToken) {\n if (!validateToken(refreshToken)) {\n throw new AccessDeniedException();\n }\n Long userId = Long.valueOf(getId(refreshToken));\n User user = userService.getById(userId);\n return JwtResponse.builder()\n .id(userId)\n .username(user.getUsername())\n .accessToken(createAccessToken(userId, user.getUsername(), user.getRoles()))\n .refreshToken(createRefreshToken(userId, user.getUsername()))\n .build();\n }\n\n public Authentication getAuthentication(final String token) {\n String username = getUsername(token);\n UserDetails userDetails = userDetailsService.loadUserByUsername(username);\n return new UsernamePasswordAuthenticationToken(userDetails, \"\", userDetails.getAuthorities());\n }\n\n public boolean validateToken(final String token) {\n Jws<Claims> claims = Jwts.parser()\n .verifyWith(key)\n .build()\n .parseSignedClaims(token);\n return !claims.getPayload().getExpiration().before(new Date());\n }\n\n private String getUsername(final String token) {\n return Jwts.parser()\n .verifyWith(key)\n .build()\n .parseSignedClaims(token)\n .getPayload()\n .getSubject();\n }\n\n private String getId(final String token) {\n return Jwts.parser()\n .verifyWith(key)\n .build()\n .parseSignedClaims(token)\n .getPayload()\n .get(\"id\")\n .toString();\n }\n\n private List<String> resolveRoles(final Set<Role> roles) {\n return roles.stream()\n .map(Enum::name)\n .collect(Collectors.toList());\n }\n}" } ]
import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.security.SecurityRequirement; import io.swagger.v3.oas.models.security.SecurityScheme; import io.swagger.v3.oas.models.security.SecurityScheme.Type; import lombok.RequiredArgsConstructor; import org.kurilov.tasklist.web.security.JwtTokenFilter; import org.kurilov.tasklist.web.security.JwtTokenProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
1,312
package org.kurilov.tasklist.config; /** * @author Ivan Kurilov on 20.10.2023 */ @Configuration @EnableWebSecurity(debug = true) @EnableMethodSecurity @RequiredArgsConstructor(onConstructor = @__(@Lazy)) public class SecurityConfig {
package org.kurilov.tasklist.config; /** * @author Ivan Kurilov on 20.10.2023 */ @Configuration @EnableWebSecurity(debug = true) @EnableMethodSecurity @RequiredArgsConstructor(onConstructor = @__(@Lazy)) public class SecurityConfig {
private final JwtTokenProvider jwtTokenProvider;
1
2023-10-19 05:50:28+00:00
2k
rfresh2/2b2t.vc-rusherhack
src/main/java/vc/command/StatsCommand.java
[ { "identifier": "VcApi", "path": "src/main/java/vc/api/VcApi.java", "snippet": "public class VcApi {\n private final HttpClient httpClient;\n private final ILogger logger;\n private final Gson gson;\n\n public VcApi(final ILogger logger) {\n this.logger = logger;\n this.httpClient = HttpClient.newBuilder()\n .build();\n this.gson = new GsonBuilder()\n .registerTypeAdapter(OffsetDateTime.class, (JsonDeserializer<OffsetDateTime>) (json, typeOfT, context) -> OffsetDateTime.parse(json.getAsString()))\n .create();\n }\n\n public Optional<SeenResponse> getSeen(final PlayerReference player) {\n return get(\"https://api.2b2t.vc/seen?playerName=\" + player.name(), SeenResponse.class);\n }\n\n public Optional<PlaytimeResponse> getPlaytime(final PlayerReference player) {\n return get(\"https://api.2b2t.vc/playtime?playerName=\" + player.name(), PlaytimeResponse.class);\n }\n\n public Optional<QueueStatus> getQueueStatus() {\n return get(\"https://api.2b2t.vc/queue\", QueueStatus.class);\n }\n\n public Optional<StatsResponse> getStats(final PlayerReference player) {\n return get(\"https://api.2b2t.vc/stats/player?playerName=\" + player.name(), StatsResponse.class);\n }\n\n private <T> Optional<T> get(final String uri, final Class<T> responseType) {\n try {\n HttpRequest request = HttpRequest.newBuilder()\n .GET()\n .uri(URI.create(uri))\n .setHeader(\"User-Agent\", \"rusherhack/1.0\")\n .build();\n HttpResponse<InputStream> response = this.httpClient.send(request, ofInputStream());\n try (JsonReader reader = new JsonReader(new InputStreamReader(response.body()))) {\n return Optional.ofNullable(this.gson.fromJson(reader, responseType));\n }\n } catch (final Exception e) {\n logger.error(\"Failed querying \" + uri);\n e.printStackTrace();\n return Optional.empty();\n }\n }\n}" }, { "identifier": "formatDuration", "path": "src/main/java/vc/util/FormatUtil.java", "snippet": "public static String formatDuration(Duration duration) {\n final StringBuilder sb = new StringBuilder();\n if (duration.toDaysPart() > 0) sb.append(duration.toDaysPart()).append(\"d \");\n if (duration.toHoursPart() > 0) sb.append(duration.toHoursPart()).append(\"h \");\n if (duration.toMinutesPart() > 0) sb.append(duration.toMinutesPart()).append(\"m \");\n sb.append(duration.toSecondsPart()).append(\"s\");\n return sb.toString();\n}" }, { "identifier": "getSeenString", "path": "src/main/java/vc/util/FormatUtil.java", "snippet": "public static String getSeenString(@Nullable final OffsetDateTime time) {\n return time != null ? time.format(formatter) : \"Never\";\n}" } ]
import org.rusherhack.client.api.feature.command.Command; import org.rusherhack.client.api.feature.command.arg.PlayerReference; import org.rusherhack.client.api.utils.ChatUtils; import org.rusherhack.core.command.annotations.CommandExecutor; import vc.api.VcApi; import java.time.Duration; import java.util.concurrent.ForkJoinPool; import static vc.util.FormatUtil.formatDuration; import static vc.util.FormatUtil.getSeenString;
931
package vc.command; public class StatsCommand extends Command { private final VcApi api; public StatsCommand(final VcApi api) { super("stats", "Gets the 2b2t stats of a player"); this.api = api; } @CommandExecutor @CommandExecutor.Argument({"player"}) private String statsPlayerName(final PlayerReference player) { ForkJoinPool.commonPool().execute(() -> { var statsResponse = api.getStats(player); var out = statsResponse.map(s -> player.name() + " Stats" + "\nJoins: " + s.joinCount() + "\nLeaves: " + s.leaveCount() + "\nFirst Seen: " + getSeenString(s.firstSeen()) + "\nLast Seen: " + getSeenString(s.lastSeen()) +
package vc.command; public class StatsCommand extends Command { private final VcApi api; public StatsCommand(final VcApi api) { super("stats", "Gets the 2b2t stats of a player"); this.api = api; } @CommandExecutor @CommandExecutor.Argument({"player"}) private String statsPlayerName(final PlayerReference player) { ForkJoinPool.commonPool().execute(() -> { var statsResponse = api.getStats(player); var out = statsResponse.map(s -> player.name() + " Stats" + "\nJoins: " + s.joinCount() + "\nLeaves: " + s.leaveCount() + "\nFirst Seen: " + getSeenString(s.firstSeen()) + "\nLast Seen: " + getSeenString(s.lastSeen()) +
"\nPlaytime: " + formatDuration(Duration.ofSeconds(s.playtimeSeconds())) +
1
2023-10-22 20:22:42+00:00
2k
Dwight-Studio/JArmEmu
src/main/java/fr/dwightstudio/jarmemu/gui/factory/CursorTableCell.java
[ { "identifier": "MemoryWordView", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/view/MemoryWordView.java", "snippet": "public class MemoryWordView {\n private final MemoryAccessor memoryAccessor;\n private final ReadOnlyIntegerProperty addressProperty;\n private final IntegerProperty valueProperty;\n private final BooleanProperty cursorProperty;\n private final MemoryByteProperty byte0;\n private final MemoryByteProperty byte1;\n private final MemoryByteProperty byte2;\n private final MemoryByteProperty byte3;\n private final Register sp;\n\n public MemoryWordView(MemoryAccessor memoryAccessor, int address) {\n this.memoryAccessor = memoryAccessor;\n this.addressProperty = new ReadOnlyIntegerWrapper(address);\n this.valueProperty = memoryAccessor.getProperty(address);\n this.sp = null;\n this.byte0 = new MemoryByteProperty(0);\n this.byte1 = new MemoryByteProperty(1);\n this.byte2 = new MemoryByteProperty(2);\n this.byte3 = new MemoryByteProperty(3);\n this.cursorProperty = null;\n }\n\n public MemoryWordView(MemoryAccessor memoryAccessor, int address, Register sp) {\n this.memoryAccessor = memoryAccessor;\n this.addressProperty = new ReadOnlyIntegerWrapper(address);\n this.valueProperty = memoryAccessor.getProperty(address);\n this.sp = sp;\n this.cursorProperty = new SimpleBooleanProperty(this.sp.getData() == address);\n this.byte0 = new MemoryByteProperty(0);\n this.byte1 = new MemoryByteProperty(1);\n this.byte2 = new MemoryByteProperty(2);\n this.byte3 = new MemoryByteProperty(3);\n\n this.sp.getDataProperty().addListener((obs, oldVal, newVal) -> this.cursorProperty.setValue((int) newVal == address));\n }\n\n public MemoryAccessor getMemoryAccessor() {\n return memoryAccessor;\n }\n\n public ReadOnlyIntegerProperty getAddressProperty() {\n return addressProperty;\n }\n\n public ReadOnlyIntegerProperty getValueProperty() {\n return valueProperty;\n }\n\n public BooleanProperty getCursorProperty() {\n return cursorProperty;\n }\n\n public ReadOnlyIntegerProperty getByte0Property() {\n return byte0;\n }\n\n public ReadOnlyIntegerProperty getByte1Property() {\n return byte1;\n }\n\n public ReadOnlyIntegerProperty getByte2Property() {\n return byte2;\n }\n\n public ReadOnlyIntegerProperty getByte3Property() {\n return byte3;\n }\n\n public Register getSP() {\n return sp;\n }\n\n\n public class MemoryByteProperty extends ReadOnlyIntegerProperty {\n\n private final ArrayList<ChangeListener<? super Number>> changeListeners;\n private final ArrayList<InvalidationListener> invalidationListeners;\n\n private final int n;\n\n public MemoryByteProperty(int n) {\n this.n = 3 - n;\n if (this.n > 3 || this.n < 0) throw new IllegalArgumentException(\"n must be between 0 and 3 included\");\n changeListeners = new ArrayList<>();\n invalidationListeners = new ArrayList<>();\n\n valueProperty.addListener(((observable, oldVal, newVal) -> {\n if (getFrom(oldVal.intValue()) != getFrom(newVal.intValue())) {\n changeListeners.forEach(changeListener -> changeListener.changed(this, getFrom(oldVal.intValue()), getFrom(newVal.intValue())));\n invalidationListeners.forEach(invalidationListener -> invalidationListener.invalidated(observable));\n }\n }));\n }\n\n @Override\n public Object getBean() {\n return MemoryWordView.class;\n }\n\n @Override\n public String getName() {\n return \"memoryByte\" + n;\n }\n\n private int getFrom(int i) {\n return (i >>> (n * 8)) & 0xFF;\n }\n\n @Override\n public int get() {\n return getFrom(valueProperty.get());\n }\n\n @Override\n public void addListener(ChangeListener<? super Number> changeListener) {\n changeListeners.add(changeListener);\n }\n\n @Override\n public void removeListener(ChangeListener<? super Number> changeListener) {\n changeListeners.remove(changeListener);\n }\n\n @Override\n public void addListener(InvalidationListener invalidationListener) {\n invalidationListeners.add(invalidationListener);\n }\n\n @Override\n public void removeListener(InvalidationListener invalidationListener) {\n invalidationListeners.remove(invalidationListener);\n }\n }\n}" }, { "identifier": "CursorStringConverter", "path": "src/main/java/fr/dwightstudio/jarmemu/util/converters/CursorStringConverter.java", "snippet": "public class CursorStringConverter extends StringConverter<Boolean> {\n\n @Override\n public String toString(Boolean bool) {\n return bool ? \"➤\" : \"\";\n }\n\n @Override\n public Boolean fromString(String s) {\n return null;\n }\n}" } ]
import fr.dwightstudio.jarmemu.gui.view.MemoryWordView; import fr.dwightstudio.jarmemu.util.converters.CursorStringConverter; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.cell.TextFieldTableCell; import javafx.util.Callback;
1,574
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package fr.dwightstudio.jarmemu.gui.factory; public class CursorTableCell extends TextFieldTableCell<MemoryWordView, Boolean> { private CursorTableCell() {
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package fr.dwightstudio.jarmemu.gui.factory; public class CursorTableCell extends TextFieldTableCell<MemoryWordView, Boolean> { private CursorTableCell() {
super(new CursorStringConverter());
1
2023-10-17 18:22:09+00:00
2k
lenhathieu96/vision-camera-face-detector
android/src/main/java/com/visioncamerafacedetectorplugin/VisionCameraFaceDetectorPlugin.java
[ { "identifier": "FaceDetectionStatus", "path": "android/src/main/java/com/visioncamerafacedetectorplugin/models/FaceDetectionStatus.java", "snippet": "public enum FaceDetectionStatus{\n STANDBY,\n ERROR,\n SUCCESS\n\n}" }, { "identifier": "FaceDetectorException", "path": "android/src/main/java/com/visioncamerafacedetectorplugin/models/FaceDetectorException.java", "snippet": "public class FaceDetectorException extends Exception {\n private int errorCode;\n private String errorMessage;\n\n public FaceDetectorException(int errorCode, String errorMessage){\n this.errorCode = errorCode;\n this.errorMessage = errorMessage;\n }\n\n public int getErrorCode() {\n return errorCode;\n }\n public String getMessage() {\n return errorMessage;\n }\n\n public Map<String, Object> toHashMap() {\n Map<String, Object> hashMap = new HashMap<>();\n hashMap.put(\"code\", this.errorCode);\n hashMap.put(\"message\", this.errorMessage);\n return hashMap;\n }\n}" }, { "identifier": "FaceDirection", "path": "android/src/main/java/com/visioncamerafacedetectorplugin/models/FaceDirection.java", "snippet": "public enum FaceDirection {\n LEFT_SKEWED,\n RIGHT_SKEWED,\n FRONTAL,\n TRANSITIONING,\n UNKNOWN,\n}" } ]
import android.graphics.Bitmap; import android.media.Image; import android.util.Base64; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.tasks.Task; import com.google.android.gms.tasks.Tasks; import com.google.mlkit.vision.common.InputImage; import com.google.mlkit.vision.face.Face; import com.google.mlkit.vision.face.FaceDetection; import com.google.mlkit.vision.face.FaceDetector; import com.google.mlkit.vision.face.FaceDetectorOptions; import com.mrousavy.camera.frameprocessor.Frame; import com.mrousavy.camera.frameprocessor.FrameProcessorPlugin; import com.visioncamerafacedetectorplugin.models.FaceDetectionStatus; import com.visioncamerafacedetectorplugin.models.FaceDetectorException; import com.visioncamerafacedetectorplugin.models.FaceDirection; import java.io.ByteArrayOutputStream; import java.sql.Time; import java.time.Instant; import java.util.HashMap; import java.util.List; import java.util.Map;
646
package com.visioncamerafacedetectorplugin; public class VisionCameraFaceDetectorPlugin extends FrameProcessorPlugin { private final int MAX_DIFFERENCE = 5; private Long firstDetectedTime = 0L; private FaceDirection _prevFaceDirection = FaceDirection.UNKNOWN; Map<String, Object> resultMap = new HashMap<>(); FaceDetectorOptions faceDetectorOptions = new FaceDetectorOptions.Builder() .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE) .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL) .build(); FaceDetector faceDetector = FaceDetection.getClient(faceDetectorOptions); private void setErrorResult(FaceDetectorException error){
package com.visioncamerafacedetectorplugin; public class VisionCameraFaceDetectorPlugin extends FrameProcessorPlugin { private final int MAX_DIFFERENCE = 5; private Long firstDetectedTime = 0L; private FaceDirection _prevFaceDirection = FaceDirection.UNKNOWN; Map<String, Object> resultMap = new HashMap<>(); FaceDetectorOptions faceDetectorOptions = new FaceDetectorOptions.Builder() .setPerformanceMode(FaceDetectorOptions.PERFORMANCE_MODE_ACCURATE) .setLandmarkMode(FaceDetectorOptions.LANDMARK_MODE_ALL) .build(); FaceDetector faceDetector = FaceDetection.getClient(faceDetectorOptions); private void setErrorResult(FaceDetectorException error){
resultMap.put("status", FaceDetectionStatus.ERROR.name().toLowerCase());
0
2023-10-18 02:13:39+00:00
2k
GTNewHorizons/FarmingForEngineers
src/main/java/com/guigs44/farmingforengineers/registry/AbstractRegistry.java
[ { "identifier": "FarmingForEngineers", "path": "src/main/java/com/guigs44/farmingforengineers/FarmingForEngineers.java", "snippet": "@Mod(\n modid = FarmingForEngineers.MOD_ID,\n name = \"Farming for Engineers\",\n dependencies = \"after:mousetweaks[2.8,);after:forestry;after:agricraft\")\n// @Mod.EventBusSubscriber\npublic class FarmingForEngineers {\n\n public static final String MOD_ID = \"farmingforengineers\";\n\n @Mod.Instance(MOD_ID)\n public static FarmingForEngineers instance;\n\n @SidedProxy(\n clientSide = \"com.guigs44.farmingforengineers.client.ClientProxy\",\n serverSide = \"com.guigs44.farmingforengineers.CommonProxy\")\n public static CommonProxy proxy;\n\n public static final Logger logger = LogManager.getLogger();\n\n public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) {\n\n @Override\n public Item getTabIconItem() {\n return Item.getItemFromBlock(FarmingForEngineers.blockMarket);\n }\n };\n\n public static File configDir;\n\n public static Block blockMarket;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n configDir = new File(event.getModConfigurationDirectory(), \"FarmingForEngineers\");\n if (!configDir.exists() && !configDir.mkdirs()) {\n throw new RuntimeException(\"Couldn't create Farming for Engineers configuration directory\");\n }\n\n Configuration config = new Configuration(new File(configDir, \"FarmingForEngineers.cfg\"));\n config.load();\n ModConfig.preInit(config);\n\n proxy.preInit(event);\n\n if (config.hasChanged()) {\n config.save();\n }\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n NetworkHandler.init();\n NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler());\n\n new VanillaAddon();\n buildSoftDependProxy(Compat.HARVESTCRAFT, \"com.guigs44.farmingforengineers.compat.HarvestcraftAddon\");\n buildSoftDependProxy(Compat.FORESTRY, \"com.guigs44.farmingforengineers.compat.ForestryAddon\");\n buildSoftDependProxy(Compat.AGRICRAFT, \"com.guigs44.farmingforengineers.compat.AgriCraftAddon\");\n buildSoftDependProxy(Compat.BIOMESOPLENTY, \"com.guigs44.farmingforengineers.compat.BiomesOPlentyAddon\");\n buildSoftDependProxy(Compat.NATURA, \"com.guigs44.farmingforengineers.compat.NaturaAddon\");\n\n ModRecipes.init();\n MarketRegistry.INSTANCE.load(configDir);\n\n EntityRegistry.registerModEntity(EntityMerchant.class, \"merchant\", 0, this, 64, 3, true);\n\n proxy.init(event);\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {}\n\n @Mod.EventHandler\n public void serverStarting(FMLServerStartingEvent event) {\n event.registerServerCommand(new CommandFarmingForEngineers());\n }\n\n // @SubscribeEvent\n // public static void registerBlocks(RegistryEvent.Register<Block> event) {\n // event.getRegistry().registerAll((ModBlocks.market = new BlockMarket()));\n // }\n\n // @SubscribeEvent\n // public static void registerItems(RegistryEvent.Register<Item> event) {\n // event.getRegistry().registerAll(new\n // ItemBlock(ModBlocks.market).setRegistryName(ModBlocks.market.getRegistryName()));\n // }\n\n @SubscribeEvent\n public void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) {\n if (AbstractRegistry.registryErrors.size() > 0) {\n event.player.addChatMessage(\n ChatComponentBuilder.of(\"There were errors loading the Farming for Engineers registries:\").build());\n for (String error : AbstractRegistry.registryErrors) {\n event.player.addChatMessage(ChatComponentBuilder.of(\"* \" + error).build());\n }\n }\n }\n\n private Optional<?> buildSoftDependProxy(String modId, String className) {\n if (Loader.isModLoaded(modId)) {\n try {\n Class<?> clz = Class.forName(className, true, Loader.instance().getModClassLoader());\n return Optional.ofNullable(clz.newInstance());\n } catch (Exception e) {\n return Optional.empty();\n }\n }\n return Optional.empty();\n }\n}" }, { "identifier": "ModConfig", "path": "src/main/java/com/guigs44/farmingforengineers/ModConfig.java", "snippet": "public class ModConfig {\n\n public static boolean showRegistryWarnings;\n\n public static void preInit(Configuration config) {\n showRegistryWarnings = config.getBoolean(\n \"Show Registry Warnings\",\n \"client\",\n false,\n \"Set this to true if you're a modpack dev to see Farming for Engineers registry warnings in chat. Errors will always display.\");\n }\n}" } ]
import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.List; import net.minecraft.util.ResourceLocation; import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.guigs44.farmingforengineers.FarmingForEngineers; import com.guigs44.farmingforengineers.ModConfig;
1,474
package com.guigs44.farmingforengineers.registry; public abstract class AbstractRegistry { public static List<String> registryErrors = Lists.newArrayList(); protected final String registryName; private boolean hasChanged; private boolean refuseSave; public AbstractRegistry(String registryName) { this.registryName = registryName; } public final void load(File configDir) { clear(); Gson gson = new Gson(); File configFile = new File(configDir, registryName + ".json"); if (!configFile.exists()) { try (JsonWriter jsonWriter = new JsonWriter(new FileWriter(configFile))) { jsonWriter.setIndent(" "); gson.toJson(create(), jsonWriter); } catch (IOException e) {
package com.guigs44.farmingforengineers.registry; public abstract class AbstractRegistry { public static List<String> registryErrors = Lists.newArrayList(); protected final String registryName; private boolean hasChanged; private boolean refuseSave; public AbstractRegistry(String registryName) { this.registryName = registryName; } public final void load(File configDir) { clear(); Gson gson = new Gson(); File configFile = new File(configDir, registryName + ".json"); if (!configFile.exists()) { try (JsonWriter jsonWriter = new JsonWriter(new FileWriter(configFile))) { jsonWriter.setIndent(" "); gson.toJson(create(), jsonWriter); } catch (IOException e) {
FarmingForEngineers.logger.error("Failed to create default {} registry: {}", registryName, e);
0
2023-10-17 00:25:50+00:00
2k
mnesimiyilmaz/sql4json
src/main/java/io/github/mnesimiyilmaz/sql4json/grouping/GroupByInput.java
[ { "identifier": "CriteriaNode", "path": "src/main/java/io/github/mnesimiyilmaz/sql4json/condition/CriteriaNode.java", "snippet": "public interface CriteriaNode {\n\n boolean test(Map<FieldKey, Object> row);\n\n}" }, { "identifier": "JsonColumnWithNonAggFunctionDefinion", "path": "src/main/java/io/github/mnesimiyilmaz/sql4json/definitions/JsonColumnWithNonAggFunctionDefinion.java", "snippet": "@Getter\npublic class JsonColumnWithNonAggFunctionDefinion {\n\n private final SQL4JsonParser.JsonColumnWithNonAggFunctionContext columnContext;\n private final String columnName;\n private final Function<Object, Object> valueDecorator;\n\n public JsonColumnWithNonAggFunctionDefinion(SQL4JsonParser.JsonColumnWithNonAggFunctionContext columnContext) {\n this.columnContext = columnContext;\n this.columnName = columnContext.jsonColumn().getText();\n if (columnContext.NON_AGG_FUNCTION() != null) {\n List<Object> args = new ArrayList<>();\n if (columnContext.params() != null && columnContext.params().value() != null) {\n List<SQL4JsonParser.ValueContext> valueContexts = columnContext.params().value();\n for (SQL4JsonParser.ValueContext valueContext : valueContexts) {\n args.add(ValueUtils.getValueFromContext(valueContext));\n }\n }\n this.valueDecorator = in -> ParameterizedFunctionUtils.getFunction(\n columnContext.NON_AGG_FUNCTION().getText().toLowerCase()).apply(in, args);\n } else {\n this.valueDecorator = null;\n }\n }\n\n public Optional<Function<Object, Object>> getValueDecorator() {\n return Optional.ofNullable(valueDecorator);\n }\n\n}" }, { "identifier": "SelectColumnDefinition", "path": "src/main/java/io/github/mnesimiyilmaz/sql4json/definitions/SelectColumnDefinition.java", "snippet": "@Getter\npublic class SelectColumnDefinition {\n\n private final SQL4JsonParser.SelectColumnContext ctx;\n private final JsonColumnWithAggFunctionDefinion columnDefinition;\n private final String alias;\n private final boolean isAsterisk;\n\n private SelectColumnDefinition() {\n this.ctx = null;\n this.columnDefinition = null;\n this.alias = null;\n this.isAsterisk = true;\n }\n\n public SelectColumnDefinition(SQL4JsonParser.SelectColumnContext ctx) {\n this.ctx = ctx;\n this.columnDefinition = new JsonColumnWithAggFunctionDefinion(ctx.jsonColumnWithAggFunction());\n if (ctx.AS() != null) {\n this.alias = ctx.jsonColumn().getText();\n } else {\n this.alias = null;\n }\n this.isAsterisk = false;\n }\n\n public static SelectColumnDefinition ofAsterisk() {\n return new SelectColumnDefinition();\n }\n\n}" }, { "identifier": "FieldKey", "path": "src/main/java/io/github/mnesimiyilmaz/sql4json/utils/FieldKey.java", "snippet": "@Getter\npublic class FieldKey {\n\n private final String key;\n private final String family;\n\n public FieldKey(String key, String family) {\n Objects.requireNonNull(key);\n this.key = key;\n this.family = family;\n }\n\n public FieldKey(String key) {\n this(key, null);\n }\n\n public static FieldKey of(String key, String family) {\n return new FieldKey(key, family);\n }\n\n public static FieldKey of(String key) {\n return new FieldKey(key);\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 FieldKey fieldKey = (FieldKey) o;\n return Objects.equals(key, fieldKey.key);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(key);\n }\n\n}" } ]
import io.github.mnesimiyilmaz.sql4json.condition.CriteriaNode; import io.github.mnesimiyilmaz.sql4json.definitions.JsonColumnWithNonAggFunctionDefinion; import io.github.mnesimiyilmaz.sql4json.definitions.SelectColumnDefinition; import io.github.mnesimiyilmaz.sql4json.utils.FieldKey; import lombok.Getter; import lombok.RequiredArgsConstructor; import java.util.List; import java.util.Map;
1,083
package io.github.mnesimiyilmaz.sql4json.grouping; /** * @author mnesimiyilmaz */ @Getter @RequiredArgsConstructor public class GroupByInput { private final List<Map<FieldKey, Object>> flattenedInputJsonNode; private final List<SelectColumnDefinition> selectedColumns;
package io.github.mnesimiyilmaz.sql4json.grouping; /** * @author mnesimiyilmaz */ @Getter @RequiredArgsConstructor public class GroupByInput { private final List<Map<FieldKey, Object>> flattenedInputJsonNode; private final List<SelectColumnDefinition> selectedColumns;
private final List<JsonColumnWithNonAggFunctionDefinion> groupByColumns;
1
2023-10-24 18:34:33+00:00
2k
AkramLZ/ServerSync
serversync-common/src/main/java/me/akraml/serversync/broker/RabbitMqMessageBrokerService.java
[ { "identifier": "ConnectionResult", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/ConnectionResult.java", "snippet": "public enum ConnectionResult {\n\n /**\n * Indicates a successful connection.\n */\n SUCCESS,\n\n /**\n * Indicates a failed connection.\n */\n FAILURE\n\n}" }, { "identifier": "AuthenticatedConnection", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/auth/AuthenticatedConnection.java", "snippet": "public interface AuthenticatedConnection<C> extends Connection<C> {\n\n /**\n * Retrieves the credentials used for authentication.\n *\n * @return The connection credentials.\n */\n ConnectionCredentials getCredentials();\n\n}" }, { "identifier": "ConnectionCredentials", "path": "serversync-common/src/main/java/me/akraml/serversync/connection/auth/ConnectionCredentials.java", "snippet": "public final class ConnectionCredentials {\n\n private final Map<CredentialsKey, Object> keyMap = new HashMap<>();\n\n /**\n * Constructor must be private to disallow external initialization.\n */\n private ConnectionCredentials() {\n }\n\n /**\n * Retrieves the value associated with the specified key and casts it to the specified type.\n *\n * @param key The key of the property.\n * @param typeClass The class representing the type of the property.\n * @param <T> The type of the property.\n * @return The value associated with the key, cast to the specified type.\n * @throws ConnectionAuthenticationException if the key is missing in the credentials.\n * @throws ClassCastException if the type is not the same as the key.\n */\n public <T> T getProperty(final CredentialsKey key,\n final Class<T> typeClass) {\n if (!keyMap.containsKey(key)) {\n throw new ConnectionAuthenticationException(\"Missing key=\" + key);\n }\n Object keyObject = keyMap.get(key);\n return typeClass.cast(keyObject);\n }\n\n /**\n * Creates a new instance of the ConnectionCredentials.Builder.\n *\n * @return A new instance of the ConnectionCredentials.Builder.\n */\n public static Builder newBuilder() {\n return new Builder();\n }\n\n /**\n * A builder class for constructing ConnectionCredentials objects.\n */\n public static final class Builder {\n\n private final ConnectionCredentials credentials;\n\n private Builder() {\n this.credentials = new ConnectionCredentials();\n }\n\n /**\n * Adds a key-value pair to the connection credentials.\n *\n * @param key The key of the credential.\n * @param value The value of the credential.\n * @return The Builder instance.\n */\n public Builder addKey(final CredentialsKey key,\n final Object value) {\n credentials.keyMap.put(key, value);\n return this;\n }\n\n /**\n * Builds and returns the ConnectionCredentials object.\n *\n * @return The constructed ConnectionCredentials object.\n */\n public ConnectionCredentials build() {\n return credentials;\n }\n\n }\n\n}" }, { "identifier": "ServersManager", "path": "serversync-common/src/main/java/me/akraml/serversync/server/ServersManager.java", "snippet": "public abstract class ServersManager {\n\n /** Timer to schedule and manage the heartbeat task. */\n private final Timer timer = new Timer();\n\n /** Map storing the servers using their names as the key. */\n private final Map<String, ServerImpl> servers = new HashMap<>();\n\n /** Integers for heartbeat task delay and maximum time to remove the server. */\n protected int heartbeatSchedulerDelay, maxAliveTime;\n\n /**\n * Starts a recurring task to check servers for their heartbeat signal.\n * Servers that haven't sent a heartbeat signal within the last 30 seconds will be removed.\n */\n public final void startHeartbeatTask() {\n timer.scheduleAtFixedRate(new TimerTask() {\n @Override\n public void run() {\n final List<ServerImpl> toRemove = new ArrayList<>();\n servers.values().forEach(server -> {\n if (System.currentTimeMillis() - server.getLastHeartbeat() > maxAliveTime) {\n toRemove.add(server);\n }\n });\n toRemove.forEach(ServersManager.this::removeServer);\n toRemove.clear();\n }\n }, 0L, Duration.ofSeconds(heartbeatSchedulerDelay).toMillis());\n }\n\n /**\n * Retrieves a server instance by its name.\n *\n * @param name The name of the server.\n * @return The server instance or null if not found.\n */\n public final Server getServer(String name) {\n return this.servers.get(name);\n }\n\n /**\n * Adds a server to the managed collection of servers.\n *\n * @param server The server to be added.\n */\n public final void addServer(Server server) {\n this.servers.put(server.getName(), (ServerImpl) server);\n registerInProxy(server);\n }\n\n /**\n * Removes a server from the managed collection of servers.\n * Also, triggers an unregister action specific to the proxy.\n *\n * @param server The server to be removed.\n */\n public final void removeServer(Server server) {\n unregisterFromProxy(server);\n this.servers.remove(server.getName());\n }\n\n /**\n * Abstract method that should be implemented to unregister a server from the associated proxy.\n *\n * @param server The server to be unregistered from the proxy.\n */\n protected abstract void unregisterFromProxy(Server server);\n\n /**\n * Abstract method that should be implemented to register a server in the proxy server.\n *\n * @param server The server to be registered in the proxy.\n */\n protected abstract void registerInProxy(Server server);\n}" } ]
import com.google.gson.JsonObject; import com.rabbitmq.client.Connection; import me.akraml.serversync.connection.ConnectionResult; import me.akraml.serversync.connection.auth.AuthenticatedConnection; import me.akraml.serversync.connection.auth.ConnectionCredentials; import me.akraml.serversync.server.ServersManager;
1,576
package me.akraml.serversync.broker; /** * A concrete implementation of the {@link MessageBrokerService} that utilizes RabbitMQ as the message broker backend. * This class is just like {@link RedisMessageBrokerService}, but the main difference is the software which handles * messages. * * TODO Implement RabbitMQ Message broker service. */ public class RabbitMqMessageBrokerService extends MessageBrokerService implements AuthenticatedConnection<Connection> { public RabbitMqMessageBrokerService(ServersManager serversManager) { super(serversManager); } @Override public void startHandler() { } @Override public void stop() { } @Override public void publish(JsonObject message) { } @Override
package me.akraml.serversync.broker; /** * A concrete implementation of the {@link MessageBrokerService} that utilizes RabbitMQ as the message broker backend. * This class is just like {@link RedisMessageBrokerService}, but the main difference is the software which handles * messages. * * TODO Implement RabbitMQ Message broker service. */ public class RabbitMqMessageBrokerService extends MessageBrokerService implements AuthenticatedConnection<Connection> { public RabbitMqMessageBrokerService(ServersManager serversManager) { super(serversManager); } @Override public void startHandler() { } @Override public void stop() { } @Override public void publish(JsonObject message) { } @Override
public ConnectionResult connect() {
0
2023-10-21 12:47:58+00:00
2k
neftalito/R-Info-Plus
arbol/sentencia/primitiva/LiberarEsquina.java
[ { "identifier": "Expresion", "path": "arbol/expresion/Expresion.java", "snippet": "public abstract class Expresion extends AST {\n public DeclaracionVariable DV;\n public Tipo T;\n public Identificador I;\n public Robot r;\n\n public DeclaracionVariable getDV() {\n return this.DV;\n }\n\n public void setDV(final DeclaracionVariable DV) {\n this.DV = DV;\n }\n\n public Identificador getI() {\n return this.I;\n }\n\n public void setI(final Identificador I) {\n this.I = I;\n }\n\n public boolean ejecutar() {\n return true;\n }\n\n public String getValue(final DeclaracionVariable DV) throws Exception {\n return \"undefinedd\";\n }\n\n public Tipo getT() {\n return this.T;\n }\n\n public void setT(final Tipo T) {\n this.T = T;\n }\n\n public Robot getRobot() {\n return this.r;\n }\n\n public void setRobot(final Robot r) {\n this.r = r;\n }\n\n @Override\n public abstract Object clone() throws CloneNotSupportedException;\n}" }, { "identifier": "DeclaracionVariable", "path": "arbol/DeclaracionVariable.java", "snippet": "public class DeclaracionVariable extends AST {\n public ArrayList<Variable> variables;\n\n public DeclaracionVariable(final ArrayList<Variable> var) {\n this.variables = var;\n }\n\n public void imprimir() {\n for (final Variable variable : this.variables) {\n System.out.println(variable.getI().toString());\n }\n }\n\n public boolean EstaParametro(final String act) throws Exception {\n int i;\n for (i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n if (i == this.variables.size()) {\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n return false;\n }\n\n public boolean EstaVariable(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public void reportError(final String str) {\n JOptionPane.showMessageDialog(null, str, \"ERROR\", 0);\n }\n\n public Variable findByName(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().toString().equals(act)) {\n return this.variables.get(i);\n }\n }\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n}" } ]
import java.util.logging.Level; import java.util.logging.Logger; import arbol.expresion.Expresion; import arbol.DeclaracionVariable;
807
package arbol.sentencia.primitiva; public class LiberarEsquina extends Primitiva { int ciclo; private int Av; private int Ca;
package arbol.sentencia.primitiva; public class LiberarEsquina extends Primitiva { int ciclo; private int Av; private int Ca;
DeclaracionVariable DV;
1
2023-10-20 15:45:37+00:00
2k
wevez/ClientCoderPack
src/tech/tenamen/client/Asset.java
[ { "identifier": "Main", "path": "src/tech/tenamen/Main.java", "snippet": "public class Main {\n public static IDE IDE = new InteliJIDE();\n public static Client client;\n\n public static File WORKING_DIR = new File(System.getProperty(\"user.dir\")),\n ASSETS_DIR = new File(WORKING_DIR, \"assets\"),\n LIBRARIES_DIR = new File(WORKING_DIR, \"libraries\"),\n OBJECTS_DIR = new File(ASSETS_DIR, \"objects\"),\n INDEXES_DIR = new File(ASSETS_DIR, \"indexes\"),\n SRC_DIR = new File(WORKING_DIR, \"src\"),\n NATIVES_DIR = new File(LIBRARIES_DIR, \"natives\");\n\n public static void main(String[] main) throws Exception {\n final Scanner scanner = new Scanner(System.in);\n System.out.println(\"ClientCoderPack\");\n System.out.print(\"Version<<\");\n final File versionFile = new File(String.format(\"%s\\\\.minecraft\\\\versions\\\\%s\", System.getenv(\"APPDATA\"), scanner.next()));\n if (!versionFile.exists()) {\n System.out.printf(\"File %s not found%n\", versionFile.getAbsolutePath());\n return;\n }\n ASSETS_DIR.mkdirs();\n LIBRARIES_DIR.mkdirs();\n OBJECTS_DIR.mkdirs();\n INDEXES_DIR.mkdirs();\n SRC_DIR.mkdirs();\n NATIVES_DIR.mkdirs();\n client = new Client(versionFile);\n System.out.println(\"Downloading dependencies\");\n client.parseDependencies();\n client.download(getOs());\n System.out.println(\"Making IDE property file\");\n IDE.createProperties();\n System.out.println(\"Process has finished!\");\n\n }\n\n private static OS getOs() {\n final String OS_NAME = System.getProperty(\"os.name\").toLowerCase();\n if (OS_NAME.startsWith(\"linux\")) return OS.LINUX;\n if (OS_NAME.startsWith(\"mac\")) return OS.MAC;\n return OS.WINDOWS;\n }\n\n}" }, { "identifier": "OS", "path": "src/tech/tenamen/property/OS.java", "snippet": "public enum OS {\n\n WINDOWS(\"windows\", \"natives-windows\"),\n MAC(\"osx\", \"natives-macos\"),\n LINUX(\"linux\", \"natives-linux\");\n\n private final String OS_RULE_NAME, NATIVE_OS_NAME;\n\n OS(final String OS_RULE_NAME, final String NATIVE_OS_NAME) {\n this.OS_RULE_NAME = OS_RULE_NAME;\n this.NATIVE_OS_NAME = NATIVE_OS_NAME;\n }\n\n public String toOsRule() { return OS_RULE_NAME; }\n public String toNativeOs() { return NATIVE_OS_NAME; }\n}" }, { "identifier": "NetUtil", "path": "src/tech/tenamen/util/NetUtil.java", "snippet": "public class NetUtil {\n\n public static boolean checkExist(final File file, final long size) {\n return file.length() == size;\n }\n\n public static void download(final String urly, final File file) {\n System.out.printf(\"Downloading %s -> %s\\n\", urly, file.getAbsolutePath());\n try {\n URL url = new URL(urly);\n final HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setAllowUserInteraction(false);\n conn.setInstanceFollowRedirects(true);\n conn.setRequestMethod(\"GET\");\n conn.connect();\n int httpStatusCode = conn.getResponseCode();\n if (httpStatusCode != HttpURLConnection.HTTP_OK) {\n throw new Exception(\"HTTP Status \" + httpStatusCode);\n }\n final DataInputStream dataInStream = new DataInputStream(conn.getInputStream());\n final DataOutputStream dataOutStream = new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(file.toPath())));\n final byte[] b = new byte[4096];\n int readByte = 0;\n while (-1 != (readByte = dataInStream.read(b))) {\n dataOutStream.write(b, 0, readByte);\n }\n dataInStream.close();\n dataOutStream.close();\n } catch (final Exception e) {\n e.printStackTrace();\n }\n }\n\n public static String download(final String urly) {\n final StringBuilder buffer = new StringBuilder();\n URL url;\n try {\n url = new URL(urly);\n final HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n final InputStreamReader reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8);\n final BufferedReader in = new BufferedReader(reader);\n String line = null;\n while ((line = in.readLine()) != null) {\n buffer.append(line);\n buffer.append('\\n');\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return buffer.toString();\n }\n\n public static String clip(String target, String first, String last) {\n final int startIndex = target.indexOf(first) + first.length();\n return target.substring(startIndex, target.indexOf(last, startIndex));\n }\n\n public static String clip(String target, String first, int last) {\n final int startIndex = target.indexOf(first) + first.length();\n return target.substring(startIndex, last);\n }\n\n}" } ]
import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import tech.tenamen.Main; import tech.tenamen.property.OS; import tech.tenamen.util.NetUtil; import java.io.File; import java.io.StringReader; import java.util.ArrayList; import java.util.List;
1,349
package tech.tenamen.client; public class Asset implements Downloadable { private final String ID; private final String SHA1; private final long SIZE; private final long TOTAL_SIZE; private final String URL; public Asset(final String ID, final String SHA1, final long SIZE, final long TOTAL_SIZE, final String URL) { this.ID = ID; this.SHA1 = SHA1; this.SIZE = SIZE; this.TOTAL_SIZE = TOTAL_SIZE; this.URL = URL; } @Override public void download(OS os) { JsonObject object = null;
package tech.tenamen.client; public class Asset implements Downloadable { private final String ID; private final String SHA1; private final long SIZE; private final long TOTAL_SIZE; private final String URL; public Asset(final String ID, final String SHA1, final long SIZE, final long TOTAL_SIZE, final String URL) { this.ID = ID; this.SHA1 = SHA1; this.SIZE = SIZE; this.TOTAL_SIZE = TOTAL_SIZE; this.URL = URL; } @Override public void download(OS os) { JsonObject object = null;
object = new GsonBuilder().setPrettyPrinting().create().fromJson(new StringReader(NetUtil.download(this.URL)), JsonObject.class);
2
2023-10-20 06:56:19+00:00
2k
Invadermonky/Omniwand
src/main/java/com/invadermonky/omniwand/handlers/MouseEventOW.java
[ { "identifier": "Omniwand", "path": "src/main/java/com/invadermonky/omniwand/Omniwand.java", "snippet": "@Mod(\n modid = Omniwand.MOD_ID,\n name = Omniwand.MOD_NAME,\n version = Omniwand.MOD_VERSION,\n acceptedMinecraftVersions = Omniwand.MC_VERSION,\n guiFactory = Omniwand.GUI_FACTORY\n)\npublic class Omniwand {\n public static final String MOD_ID = \"omniwand\";\n public static final String MOD_NAME = \"Omniwand\";\n public static final String MOD_VERSION = \"1.12.2-1.0.1\";\n public static final String GUI_FACTORY = \"com.invadermonky.omniwand.client.GuiFactory\";\n public static final String MC_VERSION = \"[1.12.2]\";\n\n public static final String ProxyClientClass = \"com.invadermonky.omniwand.proxy.ClientProxy\";\n public static final String ProxyServerClass = \"com.invadermonky.omniwand.proxy.CommonProxy\";\n\n public static SimpleNetworkWrapper network;\n\n @Mod.Instance(MOD_ID)\n public static Omniwand INSTANCE;\n\n @SidedProxy(clientSide = ProxyClientClass, serverSide = ProxyServerClass)\n public static CommonProxy proxy;\n\n @Mod.EventHandler\n public void preInit(FMLPreInitializationEvent event) {\n LogHelper.info(\"Starting Omniwand.\");\n\n //Config and config event subscriber\n ConfigHandler.preInit();\n MinecraftForge.EVENT_BUS.register(new ConfigHandler());\n\n proxy.preInit(event);\n LogHelper.debug(\"Finished preInit phase.\");\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n proxy.init(event);\n LogHelper.debug(\"Finished init phase.\");\n }\n\n @Mod.EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n LogHelper.debug(\"Finished postInit phase.\");\n }\n}" }, { "identifier": "MessageWandTransform", "path": "src/main/java/com/invadermonky/omniwand/network/MessageWandTransform.java", "snippet": "public class MessageWandTransform implements IMessage {\n public ItemStack stack;\n public int slot;\n\n public MessageWandTransform() {}\n\n public MessageWandTransform(ItemStack stack, int slot) {\n this.stack = stack;\n this.slot = slot;\n }\n\n @Override\n public void fromBytes(ByteBuf buf) {\n stack = ByteBufUtils.readItemStack(buf);\n slot = buf.readInt();\n }\n\n @Override\n public void toBytes(ByteBuf buf) {\n ByteBufUtils.writeItemStack(buf, stack);\n buf.writeInt(slot);\n }\n\n public static class MsgHandler implements IMessageHandler<MessageWandTransform,IMessage> {\n @Override\n public IMessage onMessage(MessageWandTransform message, MessageContext ctx) {\n EntityPlayer player = ctx.getServerHandler().player;\n ItemStack heldItem = player.getHeldItem(ConfigHandler.getConfiguredHand());\n\n if(TransformHandler.isOmniwand(heldItem) && message.stack != heldItem && !ItemStack.areItemsEqual(message.stack, heldItem))\n player.setHeldItem(ConfigHandler.getConfiguredHand(), message.stack);\n\n return null;\n }\n }\n}" }, { "identifier": "RayTracer", "path": "src/main/java/com/invadermonky/omniwand/util/RayTracer.java", "snippet": "public class RayTracer {\n public static RayTraceResult retrace(EntityPlayer player) {\n Vec3d startVec = getStartVec(player);\n Vec3d endVec = getEndVec(player, getBlockReachDistance(player));\n return player.world.rayTraceBlocks(startVec, endVec, true, false, true);\n }\n\n public static Vec3d getStartVec(EntityPlayer player) {\n return new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ);\n }\n\n public static Vec3d getEndVec(EntityPlayer player, double reach) {\n Vec3d headVec = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ);\n Vec3d lookVec = player.getLook(1.0F);\n return headVec.add(lookVec.x * reach, lookVec.y * reach, lookVec.z * reach);\n }\n\n public static double getBlockReachDistance(EntityPlayer player) {\n return player.world.isRemote ? getBlockReachDistanceClient() : player instanceof EntityPlayerMP ? getBlockReachDistanceServer((EntityPlayerMP) player) : 5D;\n }\n\n private static double getBlockReachDistanceServer(EntityPlayerMP player) {\n return player.getEntityAttribute(EntityPlayer.REACH_DISTANCE).getAttributeValue();\n }\n\n @SideOnly(Side.CLIENT)\n private static double getBlockReachDistanceClient() {\n return Minecraft.getMinecraft().playerController.getBlockReachDistance();\n }\n}" } ]
import com.invadermonky.omniwand.Omniwand; import com.invadermonky.omniwand.network.MessageWandTransform; import com.invadermonky.omniwand.util.RayTracer; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.item.ItemStack; import net.minecraft.util.math.RayTraceResult; import net.minecraftforge.client.event.MouseEvent; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly;
1,390
package com.invadermonky.omniwand.handlers; @SideOnly(Side.CLIENT) public class MouseEventOW { public static final MouseEventOW INSTANCE = new MouseEventOW(); @SubscribeEvent(priority = EventPriority.HIGHEST) public void onMouseEvent(MouseEvent event) { EntityPlayerSP playerSP = Minecraft.getMinecraft().player; ItemStack heldItem = playerSP.getHeldItem(ConfigHandler.getConfiguredHand()); if(TransformHandler.isOmniwand(heldItem)) { ItemStack newStack = heldItem;
package com.invadermonky.omniwand.handlers; @SideOnly(Side.CLIENT) public class MouseEventOW { public static final MouseEventOW INSTANCE = new MouseEventOW(); @SubscribeEvent(priority = EventPriority.HIGHEST) public void onMouseEvent(MouseEvent event) { EntityPlayerSP playerSP = Minecraft.getMinecraft().player; ItemStack heldItem = playerSP.getHeldItem(ConfigHandler.getConfiguredHand()); if(TransformHandler.isOmniwand(heldItem)) { ItemStack newStack = heldItem;
RayTraceResult result = RayTracer.retrace(playerSP);
2
2023-10-16 00:48:26+00:00
2k