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 |
|---|---|---|---|---|---|---|---|---|---|---|
myzticbean/QSFindItemAddOn | src/main/java/io/myzticbean/finditemaddon/QuickShopHandler/QSApi.java | [
{
"identifier": "FoundShopItemModel",
"path": "src/main/java/io/myzticbean/finditemaddon/Models/FoundShopItemModel.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic class FoundShopItemModel {\n private final double shopPrice;\n private final int remainingStockOrSpace;\n private final UUID... | import io.myzticbean.finditemaddon.Models.FoundShopItemModel;
import io.myzticbean.finditemaddon.Models.ShopSearchActivityModel;
import io.myzticbean.finditemaddon.Utils.LoggerUtils;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.Collections;
import java.util.Comparator;
import java.util.List; | 1,169 | package io.myzticbean.finditemaddon.QuickShopHandler;
/**
* Interface for QS API.
* Implement it depending on which API is being used (Reremake/Hikari).
* @param <QSType>
* @param <Shop>
* @author ronsane
*/
public interface QSApi<QSType, Shop> {
/**
* Search based on Item Type from all server shops
* @param item
* @param toBuy
* @param searchingPlayer
* @return
*/
List<FoundShopItemModel> findItemBasedOnTypeFromAllShops(ItemStack item, boolean toBuy, Player searchingPlayer);
/**
* Search based on display name of item from all server shops
* @param displayName
* @param toBuy
* @param searchingPlayer
* @return
*/
List<FoundShopItemModel> findItemBasedOnDisplayNameFromAllShops(String displayName, boolean toBuy, Player searchingPlayer);
/**
* Fetch all items from all server shops
* @param toBuy
* @param searchingPlayer
* @return
*/
List<FoundShopItemModel> fetchAllItemsFromAllShops(boolean toBuy, Player searchingPlayer);
Material getShopSignMaterial();
Shop findShopAtLocation(Block block);
boolean isShopOwnerCommandRunner(Player player, Shop shop);
List<Shop> getAllShops();
List<ShopSearchActivityModel> syncShopsListForStorage(List<ShopSearchActivityModel> globalShopsList);
void registerSubCommand();
static List<FoundShopItemModel> sortShops(int sortingMethod, List<FoundShopItemModel> shopsFoundList) {
switch (sortingMethod) {
// Random
case 1 -> Collections.shuffle(shopsFoundList);
// Based on prices (lower to higher)
case 2 -> shopsFoundList.sort(Comparator.comparing(FoundShopItemModel::getShopPrice));
// Based on stocks (higher to lower)
case 3 -> {
shopsFoundList.sort(Comparator.comparing(FoundShopItemModel::getRemainingStockOrSpace));
Collections.reverse(shopsFoundList);
}
default -> { | package io.myzticbean.finditemaddon.QuickShopHandler;
/**
* Interface for QS API.
* Implement it depending on which API is being used (Reremake/Hikari).
* @param <QSType>
* @param <Shop>
* @author ronsane
*/
public interface QSApi<QSType, Shop> {
/**
* Search based on Item Type from all server shops
* @param item
* @param toBuy
* @param searchingPlayer
* @return
*/
List<FoundShopItemModel> findItemBasedOnTypeFromAllShops(ItemStack item, boolean toBuy, Player searchingPlayer);
/**
* Search based on display name of item from all server shops
* @param displayName
* @param toBuy
* @param searchingPlayer
* @return
*/
List<FoundShopItemModel> findItemBasedOnDisplayNameFromAllShops(String displayName, boolean toBuy, Player searchingPlayer);
/**
* Fetch all items from all server shops
* @param toBuy
* @param searchingPlayer
* @return
*/
List<FoundShopItemModel> fetchAllItemsFromAllShops(boolean toBuy, Player searchingPlayer);
Material getShopSignMaterial();
Shop findShopAtLocation(Block block);
boolean isShopOwnerCommandRunner(Player player, Shop shop);
List<Shop> getAllShops();
List<ShopSearchActivityModel> syncShopsListForStorage(List<ShopSearchActivityModel> globalShopsList);
void registerSubCommand();
static List<FoundShopItemModel> sortShops(int sortingMethod, List<FoundShopItemModel> shopsFoundList) {
switch (sortingMethod) {
// Random
case 1 -> Collections.shuffle(shopsFoundList);
// Based on prices (lower to higher)
case 2 -> shopsFoundList.sort(Comparator.comparing(FoundShopItemModel::getShopPrice));
// Based on stocks (higher to lower)
case 3 -> {
shopsFoundList.sort(Comparator.comparing(FoundShopItemModel::getRemainingStockOrSpace));
Collections.reverse(shopsFoundList);
}
default -> { | LoggerUtils.logError("Invalid value in config.yml : 'shop-sorting-method'"); | 2 | 2023-11-22 11:36:01+00:00 | 2k |
DIDA-lJ/qiyao-12306 | services/user-service/src/main/java/org/opengoofy/index12306/biz/userservice/controller/UserLoginController.java | [
{
"identifier": "UserLoginReqDTO",
"path": "services/user-service/src/main/java/org/opengoofy/index12306/biz/userservice/dto/req/UserLoginReqDTO.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UserLoginReqDTO {\n\n /**\n * 用户名\n */\n private String usernameO... | import lombok.RequiredArgsConstructor;
import org.opengoofy.index12306.biz.userservice.dto.req.UserLoginReqDTO;
import org.opengoofy.index12306.biz.userservice.dto.resp.UserLoginRespDTO;
import org.opengoofy.index12306.biz.userservice.service.UserLoginService;
import org.opengoofy.index12306.framework.starter.convention.result.Result;
import org.opengoofy.index12306.framework.starter.web.Results;
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,594 | /*
* 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.opengoofy.index12306.biz.userservice.controller;
/**
* 用户登录控制层
*
* @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料
*/
@RestController
@RequiredArgsConstructor
public class UserLoginController {
private final UserLoginService userLoginService;
/**
* 用户登录
*/
@PostMapping("/api/user-service/v1/login") | /*
* 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.opengoofy.index12306.biz.userservice.controller;
/**
* 用户登录控制层
*
* @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料
*/
@RestController
@RequiredArgsConstructor
public class UserLoginController {
private final UserLoginService userLoginService;
/**
* 用户登录
*/
@PostMapping("/api/user-service/v1/login") | public Result<UserLoginRespDTO> login(@RequestBody UserLoginReqDTO requestParam) { | 0 | 2023-11-23 07:59:11+00:00 | 2k |
Uhutown/MessengerMod | src/main/java/com/uhutown/messenger/init/ItemInit.java | [
{
"identifier": "MessengerModMain",
"path": "src/main/java/com/uhutown/messenger/MessengerModMain.java",
"snippet": "@Mod(modid = MessengerModMain.MODID, name = MessengerModMain.NAME, version = MessengerModMain.VERSION, acceptedMinecraftVersions = \"[1.12.2]\")\npublic class MessengerModMain {\n\n pu... | import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import com.uhutown.messenger.MessengerModMain;
import com.uhutown.messenger.items.ChatItem;
import net.minecraft.item.Item;
import net.minecraft.util.ResourceLocation; | 720 | package com.uhutown.messenger.init;
public class ItemInit {
public static final ChatItem CHAT_ITEM = new ChatItem();
public static ArrayList<Item> registeredItems = new ArrayList<>();
public static void init() {
final Field[] fields = ItemInit.class.getFields();
for (final Field field : fields) {
final int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)
&& Modifier.isPublic(modifiers)) {
final String name = field.getName().toLowerCase().replace("_", "");
try {
final Item item = (Item) field.get(null); | package com.uhutown.messenger.init;
public class ItemInit {
public static final ChatItem CHAT_ITEM = new ChatItem();
public static ArrayList<Item> registeredItems = new ArrayList<>();
public static void init() {
final Field[] fields = ItemInit.class.getFields();
for (final Field field : fields) {
final int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)
&& Modifier.isPublic(modifiers)) {
final String name = field.getName().toLowerCase().replace("_", "");
try {
final Item item = (Item) field.get(null); | item.setRegistryName(new ResourceLocation(MessengerModMain.MODID, name)); | 0 | 2023-11-19 08:54:27+00:00 | 2k |
tilokowalski/statify | backend/src/test/java/de/tilokowalski/spotify/SpotifyTest.java | [
{
"identifier": "Surreal",
"path": "backend/src/main/java/de/tilokowalski/db/Surreal.java",
"snippet": "@ApplicationScoped\n@Log\npublic class Surreal {\n\n /**\n * The surreal driver is used to communicate with the surreal graph database.\n */\n private final SyncSurrealDriver driver;\n\n... | import de.tilokowalski.db.Surreal;
import de.tilokowalski.model.User;
import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test; | 1,021 | package de.tilokowalski.spotify;
@QuarkusTest
@Disabled
public class SpotifyTest {
private static final String ACCESS_TOKEN = "BQCRx7MpmXsYeNS_IxdAJy5gRccvk2ecLk3foEWd3jKh2e1xxc8egm-djoT9znTsrSHZ4BmIEmohiaGHUxq38O0pMvkBVPn8UTmLUdk4-uolsrtQxOURBFYNM1xZcpZiRTEKs4pOc2t0E-CR_v3V01Yvyfp3N8fhB9G_wrS4U7j3-k8p2qnICCu-fcLrByAwg_pE-52HfiJGwlACQSwRZue3";
@InjectMock | package de.tilokowalski.spotify;
@QuarkusTest
@Disabled
public class SpotifyTest {
private static final String ACCESS_TOKEN = "BQCRx7MpmXsYeNS_IxdAJy5gRccvk2ecLk3foEWd3jKh2e1xxc8egm-djoT9znTsrSHZ4BmIEmohiaGHUxq38O0pMvkBVPn8UTmLUdk4-uolsrtQxOURBFYNM1xZcpZiRTEKs4pOc2t0E-CR_v3V01Yvyfp3N8fhB9G_wrS4U7j3-k8p2qnICCu-fcLrByAwg_pE-52HfiJGwlACQSwRZue3";
@InjectMock | Surreal db; | 0 | 2023-11-24 23:32:26+00:00 | 2k |
JoseEdSouza/banco-imobiliario | app/houses/LostEvent.java | [
{
"identifier": "IHouse",
"path": "app/interfaces/IHouse.java",
"snippet": "public interface IHouse {\n public String getName();\n public void takeAction(Player player);\n public int getTypeHouse();\n public String toString();\n}"
},
{
"identifier": "Player",
"path": "app/model/P... | import app.interfaces.IHouse;
import app.model.Player; | 672 | package app.houses;
public class LostEvent implements IHouse {
public LostEvent(){
}
@Override
public String getName() {
return "Perca";
}
| package app.houses;
public class LostEvent implements IHouse {
public LostEvent(){
}
@Override
public String getName() {
return "Perca";
}
| public void takeAction(Player player) { | 1 | 2023-11-26 12:09:35+00:00 | 2k |
estkme-group/infineon-lpa-mirror | app/src/main/java/com/infineon/esim/lpa/euicc/base/task/ConnectInterfaceTask.java | [
{
"identifier": "EuiccInterface",
"path": "app/src/main/java/com/infineon/esim/lpa/euicc/base/EuiccInterface.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic interface EuiccInterface {\n\n String getTag();\n\n boolean isAvailable();\n boolean isInterfaceConnected();\n boolean connect... | import com.infineon.esim.lpa.euicc.base.EuiccInterface;
import com.infineon.esim.util.Log;
import java.util.concurrent.Callable; | 922 | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.euicc.base.task;
public class ConnectInterfaceTask implements Callable<Void> {
private static final String TAG = ConnectInterfaceTask.class.getName();
| /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.euicc.base.task;
public class ConnectInterfaceTask implements Callable<Void> {
private static final String TAG = ConnectInterfaceTask.class.getName();
| private final EuiccInterface euiccInterface; | 0 | 2023-11-22 07:46:30+00:00 | 2k |
ballerina-platform/module-ballerinax-newrelic | native/src/main/java/io/ballerina/observe/metrics/newrelic/NewRelicMetricsReporter.java | [
{
"identifier": "EXPIRY_TAG",
"path": "native/src/main/java/io/ballerina/observe/metrics/newrelic/ObserveNativeImplConstants.java",
"snippet": "public static final String EXPIRY_TAG = \"timeWindow\";"
},
{
"identifier": "PERCENTILE_TAG",
"path": "native/src/main/java/io/ballerina/observe/met... | import com.newrelic.telemetry.Attributes;
import com.newrelic.telemetry.OkHttpPoster;
import com.newrelic.telemetry.TelemetryClient;
import com.newrelic.telemetry.metrics.Count;
import com.newrelic.telemetry.metrics.MetricBatch;
import com.newrelic.telemetry.metrics.MetricBuffer;
import io.ballerina.runtime.api.PredefinedTypes;
import io.ballerina.runtime.api.creators.TypeCreator;
import io.ballerina.runtime.api.creators.ValueCreator;
import io.ballerina.runtime.api.utils.StringUtils;
import io.ballerina.runtime.api.values.BArray;
import io.ballerina.runtime.api.values.BString;
import io.ballerina.runtime.observability.metrics.Counter;
import io.ballerina.runtime.observability.metrics.DefaultMetricRegistry;
import io.ballerina.runtime.observability.metrics.Gauge;
import io.ballerina.runtime.observability.metrics.Metric;
import io.ballerina.runtime.observability.metrics.MetricConstants;
import io.ballerina.runtime.observability.metrics.MetricId;
import io.ballerina.runtime.observability.metrics.PercentileValue;
import io.ballerina.runtime.observability.metrics.PolledGauge;
import io.ballerina.runtime.observability.metrics.Snapshot;
import io.ballerina.runtime.observability.metrics.Tag;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import static io.ballerina.observe.metrics.newrelic.ObserveNativeImplConstants.EXPIRY_TAG;
import static io.ballerina.observe.metrics.newrelic.ObserveNativeImplConstants.PERCENTILE_TAG; | 1,401 | /*
* Copyright (c) 2023, WSO2 LLC. (https://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.observe.metrics.newrelic;
/**
* This is the New Relic metric reporter class.
*/
public class NewRelicMetricsReporter {
private static final String METRIC_REPORTER_ENDPOINT = "https://metric-api.newrelic.com/metric/v1";
private static final int SCHEDULE_EXECUTOR_INITIAL_DELAY = 0;
public static BArray sendMetrics(BString apiKey, int metricReporterFlushInterval,
int metricReporterClientTimeout) {
BArray output = ValueCreator.createArrayValue(TypeCreator.createArrayType(PredefinedTypes.TYPE_STRING));
// create a TelemetryClient with an HTTP connect timeout of 10 seconds.
TelemetryClient telemetryClient =
TelemetryClient.create(
() -> new OkHttpPoster(Duration.of(metricReporterClientTimeout, ChronoUnit.MILLIS)),
apiKey.getValue());
Attributes commonAttributes = null;
try {
commonAttributes = new Attributes()
.put("host", InetAddress.getLocalHost().getHostName())
.put("language", "ballerina");
} catch (UnknownHostException e) {
output.append(StringUtils.fromString("error: while getting the host name of the instance"));
}
// Create a ScheduledExecutorService with a single thread
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
// Schedule a task to run every 1 second with an initial delay of 0 seconds
Attributes finalCommonAttributes = commonAttributes;
executorService.scheduleAtFixedRate(() -> {
MetricBuffer metricBuffer = generateMetricBuffer(finalCommonAttributes);
MetricBatch batch = metricBuffer.createBatch();
telemetryClient.sendBatch(batch);
}, SCHEDULE_EXECUTOR_INITIAL_DELAY, metricReporterFlushInterval, TimeUnit.MILLISECONDS);
output.append(StringUtils.fromString("ballerina: started publishing metrics to New Relic on " +
METRIC_REPORTER_ENDPOINT));
return output;
}
private static MetricBuffer generateMetricBuffer(Attributes commonAttributes) {
MetricBuffer metricBuffer = new MetricBuffer(commonAttributes);
Metric[] metrics = DefaultMetricRegistry.getInstance().getAllMetrics();
for (Metric metric : metrics) {
MetricId metricId = metric.getId();
String qualifiedMetricName = metricId.getName();
String metricReportName = getMetricName(qualifiedMetricName, "value");
Double metricValue = null;
String metricType = null;
Snapshot[] snapshots = null;
if (metric instanceof Counter counter) {
metricValue = getMetricValue(counter.getValue());
metricType = MetricConstants.COUNTER;
} else if (metric instanceof Gauge gauge) {
metricValue = getMetricValue(gauge.getValue());
metricType = MetricConstants.GAUGE;
snapshots = gauge.getSnapshots();
} else if (metric instanceof PolledGauge polledGauge) {
metricValue = getMetricValue(polledGauge.getValue());
metricType = MetricConstants.GAUGE;
}
if (metricValue != null) {
long startTimeInMillis = System.currentTimeMillis();
Attributes tags = new Attributes();
for (Tag tag : metricId.getTags()) {
tags.put(tag.getKey(), tag.getValue());
}
if (metricType.equals(MetricConstants.COUNTER)) {
Count countMetric = generateCountMetric(metricReportName, metricValue, startTimeInMillis, tags);
metricBuffer.addMetric(countMetric);
} else if (metricType.equals(MetricConstants.GAUGE)) {
com.newrelic.telemetry.metrics.Gauge gaugeMetric = generateGaugeMetric(metricReportName,
metricValue, tags);
metricBuffer.addMetric(gaugeMetric);
}
if (snapshots != null) {
for (Snapshot snapshot : snapshots) {
Attributes snapshotTags = tags.copy(); | /*
* Copyright (c) 2023, WSO2 LLC. (https://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.observe.metrics.newrelic;
/**
* This is the New Relic metric reporter class.
*/
public class NewRelicMetricsReporter {
private static final String METRIC_REPORTER_ENDPOINT = "https://metric-api.newrelic.com/metric/v1";
private static final int SCHEDULE_EXECUTOR_INITIAL_DELAY = 0;
public static BArray sendMetrics(BString apiKey, int metricReporterFlushInterval,
int metricReporterClientTimeout) {
BArray output = ValueCreator.createArrayValue(TypeCreator.createArrayType(PredefinedTypes.TYPE_STRING));
// create a TelemetryClient with an HTTP connect timeout of 10 seconds.
TelemetryClient telemetryClient =
TelemetryClient.create(
() -> new OkHttpPoster(Duration.of(metricReporterClientTimeout, ChronoUnit.MILLIS)),
apiKey.getValue());
Attributes commonAttributes = null;
try {
commonAttributes = new Attributes()
.put("host", InetAddress.getLocalHost().getHostName())
.put("language", "ballerina");
} catch (UnknownHostException e) {
output.append(StringUtils.fromString("error: while getting the host name of the instance"));
}
// Create a ScheduledExecutorService with a single thread
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
// Schedule a task to run every 1 second with an initial delay of 0 seconds
Attributes finalCommonAttributes = commonAttributes;
executorService.scheduleAtFixedRate(() -> {
MetricBuffer metricBuffer = generateMetricBuffer(finalCommonAttributes);
MetricBatch batch = metricBuffer.createBatch();
telemetryClient.sendBatch(batch);
}, SCHEDULE_EXECUTOR_INITIAL_DELAY, metricReporterFlushInterval, TimeUnit.MILLISECONDS);
output.append(StringUtils.fromString("ballerina: started publishing metrics to New Relic on " +
METRIC_REPORTER_ENDPOINT));
return output;
}
private static MetricBuffer generateMetricBuffer(Attributes commonAttributes) {
MetricBuffer metricBuffer = new MetricBuffer(commonAttributes);
Metric[] metrics = DefaultMetricRegistry.getInstance().getAllMetrics();
for (Metric metric : metrics) {
MetricId metricId = metric.getId();
String qualifiedMetricName = metricId.getName();
String metricReportName = getMetricName(qualifiedMetricName, "value");
Double metricValue = null;
String metricType = null;
Snapshot[] snapshots = null;
if (metric instanceof Counter counter) {
metricValue = getMetricValue(counter.getValue());
metricType = MetricConstants.COUNTER;
} else if (metric instanceof Gauge gauge) {
metricValue = getMetricValue(gauge.getValue());
metricType = MetricConstants.GAUGE;
snapshots = gauge.getSnapshots();
} else if (metric instanceof PolledGauge polledGauge) {
metricValue = getMetricValue(polledGauge.getValue());
metricType = MetricConstants.GAUGE;
}
if (metricValue != null) {
long startTimeInMillis = System.currentTimeMillis();
Attributes tags = new Attributes();
for (Tag tag : metricId.getTags()) {
tags.put(tag.getKey(), tag.getValue());
}
if (metricType.equals(MetricConstants.COUNTER)) {
Count countMetric = generateCountMetric(metricReportName, metricValue, startTimeInMillis, tags);
metricBuffer.addMetric(countMetric);
} else if (metricType.equals(MetricConstants.GAUGE)) {
com.newrelic.telemetry.metrics.Gauge gaugeMetric = generateGaugeMetric(metricReportName,
metricValue, tags);
metricBuffer.addMetric(gaugeMetric);
}
if (snapshots != null) {
for (Snapshot snapshot : snapshots) {
Attributes snapshotTags = tags.copy(); | snapshotTags.put(EXPIRY_TAG, snapshot.getTimeWindow().toString()); | 0 | 2023-11-22 11:48:31+00:00 | 2k |
idaoyu/iot-project-java | iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/device/controller/DeviceShadowController.java | [
{
"identifier": "DeviceShadow",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/device/entity/DeviceShadow.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(value = \"device_shadow\")\npublic class DeviceShadow {\n\n @TableId(value = \"... | import com.bbkk.project.module.device.entity.DeviceShadow;
import com.bbkk.project.module.device.service.DeviceShadowBusinessService;
import jakarta.validation.constraints.NotEmpty;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; | 644 | package com.bbkk.project.module.device.controller;
/**
* 设备影子接口
*
* @author 一条秋刀鱼zz qchenzexuan@vip.qq.com
* @since 2023-12-16 11:45
**/
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/deviceShadow")
public class DeviceShadowController {
| package com.bbkk.project.module.device.controller;
/**
* 设备影子接口
*
* @author 一条秋刀鱼zz qchenzexuan@vip.qq.com
* @since 2023-12-16 11:45
**/
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/deviceShadow")
public class DeviceShadowController {
| private final DeviceShadowBusinessService deviceShadowBusinessService; | 1 | 2023-11-25 06:59:20+00:00 | 2k |
MattiDragon/JsonPatcherLang | src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/expression/BinaryExpression.java | [
{
"identifier": "EvaluationException",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/EvaluationException.java",
"snippet": "public class EvaluationException extends PositionedException {\n @Nullable\n private final SourceSpan pos;\n\n public EvaluationException(String me... | import io.github.mattidragon.jsonpatcher.lang.parse.SourceSpan;
import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationContext;
import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationException;
import io.github.mattidragon.jsonpatcher.lang.runtime.Value;
import java.util.function.BiPredicate; | 1,575 | package io.github.mattidragon.jsonpatcher.lang.runtime.expression;
public record BinaryExpression(Expression first, Expression second, Operator op, SourceSpan pos) implements Expression {
@Override | package io.github.mattidragon.jsonpatcher.lang.runtime.expression;
public record BinaryExpression(Expression first, Expression second, Operator op, SourceSpan pos) implements Expression {
@Override | public Value evaluate(EvaluationContext context) { | 1 | 2023-11-23 14:17:00+00:00 | 2k |
quarkusio/conversational-release-action | src/main/java/io/quarkus/bot/release/util/Issues.java | [
{
"identifier": "ReleaseInformation",
"path": "src/main/java/io/quarkus/bot/release/ReleaseInformation.java",
"snippet": "public class ReleaseInformation {\n\n private final String branch;\n private final String qualifier;\n private final boolean major;\n\n private String version;\n priva... | import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.quarkus.bot.release.ReleaseInformation;
import io.quarkus.bot.release.ReleaseStatus;
import io.quarkus.bot.release.util.UtilsProducer.Yaml; | 1,541 | package io.quarkus.bot.release.util;
@Singleton
public final class Issues {
private static final String BRANCH = "### Branch";
private static final String QUALIFIER = "### Qualifier";
private static final String MAJOR_VERSION = "### Major version";
private static final String NO_RESPONSE = "_No response_";
private static final String RELEASE_INFORMATION_MARKER = "<!-- quarkus-release/release-information:";
private static final String RELEASE_STATUS_MARKER = "<!-- quarkus-release/release-status:";
private static final String END_OF_MARKER = "-->";
private static final Pattern RELEASE_INFORMATION_PATTERN = Pattern.compile(RELEASE_INFORMATION_MARKER + "(.*?)" + END_OF_MARKER, Pattern.DOTALL);
private static final Pattern RELEASE_STATUS_PATTERN = Pattern.compile(RELEASE_STATUS_MARKER + "(.*?)" + END_OF_MARKER, Pattern.DOTALL);
@Inject
@Yaml
ObjectMapper objectMapper;
| package io.quarkus.bot.release.util;
@Singleton
public final class Issues {
private static final String BRANCH = "### Branch";
private static final String QUALIFIER = "### Qualifier";
private static final String MAJOR_VERSION = "### Major version";
private static final String NO_RESPONSE = "_No response_";
private static final String RELEASE_INFORMATION_MARKER = "<!-- quarkus-release/release-information:";
private static final String RELEASE_STATUS_MARKER = "<!-- quarkus-release/release-status:";
private static final String END_OF_MARKER = "-->";
private static final Pattern RELEASE_INFORMATION_PATTERN = Pattern.compile(RELEASE_INFORMATION_MARKER + "(.*?)" + END_OF_MARKER, Pattern.DOTALL);
private static final Pattern RELEASE_STATUS_PATTERN = Pattern.compile(RELEASE_STATUS_MARKER + "(.*?)" + END_OF_MARKER, Pattern.DOTALL);
@Inject
@Yaml
ObjectMapper objectMapper;
| public ReleaseInformation extractReleaseInformationFromForm(String description) { | 0 | 2023-11-20 10:33:48+00:00 | 2k |
surajkumar/wazei | app/src/main/java/io/github/surajkumar/wazei/RequestHandler.java | [
{
"identifier": "Config",
"path": "app/src/main/java/io/github/surajkumar/wazei/config/Config.java",
"snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Config {\n private String packageName;\n private String className;\n private List<Metadata> metadata;\n\n public Config()... | import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import io.github.surajkumar.wazei.config.Config;
import io.github.surajkumar.wazei.config.ConfigSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; | 785 | package io.github.surajkumar.wazei;
/**
* Handles incoming HTTP requests and delegates processing to a {@link RequestProcessor}.
*
* @author Suraj Kumar
*/
public class RequestHandler implements HttpHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final ConfigSearcher configSearcher;
/**
* Constructs a RequestHandler with a given ConfigSearcher.
*
* @param configSearcher The ConfigSearcher to use for retrieving configurations.
*/
public RequestHandler(ConfigSearcher configSearcher) {
this.configSearcher = configSearcher;
}
@Override
public void handle(HttpExchange exchange) {
try {
processRequest(exchange);
} catch (IOException e) {
handleError(exchange, e);
}
}
/**
* Processes an incoming HTTP request.
*
* @param exchange The HttpExchange object representing the incoming request and response.
* @throws IOException If an IO error occurs during request processing.
*/
private void processRequest(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
String remoteAddress = exchange.getRemoteAddress().getHostString();
LOGGER.info("Received request from {} for path: {}", remoteAddress, path);
try { | package io.github.surajkumar.wazei;
/**
* Handles incoming HTTP requests and delegates processing to a {@link RequestProcessor}.
*
* @author Suraj Kumar
*/
public class RequestHandler implements HttpHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final ConfigSearcher configSearcher;
/**
* Constructs a RequestHandler with a given ConfigSearcher.
*
* @param configSearcher The ConfigSearcher to use for retrieving configurations.
*/
public RequestHandler(ConfigSearcher configSearcher) {
this.configSearcher = configSearcher;
}
@Override
public void handle(HttpExchange exchange) {
try {
processRequest(exchange);
} catch (IOException e) {
handleError(exchange, e);
}
}
/**
* Processes an incoming HTTP request.
*
* @param exchange The HttpExchange object representing the incoming request and response.
* @throws IOException If an IO error occurs during request processing.
*/
private void processRequest(HttpExchange exchange) throws IOException {
String path = exchange.getRequestURI().getPath();
String remoteAddress = exchange.getRemoteAddress().getHostString();
LOGGER.info("Received request from {} for path: {}", remoteAddress, path);
try { | Config config = configSearcher.getConfigForPath(path); | 0 | 2023-11-19 18:06:58+00:00 | 2k |
syncstream-dev/syncstream-backend | src/main/java/com/syncstream_dev/syncstream/model/session/Session.java | [
{
"identifier": "ChatStream",
"path": "src/main/java/com/syncstream_dev/syncstream/model/ChatStream.java",
"snippet": "public class ChatStream {\n private HashMap<String, Message> messages; // Message id to Message mapping\n private ArrayList<User> participants;\n\n public ChatStream() {\n... | import java.util.ArrayList;
import com.syncstream_dev.syncstream.model.ChatStream;
import com.syncstream_dev.syncstream.model.Genre;
import com.syncstream_dev.syncstream.model.VideoInfo;
import com.syncstream_dev.syncstream.model.User; | 1,122 | package com.syncstream_dev.syncstream.model.session;
public abstract class Session {
protected String sessionId;
protected Genre genre; | package com.syncstream_dev.syncstream.model.session;
public abstract class Session {
protected String sessionId;
protected Genre genre; | protected ArrayList<User> participants; | 3 | 2023-11-19 02:02:53+00:00 | 2k |
wssun/AST4PLU | data-process/process/src/main/java/utils/TreeTools.java | [
{
"identifier": "BinaryTree",
"path": "data-process/process/src/main/java/tree/BinaryTree.java",
"snippet": "public class BinaryTree {\n\t\n\tprivate String root;\n\tprivate BinaryTree left,right;\n\t\n\tpublic BinaryTree()\n\t{\n\t\troot=\"\";\n\t\tleft=null;\n\t\tright=null;\n\t}\n\t\n\tpublic String ... | import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import tree.BinaryTree;
import tree.Tree; | 1,515 | package utils;
public class TreeTools {
private static String sbt;
private static List<String> sbt_no_brk;
private static List<String> sbt_brk;
private static List<String> non_leaf; | package utils;
public class TreeTools {
private static String sbt;
private static List<String> sbt_no_brk;
private static List<String> sbt_brk;
private static List<String> non_leaf; | private static Queue<Tree> que; | 1 | 2023-11-23 06:08:43+00:00 | 2k |
vitozs/api-zelda | user-service/src/main/java/com/github/userservice/controller/AutenticationController.java | [
{
"identifier": "UserModel",
"path": "user-service/src/main/java/com/github/userservice/models/UserModel.java",
"snippet": "@Entity(name = \"User\")\n@Table(name = \"users\")\n@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode(of = \"id\")\npublic class UserModel implements Us... | import com.github.userservice.infra.security.TokenJWTData;
import com.github.userservice.models.UserModel;
import com.github.userservice.models.recordClasses.AutenticationData;
import com.github.userservice.repository.UserRepository;
import com.github.userservice.service.TokenService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
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,057 | package com.github.userservice.controller;
@RestController
@RequestMapping("login")
public class AutenticationController {
@Autowired
private AuthenticationManager authenticationManager; // do proprio spring
@Autowired | package com.github.userservice.controller;
@RestController
@RequestMapping("login")
public class AutenticationController {
@Autowired
private AuthenticationManager authenticationManager; // do proprio spring
@Autowired | private UserRepository userRepository; | 1 | 2023-11-22 00:20:25+00:00 | 2k |
skippy-io/skippy | skippy-build-common/src/main/java/io/skippy/build/SkippyBuildApi.java | [
{
"identifier": "SkippyUtils",
"path": "skippy-common/src/main/java/io/skippy/core/SkippyUtils.java",
"snippet": "public final class SkippyUtils {\n\n /**\n * Returns the skippy folder. This method will create the folder if it doesn't exist.\n *\n * @return the skippy folder\n */\n ... | import io.skippy.core.SkippyUtils;
import java.nio.file.Path;
import static io.skippy.core.SkippyConstants.*; | 1,129 | /*
* Copyright 2023-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.skippy.build;
/**
* API with functionality that is used across build-tool specific libraries (e.g., skippy-gradle and skippy-maven).
*
* @author Florian McKee
*/
public final class SkippyBuildApi {
private final Path projectDir;
private final ClassesMd5Writer classesMd5Writer;
private final CoverageFileCompactor coverageFileCompactor;
/**
* C'tor.
*
* @param projectDir the project folder
* @param classFileCollector the {@link ClassFileCollector}
*/
public SkippyBuildApi(Path projectDir, ClassFileCollector classFileCollector) {
this.projectDir = projectDir;
this.classesMd5Writer = new ClassesMd5Writer(projectDir, classFileCollector);
this.coverageFileCompactor = new CoverageFileCompactor(projectDir, classFileCollector);
}
/**
* Performs the following actions:
* <ul>
* <li>Compacts the coverage files (see {@link CoverageFileCompactor})</li>
* <li>Writes the {@code classes.md5} file (see {@link ClassesMd5Writer})</li>
* </ul>
*/
public void writeClassesMd5FileAndCompactCoverageFiles() {
classesMd5Writer.write();
coverageFileCompactor.compact();
}
/**
* Removes the skippy folder.
*/
public void removeSkippyFolder() { | /*
* Copyright 2023-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.skippy.build;
/**
* API with functionality that is used across build-tool specific libraries (e.g., skippy-gradle and skippy-maven).
*
* @author Florian McKee
*/
public final class SkippyBuildApi {
private final Path projectDir;
private final ClassesMd5Writer classesMd5Writer;
private final CoverageFileCompactor coverageFileCompactor;
/**
* C'tor.
*
* @param projectDir the project folder
* @param classFileCollector the {@link ClassFileCollector}
*/
public SkippyBuildApi(Path projectDir, ClassFileCollector classFileCollector) {
this.projectDir = projectDir;
this.classesMd5Writer = new ClassesMd5Writer(projectDir, classFileCollector);
this.coverageFileCompactor = new CoverageFileCompactor(projectDir, classFileCollector);
}
/**
* Performs the following actions:
* <ul>
* <li>Compacts the coverage files (see {@link CoverageFileCompactor})</li>
* <li>Writes the {@code classes.md5} file (see {@link ClassesMd5Writer})</li>
* </ul>
*/
public void writeClassesMd5FileAndCompactCoverageFiles() {
classesMd5Writer.write();
coverageFileCompactor.compact();
}
/**
* Removes the skippy folder.
*/
public void removeSkippyFolder() { | var skippyFolder = SkippyUtils.getSkippyFolder(projectDir).toFile(); | 0 | 2023-11-24 14:19:17+00:00 | 2k |
marie0llie/themetip | src/main/java/gay/marie_the/themetip/compat/ModMenuIntegration.java | [
{
"identifier": "ThemetipConfig",
"path": "src/main/java/gay/marie_the/themetip/config/ThemetipConfig.java",
"snippet": "public class ThemetipConfig {\n\n public static final Path configFile = FabricLoader.getInstance().getConfigDir().resolve(\"themetip.json5\");\n\n private static final String ma... | import com.terraformersmc.modmenu.api.ConfigScreenFactory;
import com.terraformersmc.modmenu.api.ModMenuApi;
import gay.marie_the.themetip.config.ThemetipConfig;
import gay.marie_the.themetip.Themetip; | 792 | package gay.marie_the.themetip.compat;
public class ModMenuIntegration implements ModMenuApi {
public ConfigScreenFactory<?> getModConfigScreenFactory() { | package gay.marie_the.themetip.compat;
public class ModMenuIntegration implements ModMenuApi {
public ConfigScreenFactory<?> getModConfigScreenFactory() { | Themetip.LOGGER.atInfo().log("Loading themetip config"); | 1 | 2023-11-22 03:17:18+00:00 | 2k |
CaoBaoQi/homework-android | work-account-book/src/main/java/jz/cbq/work_account_book/ui/home/AddIncome.java | [
{
"identifier": "Card",
"path": "work-account-book/src/main/java/jz/cbq/work_account_book/Card.java",
"snippet": "public class Card {\n private final String name;\n private final int imageId;\n\n public Card(String name, int imageId) {\n this.name = name;\n this.imageId = imageId;... | import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import androidx.fragment.app.Fragment;
import jz.cbq.work_account_book.Card;
import jz.cbq.work_account_book.CardsAdapter;
import jz.cbq.work_account_book.R;
import java.util.ArrayList; | 735 | package jz.cbq.work_account_book.ui.home;
public class AddIncome extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private final ArrayList<Card> inTypeList = new ArrayList<>(); | package jz.cbq.work_account_book.ui.home;
public class AddIncome extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private final ArrayList<Card> inTypeList = new ArrayList<>(); | public static CardsAdapter adapter; | 1 | 2023-11-20 17:30:01+00:00 | 2k |
tommyskeff/futur4j | futur-reactive-streams/src/main/java/dev/tommyjs/futur/reactivestreams/SingleAccumulatorSubscriber.java | [
{
"identifier": "Promise",
"path": "futur-api/src/main/java/dev/tommyjs/futur/promise/Promise.java",
"snippet": "public interface Promise<T> {\n\n static <T> @NotNull Promise<T> resolve(T value, PromiseFactory factory) {\n return factory.resolve(value);\n }\n\n static <T> @NotNull Promis... | import dev.tommyjs.futur.promise.Promise;
import dev.tommyjs.futur.promise.PromiseFactory;
import dev.tommyjs.futur.promise.StaticPromiseFactory;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription; | 1,586 | package dev.tommyjs.futur.reactivestreams;
public class SingleAccumulatorSubscriber<T> implements Subscriber<T> {
private final Promise<T> promise;
public SingleAccumulatorSubscriber(Promise<T> promise) {
this.promise = promise;
}
@Override
public void onSubscribe(Subscription s) {
s.request(1);
}
@Override
public void onNext(T t) {
promise.complete(t);
}
@Override
public void onError(Throwable t) {
promise.completeExceptionally(t);
}
@Override
public void onComplete() {
// ignore
}
public Promise<T> getPromise() {
return promise;
}
public static <T> SingleAccumulatorSubscriber<T> create(Promise<T> promise) {
return new SingleAccumulatorSubscriber<>(promise);
}
public static <T> SingleAccumulatorSubscriber<T> create(PromiseFactory factory) {
return create(factory.unresolved());
}
public static <T> SingleAccumulatorSubscriber<T> create() { | package dev.tommyjs.futur.reactivestreams;
public class SingleAccumulatorSubscriber<T> implements Subscriber<T> {
private final Promise<T> promise;
public SingleAccumulatorSubscriber(Promise<T> promise) {
this.promise = promise;
}
@Override
public void onSubscribe(Subscription s) {
s.request(1);
}
@Override
public void onNext(T t) {
promise.complete(t);
}
@Override
public void onError(Throwable t) {
promise.completeExceptionally(t);
}
@Override
public void onComplete() {
// ignore
}
public Promise<T> getPromise() {
return promise;
}
public static <T> SingleAccumulatorSubscriber<T> create(Promise<T> promise) {
return new SingleAccumulatorSubscriber<>(promise);
}
public static <T> SingleAccumulatorSubscriber<T> create(PromiseFactory factory) {
return create(factory.unresolved());
}
public static <T> SingleAccumulatorSubscriber<T> create() { | return create(StaticPromiseFactory.INSTANCE); | 2 | 2023-11-19 20:56:51+00:00 | 2k |
phamdung2209/FAP | src/main/java/com/course/Course.java | [
{
"identifier": "Schedule",
"path": "src/main/java/com/Date/Schedule.java",
"snippet": "public class Schedule {\n private String id;\n private Date date;\n private Date startTime;\n private Date endTime;\n\n public Schedule(Date date, Date startDate, Date endDate, String id) {\n th... | import java.util.ArrayList;
import java.util.List;
import com.date.Schedule;
import com.persons.Lecturer;
import com.persons.Student; | 1,521 | package com.course;
public class Course {
private String id;
private String courseName;
private String description;
private long cost;
private Student student;
private Lecturer lecturer; | package com.course;
public class Course {
private String id;
private String courseName;
private String description;
private long cost;
private Student student;
private Lecturer lecturer; | private List<Schedule> schedules = new ArrayList<Schedule>(); | 0 | 2023-11-23 18:42:19+00:00 | 2k |
morihofi/acmeserver | src/main/java/de/morihofi/acmeserver/tools/certificate/generator/CertificateRevokationListGenerator.java | [
{
"identifier": "RevokedCertificate",
"path": "src/main/java/de/morihofi/acmeserver/certificate/revokeDistribution/objects/RevokedCertificate.java",
"snippet": "public class RevokedCertificate {\n private BigInteger serialNumber;\n private Date revokationDate;\n private int revokationReason;\n\... | import de.morihofi.acmeserver.certificate.revokeDistribution.objects.RevokedCertificate;
import de.morihofi.acmeserver.tools.certificate.CertMisc;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509v2CRLBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CRLConverter;
import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import java.security.PrivateKey;
import java.security.cert.CRLException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.List; | 1,600 | package de.morihofi.acmeserver.tools.certificate.generator;
public class CertificateRevokationListGenerator {
private CertificateRevokationListGenerator(){}
/**
* Generates a Certificate Revocation List (CRL) using the provided list of revoked certificates,
* the Certificate Authority (CA) certificate, and the CA's private key. The generated CRL will
* include details about the revoked certificates and will be signed using the CA's private key.
*
* @param revokedCertificates A list of {@link RevokedCertificate} objects representing the certificates
* that need to be revoked.
* @param caCert The X509 certificate of the Certificate Authority.
* @param caPrivateKey The private key of the Certificate Authority used to sign the CRL.
* @param updateMinutes The number of minutes after which the CRL should be updated.
* @return An {@link X509CRL} object representing the generated CRL.
* @throws CertificateEncodingException if an encoding error occurs with the CA certificate.
* @throws CRLException if an error occurs during the CRL generation.
* @throws OperatorCreationException if there's an error in creating the content signer.
*/
public static X509CRL generateCRL(List<RevokedCertificate> revokedCertificates,
X509Certificate caCert,
PrivateKey caPrivateKey, int updateMinutes) throws CertificateEncodingException, CRLException, OperatorCreationException {
// Create the CRL Builder
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(
new JcaX509CertificateHolder(caCert).getSubject(),
new Date()
);
// Add an expiration date
crlBuilder.setNextUpdate(new Date(System.currentTimeMillis() + updateMinutes * 60 * 1000L)); //Update in 5 minutes
// Add the revoked serial numbers
for (RevokedCertificate revokedCertificate : revokedCertificates) {
crlBuilder.addCRLEntry(revokedCertificate.getSerialNumber(), revokedCertificate.getRevokationDate(), revokedCertificate.getRevokationReason());
}
// Sign the CRL with the CA's private key | package de.morihofi.acmeserver.tools.certificate.generator;
public class CertificateRevokationListGenerator {
private CertificateRevokationListGenerator(){}
/**
* Generates a Certificate Revocation List (CRL) using the provided list of revoked certificates,
* the Certificate Authority (CA) certificate, and the CA's private key. The generated CRL will
* include details about the revoked certificates and will be signed using the CA's private key.
*
* @param revokedCertificates A list of {@link RevokedCertificate} objects representing the certificates
* that need to be revoked.
* @param caCert The X509 certificate of the Certificate Authority.
* @param caPrivateKey The private key of the Certificate Authority used to sign the CRL.
* @param updateMinutes The number of minutes after which the CRL should be updated.
* @return An {@link X509CRL} object representing the generated CRL.
* @throws CertificateEncodingException if an encoding error occurs with the CA certificate.
* @throws CRLException if an error occurs during the CRL generation.
* @throws OperatorCreationException if there's an error in creating the content signer.
*/
public static X509CRL generateCRL(List<RevokedCertificate> revokedCertificates,
X509Certificate caCert,
PrivateKey caPrivateKey, int updateMinutes) throws CertificateEncodingException, CRLException, OperatorCreationException {
// Create the CRL Builder
X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(
new JcaX509CertificateHolder(caCert).getSubject(),
new Date()
);
// Add an expiration date
crlBuilder.setNextUpdate(new Date(System.currentTimeMillis() + updateMinutes * 60 * 1000L)); //Update in 5 minutes
// Add the revoked serial numbers
for (RevokedCertificate revokedCertificate : revokedCertificates) {
crlBuilder.addCRLEntry(revokedCertificate.getSerialNumber(), revokedCertificate.getRevokationDate(), revokedCertificate.getRevokationReason());
}
// Sign the CRL with the CA's private key | JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(CertMisc.getSignatureAlgorithmBasedOnKeyType(caPrivateKey)); | 1 | 2023-11-22 15:54:36+00:00 | 2k |
abdelaalimouid/marketplacce | src/Main.java | [
{
"identifier": "IService",
"path": "src/serviceManagement/IService.java",
"snippet": "public interface IService {\n String getName();\n double getPrice();\n void performService();\n \n}"
},
{
"identifier": "IUser",
"path": "src/userManagement/IUser.java",
"snippet": "public interfac... | import serviceManagement.IService;
import userManagement.IUser;
import java.util.List;
import java.util.Scanner; | 1,082 | scanner.close();
}
private static IUser displayLoginScreen() {
System.out.println("Welcome to the Service Marketplace!");
String username = UserInput.getInput("Enter your username: ");
String password = UserInput.getInput("Enter your password: ");
return getAuthenticatedUser(username, password);
}
private static IUser getAuthenticatedUser(String username, String password) {
for (IUser user : users) {
if (user.getUsername().equals(username) && authenticatePassword(user, password)) {
return user;
}
}
return null;
}
private static boolean authenticatePassword(IUser user, String password) {
if (user instanceof ServiceProvider) {
return ((ServiceProvider) user).authenticate(password);
} else if (user instanceof Client) {
return ((Client) user).authenticate(password);
}
return false;
}
private static void runServiceProvider(ServiceProvider serviceProvider) {
boolean continueRunning = true;
createInitialServices(serviceProvider);
while (continueRunning) {
displayServiceProviderMenu();
int choice = getUserInputInt("Enter your choice: ");
switch (choice) {
case 1:
displayServicesWithIndex(serviceProvider.getServicesOffered());
break;
case 2:
createServiceInteractive(serviceProvider);
break;
case 3:
displayServiceHistory(serviceProvider.getServiceHistory());
break;
case 4:
System.out.println("Exiting the program. Goodbye!");
continueRunning = false;
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
}
}
private static void runClient(Client client, ServiceProvider serviceProvider) {
boolean continueRunning = true;
while (continueRunning) {
displayClientMenu();
int choice = getUserInputInt("Enter your choice: ");
switch (choice) {
case 1:
displayServicesWithIndex(serviceProvider.getServicesOffered());
break;
case 2:
purchaseServiceInteractive(client, serviceProvider);
break;
case 3:
displayPurchaseHistory(client.getPurchaseHistory());
break;
case 4:
System.out.println("Exiting the program. Goodbye!");
continueRunning = false;
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
}
}
private static ServiceProvider createServiceProvider() {
return new ServiceProvider("TemporaryServiceProvider", "temporary_password");
}
private static void displayServiceProviderMenu() {
System.out.println("\n" + ANSI_CYAN + "Service Provider Menu:" + ANSI_RESET);
System.out.println("1. Display Services Offered");
System.out.println("2. Create a New Service");
System.out.println("3. Display Service History");
System.out.println("4. Exit");
}
private static void displayClientMenu() {
System.out.println("\n" + ANSI_CYAN + "Client Menu:" + ANSI_RESET);
System.out.println("1. Display Services Available for Purchase");
System.out.println("2. Purchase a Service");
System.out.println("3. Display Purchase History");
System.out.println("4. Exit");
}
private static void createInitialServices(ServiceProvider serviceProvider) {
Service service1 = new Service("Cleaning", 25.0);
Service service2 = new Service("Gardening", 30.0);
Service service3 = new Service("Plumbing", 40.0);
serviceProvider.addService(service1);
serviceProvider.addService(service2);
serviceProvider.addService(service3);
}
|
public class Main {
private static final String ANSI_RESET = "\u001B[0m";
private static final String ANSI_GREEN = "\u001B[32m";
private static final String ANSI_CYAN = "\u001B[36m";
private static Scanner scanner = new Scanner(System.in);
private static List<IUser> users = List.of(
new ServiceProvider("ServiceProvider", "sp_password"),
new Client("Client", "client_password")
);
public static void main(String[] args) {
IUser authenticatedUser = displayLoginScreen();
if (authenticatedUser != null) {
System.out.println("Welcome to the Service Marketplace!");
if (authenticatedUser.isServiceProvider()) {
ServiceProvider serviceProvider = (ServiceProvider) authenticatedUser;
runServiceProvider(serviceProvider);
} else if (authenticatedUser.isClient()) {
Client client = (Client) authenticatedUser;
ServiceProvider serviceProvider = createServiceProvider();
createInitialServices(serviceProvider);
runClient(client, serviceProvider);
}
} else {
System.out.println("Exiting the program. Goodbye!");
}
scanner.close();
}
private static IUser displayLoginScreen() {
System.out.println("Welcome to the Service Marketplace!");
String username = UserInput.getInput("Enter your username: ");
String password = UserInput.getInput("Enter your password: ");
return getAuthenticatedUser(username, password);
}
private static IUser getAuthenticatedUser(String username, String password) {
for (IUser user : users) {
if (user.getUsername().equals(username) && authenticatePassword(user, password)) {
return user;
}
}
return null;
}
private static boolean authenticatePassword(IUser user, String password) {
if (user instanceof ServiceProvider) {
return ((ServiceProvider) user).authenticate(password);
} else if (user instanceof Client) {
return ((Client) user).authenticate(password);
}
return false;
}
private static void runServiceProvider(ServiceProvider serviceProvider) {
boolean continueRunning = true;
createInitialServices(serviceProvider);
while (continueRunning) {
displayServiceProviderMenu();
int choice = getUserInputInt("Enter your choice: ");
switch (choice) {
case 1:
displayServicesWithIndex(serviceProvider.getServicesOffered());
break;
case 2:
createServiceInteractive(serviceProvider);
break;
case 3:
displayServiceHistory(serviceProvider.getServiceHistory());
break;
case 4:
System.out.println("Exiting the program. Goodbye!");
continueRunning = false;
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
}
}
private static void runClient(Client client, ServiceProvider serviceProvider) {
boolean continueRunning = true;
while (continueRunning) {
displayClientMenu();
int choice = getUserInputInt("Enter your choice: ");
switch (choice) {
case 1:
displayServicesWithIndex(serviceProvider.getServicesOffered());
break;
case 2:
purchaseServiceInteractive(client, serviceProvider);
break;
case 3:
displayPurchaseHistory(client.getPurchaseHistory());
break;
case 4:
System.out.println("Exiting the program. Goodbye!");
continueRunning = false;
break;
default:
System.out.println("Invalid choice. Please enter a valid option.");
}
}
}
private static ServiceProvider createServiceProvider() {
return new ServiceProvider("TemporaryServiceProvider", "temporary_password");
}
private static void displayServiceProviderMenu() {
System.out.println("\n" + ANSI_CYAN + "Service Provider Menu:" + ANSI_RESET);
System.out.println("1. Display Services Offered");
System.out.println("2. Create a New Service");
System.out.println("3. Display Service History");
System.out.println("4. Exit");
}
private static void displayClientMenu() {
System.out.println("\n" + ANSI_CYAN + "Client Menu:" + ANSI_RESET);
System.out.println("1. Display Services Available for Purchase");
System.out.println("2. Purchase a Service");
System.out.println("3. Display Purchase History");
System.out.println("4. Exit");
}
private static void createInitialServices(ServiceProvider serviceProvider) {
Service service1 = new Service("Cleaning", 25.0);
Service service2 = new Service("Gardening", 30.0);
Service service3 = new Service("Plumbing", 40.0);
serviceProvider.addService(service1);
serviceProvider.addService(service2);
serviceProvider.addService(service3);
}
| private static void displayServicesWithIndex(List<IService> services) { | 0 | 2023-11-24 05:32:52+00:00 | 2k |
feiniaojin/ddd-event-sourcing | ddd-event-sourcing-ui-web/src/main/java/com/feiniaojin/ddd/eventsourcing/ui/web/controller/ProductController.java | [
{
"identifier": "ProductApplicationService",
"path": "ddd-event-sourcing-application-service/src/main/java/com/feiniaojin/ddd/eventsourcing/application/service/ProductApplicationService.java",
"snippet": "@Service\npublic class ProductApplicationService {\n\n private ProductFactory productFactory = n... | import com.feiniaojin.ddd.eventsourcing.application.service.ProductApplicationService;
import com.feiniaojin.ddd.eventsourcing.application.service.command.processor.ProductPictureChangeCommandProcessor;
import com.feiniaojin.ddd.eventsourcing.domain.commands.ProductCountReduceCommand;
import com.feiniaojin.ddd.eventsourcing.domain.commands.ProductCreateCommand;
import com.feiniaojin.ddd.eventsourcing.domain.commands.ProductPictureChangeCommand;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource; | 1,182 | package com.feiniaojin.ddd.eventsourcing.ui.web.controller;
@RestController
@RequestMapping("/product")
public class ProductController {
@Resource | package com.feiniaojin.ddd.eventsourcing.ui.web.controller;
@RestController
@RequestMapping("/product")
public class ProductController {
@Resource | private ProductApplicationService productApplicationService; | 0 | 2023-11-25 09:19:45+00:00 | 2k |
sakura-ryoko/afkplus | src/main/java/io/github/sakuraryoko/afkplus/events/ServerEvents.java | [
{
"identifier": "AfkPlusConflicts",
"path": "src/main/java/io/github/sakuraryoko/afkplus/util/AfkPlusConflicts.java",
"snippet": "public class AfkPlusConflicts {\n public static boolean checkMods() {\n String modTarget;\n String modVer;\n String modName;\n ModMetadata modD... | import java.util.Collection;
import io.github.sakuraryoko.afkplus.util.AfkPlusConflicts;
import io.github.sakuraryoko.afkplus.util.AfkPlusLogger;
import net.minecraft.server.MinecraftServer; | 1,520 | package io.github.sakuraryoko.afkplus.events;
public class ServerEvents {
static private Collection<String> dpCollection;
public static void starting(MinecraftServer server) {
AfkPlusLogger.debug("Server is starting. " + server.getName());
}
public static void started(MinecraftServer server) {
dpCollection = server.getDataPackManager().getEnabledNames(); | package io.github.sakuraryoko.afkplus.events;
public class ServerEvents {
static private Collection<String> dpCollection;
public static void starting(MinecraftServer server) {
AfkPlusLogger.debug("Server is starting. " + server.getName());
}
public static void started(MinecraftServer server) {
dpCollection = server.getDataPackManager().getEnabledNames(); | if (!AfkPlusConflicts.checkDatapacks(dpCollection)) | 0 | 2023-11-22 00:21:36+00:00 | 2k |
sddevelopment-be/modular-validators | src/test/java/be/sddevelopment/validation/specs/usage/BasicUsageTest.java | [
{
"identifier": "CheckedTestUtils",
"path": "src/test/java/be/sddevelopment/validation/CheckedTestUtils.java",
"snippet": "public final class CheckedTestUtils {\n\n private CheckedTestUtils() throws IllegalAccessException {\n throw new IllegalAccessException(\"Utility classes (containing share... | import be.sddevelopment.validation.CheckedTestUtils;
import be.sddevelopment.validation.core.Constraint;
import be.sddevelopment.validation.core.InvalidObjectException;
import net.serenitybdd.annotations.Description;
import net.serenitybdd.junit5.SerenityJUnit5Extension;
import org.assertj.core.api.WithAssertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.time.LocalDate;
import java.util.Objects;
import static be.sddevelopment.validation.core.ModularRuleset.aValid;
import static be.sddevelopment.validation.core.Constraints.haveNonNullField;
import static java.time.Month.MARCH;
import static java.util.Optional.ofNullable; | 1,086 | package be.sddevelopment.validation.specs.usage;
@DisplayName("Basic Usage")
@ExtendWith(SerenityJUnit5Extension.class)
@Description("This test suite verifies that the basic usage of the library is correct.")
class BasicUsageTest implements WithAssertions {
@Nested
@DisplayName("Can be used as Validators")
@Description("These tests illustrate using the libraries as validators through close-to-real examples.")
class ValidatorUsage {
@Test
void modularValidatorsMustCoverBasicUsage_givenSimpleDateBasedValidationLogic() {
var toValidate = new DateBasedDummyObject(LocalDate.of(2023, MARCH, 9));
assertThat(toValidate).isNotNull()
.extracting(DateBasedDummyObject::localDate)
.isNotNull();
var notBeNull = new Constraint<DateBasedDummyObject>(Objects::nonNull, "not be null");
var validator = aValid(DateBasedDummyObject.class)
.must(notBeNull)
.must(haveNonNullField(DateBasedDummyObject::localDate), "have a non-null local date")
.iHaveSpoken();
assertThat(validator.constrain(toValidate)).is(CheckedTestUtils.valid());
}
private record DateBasedDummyObject(LocalDate localDate) {
}
}
@Nested
@DisplayName("Constrained objects should allow for fluent usage")
@Description("These tests illustrate using the Constrainable monad as a guard against invalid objects.")
class ConstrainableUsage {
@Test
@DisplayName("when used as a guard clause")
void checkedShouldAllowForFluentUsage_whenUsingItAsAGuard_givenInvalidObject() {
var validator = aValid(DateBasedDummyObject.class)
.must(Objects::nonNull, "not be null")
.must(haveNonNullField(DateBasedDummyObject::localDate), "have a non-null local date")
.must(this::haveAName, "have a name")
.iHaveSpoken();
var toValidate = new DateBasedDummyObject("", LocalDate.of(2023, MARCH, 9));
assertThat(validator.constrain(toValidate)).matches(dateBasedDummyObjectConstrainable -> !dateBasedDummyObjectConstrainable.isValid());
var result = validator.constrain(toValidate);
| package be.sddevelopment.validation.specs.usage;
@DisplayName("Basic Usage")
@ExtendWith(SerenityJUnit5Extension.class)
@Description("This test suite verifies that the basic usage of the library is correct.")
class BasicUsageTest implements WithAssertions {
@Nested
@DisplayName("Can be used as Validators")
@Description("These tests illustrate using the libraries as validators through close-to-real examples.")
class ValidatorUsage {
@Test
void modularValidatorsMustCoverBasicUsage_givenSimpleDateBasedValidationLogic() {
var toValidate = new DateBasedDummyObject(LocalDate.of(2023, MARCH, 9));
assertThat(toValidate).isNotNull()
.extracting(DateBasedDummyObject::localDate)
.isNotNull();
var notBeNull = new Constraint<DateBasedDummyObject>(Objects::nonNull, "not be null");
var validator = aValid(DateBasedDummyObject.class)
.must(notBeNull)
.must(haveNonNullField(DateBasedDummyObject::localDate), "have a non-null local date")
.iHaveSpoken();
assertThat(validator.constrain(toValidate)).is(CheckedTestUtils.valid());
}
private record DateBasedDummyObject(LocalDate localDate) {
}
}
@Nested
@DisplayName("Constrained objects should allow for fluent usage")
@Description("These tests illustrate using the Constrainable monad as a guard against invalid objects.")
class ConstrainableUsage {
@Test
@DisplayName("when used as a guard clause")
void checkedShouldAllowForFluentUsage_whenUsingItAsAGuard_givenInvalidObject() {
var validator = aValid(DateBasedDummyObject.class)
.must(Objects::nonNull, "not be null")
.must(haveNonNullField(DateBasedDummyObject::localDate), "have a non-null local date")
.must(this::haveAName, "have a name")
.iHaveSpoken();
var toValidate = new DateBasedDummyObject("", LocalDate.of(2023, MARCH, 9));
assertThat(validator.constrain(toValidate)).matches(dateBasedDummyObjectConstrainable -> !dateBasedDummyObjectConstrainable.isValid());
var result = validator.constrain(toValidate);
| assertThatExceptionOfType(InvalidObjectException.class) | 1 | 2023-11-26 08:04:15+00:00 | 2k |
DewmithMihisara/car-rental-hibernate | src/main/java/lk/ijse/bo/custom/impl/ActiveRentBOImpl.java | [
{
"identifier": "ActiveRentBO",
"path": "src/main/java/lk/ijse/bo/custom/ActiveRentBO.java",
"snippet": "public interface ActiveRentBO extends SuperBO {\n List<RentDto> getAllActive();\n}"
},
{
"identifier": "DAOFactory",
"path": "src/main/java/lk/ijse/dao/DAOFactory.java",
"snippet":... | import lk.ijse.bo.custom.ActiveRentBO;
import lk.ijse.dao.DAOFactory;
import lk.ijse.dao.custom.RentDAO;
import lk.ijse.dto.CarDto;
import lk.ijse.dto.RentDto;
import lk.ijse.entity.Car;
import lk.ijse.entity.Rent;
import java.util.ArrayList;
import java.util.List; | 1,573 | package lk.ijse.bo.custom.impl;
public class ActiveRentBOImpl implements ActiveRentBO {
RentDAO rentDAO= (RentDAO) DAOFactory.getInstance().getDAO(DAOFactory.DAOTypes.RENT);
@Override | package lk.ijse.bo.custom.impl;
public class ActiveRentBOImpl implements ActiveRentBO {
RentDAO rentDAO= (RentDAO) DAOFactory.getInstance().getDAO(DAOFactory.DAOTypes.RENT);
@Override | public List<RentDto> getAllActive() { | 4 | 2023-11-27 17:28:48+00:00 | 2k |
inferior3x/JNU-course-seat-alert-Server | src/main/java/com/coco3x/jnu_course_seat_alert/repository/ApplicantRepository.java | [
{
"identifier": "Applicant",
"path": "src/main/java/com/coco3x/jnu_course_seat_alert/domain/entity/Applicant.java",
"snippet": "@Getter\n@Entity\n@NoArgsConstructor\n@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {\"user_id\", \"course_id\"})})\npublic class Applicant {\n @Id\n @Gener... | import com.coco3x.jnu_course_seat_alert.domain.entity.Applicant;
import com.coco3x.jnu_course_seat_alert.domain.entity.Course;
import com.coco3x.jnu_course_seat_alert.domain.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
import java.util.Optional; | 801 | package com.coco3x.jnu_course_seat_alert.repository;
public interface ApplicantRepository extends JpaRepository<Applicant, Long> {
List<Applicant> findApplicantsByUser(User user); | package com.coco3x.jnu_course_seat_alert.repository;
public interface ApplicantRepository extends JpaRepository<Applicant, Long> {
List<Applicant> findApplicantsByUser(User user); | void deleteApplicantByUserAndCourse(User user, Course course); | 1 | 2023-11-26 05:01:32+00:00 | 2k |
feiniaojin/ddd-event-sourcing-snapshot | ddd-event-sourcing-snapshot-infrastructure-persistence/src/main/java/com/feiniaojin/ddd/eventsourcing/infrastructure/persistence/ProductRepositoryImpl.java | [
{
"identifier": "Entity",
"path": "ddd-event-sourcing-snapshot-infrastructure-persistence/src/main/java/com/feiniaojin/ddd/eventsourcing/infrastructure/persistence/jdbc/data/Entity.java",
"snippet": "@Data\n@Table(\"t_entity\")\n@Generated(\"generator\")\npublic class Entity implements Serializable {\n ... | import com.feiniaojin.ddd.eventsourcing.domain.*;
import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.data.Entity;
import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.data.Event;
import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.data.Snapshot;
import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.repository.EntityJdbcRepository;
import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.repository.EventJdbcRepository;
import com.feiniaojin.ddd.eventsourcing.infrastructure.persistence.jdbc.repository.SnapshotJdbcRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; | 1,503 | package com.feiniaojin.ddd.eventsourcing.infrastructure.persistence;
@Component
public class ProductRepositoryImpl implements ProductRepository {
ProductFactory productFactory = new ProductFactory();
@Resource
private EventJdbcRepository eventJdbcRepository;
@Resource
private EntityJdbcRepository entityJdbcRepository;
@Resource | package com.feiniaojin.ddd.eventsourcing.infrastructure.persistence;
@Component
public class ProductRepositoryImpl implements ProductRepository {
ProductFactory productFactory = new ProductFactory();
@Resource
private EventJdbcRepository eventJdbcRepository;
@Resource
private EntityJdbcRepository entityJdbcRepository;
@Resource | private SnapshotJdbcRepository snapshotJdbcRepository; | 5 | 2023-11-25 09:36:05+00:00 | 2k |
clasSeven7/sebo-cultural | src/Infrastructure/EstoqueRepository.java | [
{
"identifier": "IEstoqueRepository",
"path": "src/Domain/Repositories/IEstoqueRepository.java",
"snippet": "public interface IEstoqueRepository {\n Estoque buscar();\n void salvar(ArrayList<ItemEstoque> items);\n}"
},
{
"identifier": "UniqueIdGenerator",
"path": "src/Shared/Utils/Uniq... | import Domain.Entities.*;
import Domain.Repositories.IEstoqueRepository;
import Shared.Utils.UniqueIdGenerator;
import org.json.JSONObject;
import java.util.ArrayList; | 730 | package Infrastructure;
public class EstoqueRepository extends JSONRepository<ItemEstoque> implements IEstoqueRepository {
public EstoqueRepository() {
super(ItemEstoque.class);
}
public Estoque buscar() {
var items = this.buscarDoJson();
var estoque = new Estoque();
for (ItemEstoque itemEstoque:items) {
estoque.adicionar(itemEstoque.getItem(), itemEstoque.getQuantidade(), itemEstoque.getPreco());
}
return estoque;
}
public void salvar(ArrayList<ItemEstoque> items) {
this.salvarNoJson(items);
}
@Override
protected ItemEstoque criarInstanciaAPartirDoJson(JSONObject jsonObject) {
var itemBibliotecaObject = jsonObject.getJSONObject("item");
var itemBibliotecaType = itemBibliotecaObject.getEnum(TipoItemBiblioteca.class, "tipo");
var itemBiblioteca = itemBibliotecaType == TipoItemBiblioteca.LIVRO
? new Livro(itemBibliotecaObject.getString("id"), itemBibliotecaObject.getString("titulo"),
itemBibliotecaObject.getString("genero"),
itemBibliotecaObject.getString("autor"),
itemBibliotecaObject.getInt("anoPublicacao"),
itemBibliotecaObject.getString("editora"))
: new Revista(itemBibliotecaObject.getString("id"), itemBibliotecaObject.getString("titulo"),
itemBibliotecaObject.getString("genero"),
itemBibliotecaObject.getString("autor"),
itemBibliotecaObject.getInt("anoPublicacao"),
itemBibliotecaObject.getString("editora"));
return new ItemEstoque(
itemBiblioteca,
jsonObject.getInt("quantidade"),
jsonObject.getDouble("preco")
);
}
@Override
protected JSONObject criarJsonAPartirDaInstancia(ItemEstoque entidade) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("quantidade", entidade.getQuantidade());
jsonObject.put("preco", entidade.getPreco());
var itemBibliotecaJsonObject = new JSONObject();
itemBibliotecaJsonObject.put("id", entidade.getItem().getId());
itemBibliotecaJsonObject.put("titulo", entidade.getItem().getTitulo());
itemBibliotecaJsonObject.put("tipo", entidade.getItem().getTipo());
itemBibliotecaJsonObject.put("genero", entidade.getItem().getGenero());
itemBibliotecaJsonObject.put("autor", entidade.getItem().getAutor());
itemBibliotecaJsonObject.put("anoPublicacao", entidade.getItem().getAnoPublicacao());
itemBibliotecaJsonObject.put("editora", entidade.getItem().getEditora());
jsonObject.put("item", itemBibliotecaJsonObject);
return jsonObject;
}
protected String getId(ItemEstoque entidade) { | package Infrastructure;
public class EstoqueRepository extends JSONRepository<ItemEstoque> implements IEstoqueRepository {
public EstoqueRepository() {
super(ItemEstoque.class);
}
public Estoque buscar() {
var items = this.buscarDoJson();
var estoque = new Estoque();
for (ItemEstoque itemEstoque:items) {
estoque.adicionar(itemEstoque.getItem(), itemEstoque.getQuantidade(), itemEstoque.getPreco());
}
return estoque;
}
public void salvar(ArrayList<ItemEstoque> items) {
this.salvarNoJson(items);
}
@Override
protected ItemEstoque criarInstanciaAPartirDoJson(JSONObject jsonObject) {
var itemBibliotecaObject = jsonObject.getJSONObject("item");
var itemBibliotecaType = itemBibliotecaObject.getEnum(TipoItemBiblioteca.class, "tipo");
var itemBiblioteca = itemBibliotecaType == TipoItemBiblioteca.LIVRO
? new Livro(itemBibliotecaObject.getString("id"), itemBibliotecaObject.getString("titulo"),
itemBibliotecaObject.getString("genero"),
itemBibliotecaObject.getString("autor"),
itemBibliotecaObject.getInt("anoPublicacao"),
itemBibliotecaObject.getString("editora"))
: new Revista(itemBibliotecaObject.getString("id"), itemBibliotecaObject.getString("titulo"),
itemBibliotecaObject.getString("genero"),
itemBibliotecaObject.getString("autor"),
itemBibliotecaObject.getInt("anoPublicacao"),
itemBibliotecaObject.getString("editora"));
return new ItemEstoque(
itemBiblioteca,
jsonObject.getInt("quantidade"),
jsonObject.getDouble("preco")
);
}
@Override
protected JSONObject criarJsonAPartirDaInstancia(ItemEstoque entidade) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("quantidade", entidade.getQuantidade());
jsonObject.put("preco", entidade.getPreco());
var itemBibliotecaJsonObject = new JSONObject();
itemBibliotecaJsonObject.put("id", entidade.getItem().getId());
itemBibliotecaJsonObject.put("titulo", entidade.getItem().getTitulo());
itemBibliotecaJsonObject.put("tipo", entidade.getItem().getTipo());
itemBibliotecaJsonObject.put("genero", entidade.getItem().getGenero());
itemBibliotecaJsonObject.put("autor", entidade.getItem().getAutor());
itemBibliotecaJsonObject.put("anoPublicacao", entidade.getItem().getAnoPublicacao());
itemBibliotecaJsonObject.put("editora", entidade.getItem().getEditora());
jsonObject.put("item", itemBibliotecaJsonObject);
return jsonObject;
}
protected String getId(ItemEstoque entidade) { | return UniqueIdGenerator.generate(); | 1 | 2023-11-19 02:11:46+00:00 | 2k |
eduardoAssuncao/API-Restful-com-Spring-Boot | src/test/java/com/todolist/todolist/TodolistApplicationTests.java | [
{
"identifier": "Tarefa",
"path": "src/main/java/com/todolist/todolist/entity/Tarefa.java",
"snippet": "@Entity\npublic class Tarefa extends RepresentationModel<Tarefa>{\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String descricao;\n\n @Man... | import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.web.reactive.server.WebTestClient;
import com.todolist.todolist.entity.Tarefa;
import com.todolist.todolist.entity.Usuario; | 781 | package com.todolist.todolist;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class TodolistApplicationTests {
@Autowired
private WebTestClient webTestClient;
@Test
void testeCriarUsuario() { | package com.todolist.todolist;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class TodolistApplicationTests {
@Autowired
private WebTestClient webTestClient;
@Test
void testeCriarUsuario() { | var usuario = new Usuario("Eduardo"); | 1 | 2023-11-26 15:15:18+00:00 | 2k |
lk-eternal/AI-Assistant-Plus | src/main/java/lk/eternal/ai/model/plugin/PluginModel.java | [
{
"identifier": "Message",
"path": "src/main/java/lk/eternal/ai/dto/req/Message.java",
"snippet": "@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)\n@JsonIgnoreProperties(\"think\")\npublic final class Message {\n private String role;\n private String content;\n private List<GPT... | import lk.eternal.ai.dto.req.Message;
import lk.eternal.ai.dto.resp.ChatResp;
import lk.eternal.ai.model.ai.AiModel;
import lk.eternal.ai.plugin.Plugin;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier; | 931 | package lk.eternal.ai.model.plugin;
public interface PluginModel {
String getName();
| package lk.eternal.ai.model.plugin;
public interface PluginModel {
String getName();
| void question(AiModel aiModel, LinkedList<Message> messages, List<Plugin> plugins, Function<String, Map<String, Object>> pluginProperties, Supplier<Boolean> stopCheck, Consumer<ChatResp> respConsumer); | 1 | 2023-11-23 01:12:34+00:00 | 2k |
Guan-Meng-Yuan/spring-ex | spring-cloud-starter-auth/src/main/java/com/guanmengyuan/spring/ex/auth/config/SaTokenConfiguration.java | [
{
"identifier": "GlobalResponseConstant",
"path": "spring-ex-common-model/src/main/java/com/guanmengyuan/spring/ex/common/model/constant/GlobalResponseConstant.java",
"snippet": "public interface GlobalResponseConstant {\n /**\n * 默认白名单路径\n */\n Set<String> DEFAULT_PATH = SetUtil.of(\"/v3/... | import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.same.SaSameUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.guanmengyuan.spring.ex.common.model.constant.GlobalResponseConstant;
import com.guanmengyuan.spring.ex.common.model.enums.ResEnum;
import com.guanmengyuan.spring.ex.common.model.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order; | 1,195 | package com.guanmengyuan.spring.ex.auth.config;
@Configuration
@EnableConfigurationProperties(AuthConfigProperties.class)
@RequiredArgsConstructor
@Order(-100)
public class SaTokenConfiguration {
private final AuthConfigProperties authConfigProperties;
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public SaServletFilter saServletFilter() {
authConfigProperties.getWhitelist().addAll(GlobalResponseConstant.DEFAULT_PATH);
return new SaServletFilter()
.addInclude("/**")
.addExclude(authConfigProperties.getWhitelist().toArray(new String[0]))
.setAuth(obj -> {
SaRouter.match("/**", StpUtil::checkLogin);
SaRouter.match("/**", () -> {
if (SaManager.getConfig().getCheckSameToken()) {
SaSameUtil.checkCurrentRequestToken();
}
});
}).setError(e -> { | package com.guanmengyuan.spring.ex.auth.config;
@Configuration
@EnableConfigurationProperties(AuthConfigProperties.class)
@RequiredArgsConstructor
@Order(-100)
public class SaTokenConfiguration {
private final AuthConfigProperties authConfigProperties;
@Bean
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public SaServletFilter saServletFilter() {
authConfigProperties.getWhitelist().addAll(GlobalResponseConstant.DEFAULT_PATH);
return new SaServletFilter()
.addInclude("/**")
.addExclude(authConfigProperties.getWhitelist().toArray(new String[0]))
.setAuth(obj -> {
SaRouter.match("/**", StpUtil::checkLogin);
SaRouter.match("/**", () -> {
if (SaManager.getConfig().getCheckSameToken()) {
SaSameUtil.checkCurrentRequestToken();
}
});
}).setError(e -> { | throw new ServiceException(ResEnum.UNAUTHORIZED); | 1 | 2023-11-21 09:20:17+00:00 | 2k |
davidtongeo/netj | Main.java | [
{
"identifier": "httpClass",
"path": "httpClass/httpClass.java",
"snippet": "public class httpClass {\n\tprivate HttpClient client;\n\tprivate URI url;\n\n\tpublic void makeRequest(Verbs verb, String[] headers, String body, Boolean showBody) {\n\t\ttry {\n\t\t\tif (verb == Verbs.GET) {\n\t\t\t\tif (show... | import httpClass.httpClass;
import cliClass.manual;
import cliClass.parseClass; | 1,229 |
class Main {
public static void main(String[] a) {
// Parsing the arguments.
if (a.length < 1) {
System.err.println("[ERROR] No arguments provided.");
return;
} |
class Main {
public static void main(String[] a) {
// Parsing the arguments.
if (a.length < 1) {
System.err.println("[ERROR] No arguments provided.");
return;
} | parseClass Args = null; | 2 | 2023-11-25 22:51:00+00:00 | 2k |
lushangkan/AutoLogin | src/main/java/cn/cutemc/autologin/AutoLogin.java | [
{
"identifier": "ModConfig",
"path": "src/main/java/cn/cutemc/autologin/config/ModConfig.java",
"snippet": "public class ModConfig {\n\n public MainConfig mainConfig;\n\n public ModConfig() {\n AutoConfig.register(MainConfig.class, GsonConfigSerializer::new);\n mainConfig = AutoConfi... | import cn.cutemc.autologin.config.ModConfig;
import cn.cutemc.autologin.listeners.SystemMsgListener;
import cn.cutemc.autologin.records.ServerStatus;
import lombok.extern.log4j.Log4j2;
import net.fabricmc.api.ClientModInitializer; | 939 | package cn.cutemc.autologin;
@Log4j2
public class AutoLogin implements ClientModInitializer {
public static ModConfig modConfig;
public static volatile ServerStatus server = null;
@Override
public void onInitializeClient() {
log.info("Initializing AutoLogin...");
log.info("Loading config...");
modConfig = new ModConfig();
log.info("Registering listeners..."); | package cn.cutemc.autologin;
@Log4j2
public class AutoLogin implements ClientModInitializer {
public static ModConfig modConfig;
public static volatile ServerStatus server = null;
@Override
public void onInitializeClient() {
log.info("Initializing AutoLogin...");
log.info("Loading config...");
modConfig = new ModConfig();
log.info("Registering listeners..."); | new SystemMsgListener(); | 1 | 2023-11-23 12:22:06+00:00 | 2k |
Neelesh-Janga/23-Java-Design-Patterns | src/com/neelesh/design/patterns/structural/bridge/BridgeTest.java | [
{
"identifier": "AdvanceRemote",
"path": "src/com/neelesh/design/patterns/structural/bridge/components/remote/AdvanceRemote.java",
"snippet": "public interface AdvanceRemote extends Remote{\n void netflix();\n void amazonPrime();\n}"
},
{
"identifier": "Remote",
"path": "src/com/neeles... | import com.neelesh.design.patterns.structural.bridge.components.remote.AdvanceRemote;
import com.neelesh.design.patterns.structural.bridge.components.remote.Remote;
import com.neelesh.design.patterns.structural.bridge.components.remote.SamsungRemote;
import com.neelesh.design.patterns.structural.bridge.components.remote.SonyRemote;
import com.neelesh.design.patterns.structural.bridge.components.tv.SamsungTV;
import com.neelesh.design.patterns.structural.bridge.components.tv.SonyTV; | 1,034 | package com.neelesh.design.patterns.structural.bridge;
public class BridgeTest {
public static void main(String[] args) { | package com.neelesh.design.patterns.structural.bridge;
public class BridgeTest {
public static void main(String[] args) { | AdvanceRemote sonyRemote = new SonyRemote(new SonyTV()); | 0 | 2023-11-22 10:19:01+00:00 | 2k |
TioStitch/Dark-Geometry-Cube | src/tiostitch/geometry/cube/Main.java | [
{
"identifier": "CharController",
"path": "src/tiostitch/geometry/cube/controllers/CharController.java",
"snippet": "public class CharController {\r\n\r\n private int x;\r\n private int y;\r\n private final int width;\r\n private final int height;\r\n\r\n public CharController(int x, int ... | import tiostitch.geometry.cube.controllers.CharController;
import tiostitch.geometry.cube.controllers.ImgController;
import tiostitch.geometry.cube.controllers.KeyController;
import javax.swing.*;
| 910 | package tiostitch.geometry.cube;
public class Main extends JFrame {
private final ImageIcon logoDraw = new ImageIcon(getClass().getResource("Backgrounds/Logodraw.png"));
private final ImageIcon backDraw = ImgController.resizeImageGif(new ImageIcon(getClass().getResource("Backgrounds/Backdraw.png")), 510, 408);
private static final CharController player = new CharController(50, 50, 40, 40);
| package tiostitch.geometry.cube;
public class Main extends JFrame {
private final ImageIcon logoDraw = new ImageIcon(getClass().getResource("Backgrounds/Logodraw.png"));
private final ImageIcon backDraw = ImgController.resizeImageGif(new ImageIcon(getClass().getResource("Backgrounds/Backdraw.png")), 510, 408);
private static final CharController player = new CharController(50, 50, 40, 40);
| private final KeyController keyController = new KeyController();
| 2 | 2023-11-26 03:55:24+00:00 | 2k |
A-BigTree/tree-learning-notes | 数据库/MySQL/code/jdbc_test/src/com/test/MainTest.java | [
{
"identifier": "User",
"path": "数据库/MySQL/code/dynamic_web_test/pro2_crud/src/com/beans/User.java",
"snippet": "public class User {\n private String userId;\n private String userName;\n private double salary;\n\n public User(){\n\n }\n\n public User(String userId, String userName, dou... | import com.beans.User;
import com.impl.UserImpl; | 649 | /**
* ==================================================
* Project: jdbc_test
* Package: com
* =====================================================
* Title: Main.java
* Created: [2023/3/15 20:53] by Shuxin-Wang
* =====================================================
* Description: description here
* =====================================================
* Revised History:
* 1. 2023/3/15, created by Shuxin-Wang.
* 2.
*/
package com.test;
public class MainTest {
public static void main(String[]args){
UserImpl userImpl = new UserImpl();
// 查找
System.out.println(userImpl.getUserById("000000")); | /**
* ==================================================
* Project: jdbc_test
* Package: com
* =====================================================
* Title: Main.java
* Created: [2023/3/15 20:53] by Shuxin-Wang
* =====================================================
* Description: description here
* =====================================================
* Revised History:
* 1. 2023/3/15, created by Shuxin-Wang.
* 2.
*/
package com.test;
public class MainTest {
public static void main(String[]args){
UserImpl userImpl = new UserImpl();
// 查找
System.out.println(userImpl.getUserById("000000")); | User user1 = new User("000004", "小云", 1000.99); | 0 | 2023-11-20 06:26:05+00:00 | 2k |
FalkorDB/JFalkorDB | src/main/java/com/falkordb/impl/graph_cache/GraphCacheList.java | [
{
"identifier": "Record",
"path": "src/main/java/com/falkordb/Record.java",
"snippet": "public interface Record {\n\n /**\n * The value at the given field index\n * \n * @param index field index\n * @param <T> return value type\n * \n * @return the value\n */\n <T> T getValue(int index);... | import com.falkordb.Record;
import com.falkordb.Graph;
import com.falkordb.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; | 1,546 | package com.falkordb.impl.graph_cache;
/**
* Represents a local cache of list of strings. Holds data from a specific procedure, for a specific graph.
*/
class GraphCacheList {
private final String procedure;
private final List<String> data = new CopyOnWriteArrayList<>();
/**
* @param procedure - exact procedure command
*/
public GraphCacheList(String procedure) {
this.procedure = procedure;
}
/**
* A method to return a cached item if it is in the cache, or re-validate the cache if its invalidated
* @param index index of data item
* @return The string value of the specific procedure response, at the given index.
*/
public String getCachedData(int index, Graph graph) {
if (index >= data.size()) {
synchronized (data){
if (index >= data.size()) {
getProcedureInfo(graph);
}
}
}
return data.get(index);
}
/**
* Auxiliary method to parse a procedure result set and refresh the cache
*/
private void getProcedureInfo(Graph graph) { | package com.falkordb.impl.graph_cache;
/**
* Represents a local cache of list of strings. Holds data from a specific procedure, for a specific graph.
*/
class GraphCacheList {
private final String procedure;
private final List<String> data = new CopyOnWriteArrayList<>();
/**
* @param procedure - exact procedure command
*/
public GraphCacheList(String procedure) {
this.procedure = procedure;
}
/**
* A method to return a cached item if it is in the cache, or re-validate the cache if its invalidated
* @param index index of data item
* @return The string value of the specific procedure response, at the given index.
*/
public String getCachedData(int index, Graph graph) {
if (index >= data.size()) {
synchronized (data){
if (index >= data.size()) {
getProcedureInfo(graph);
}
}
}
return data.get(index);
}
/**
* Auxiliary method to parse a procedure result set and refresh the cache
*/
private void getProcedureInfo(Graph graph) { | ResultSet resultSet = graph.callProcedure(procedure); | 2 | 2023-11-26 13:38:14+00:00 | 2k |
EcoNetsTech/spore-spring-boot-starter | src/main/java/cn/econets/ximutech/spore/config/RetrofitProperties.java | [
{
"identifier": "GlobalRetryProperty",
"path": "src/main/java/cn/econets/ximutech/spore/retry/GlobalRetryProperty.java",
"snippet": "@Data\npublic class GlobalRetryProperty {\n\n /**\n * 是否启用全局重试,启用的话,所有HTTP请求都会自动重试。\n * 否则的话,只有被 {@link Retry}标注的接口才会执行重试。\n * 接口上Retry注解属性优先于全局配置。\n */... | import cn.econets.ximutech.spore.retry.GlobalRetryProperty;
import cn.econets.ximutech.spore.Constants;
import cn.econets.ximutech.spore.log.GlobalLogProperty;
import cn.econets.ximutech.spore.retrofit.converter.BaseTypeConverterFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.converter.jackson.JacksonConverterFactory; | 1,344 | package cn.econets.ximutech.spore.config;
/**
* @author ximu
*/
@ConfigurationProperties(prefix = Constants.RETROFIT)
@Data
public class RetrofitProperties {
/**
* 全局的重试配置
*/
@NestedConfigurationProperty | package cn.econets.ximutech.spore.config;
/**
* @author ximu
*/
@ConfigurationProperties(prefix = Constants.RETROFIT)
@Data
public class RetrofitProperties {
/**
* 全局的重试配置
*/
@NestedConfigurationProperty | private GlobalRetryProperty globalRetry = new GlobalRetryProperty(); | 0 | 2023-11-21 18:00:50+00:00 | 2k |
NBHZW/hnustDatabaseCourseDesign | ruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/service/impl/ClazzServiceImpl.java | [
{
"identifier": "ClazzMapper",
"path": "ruoyi-studentInformation/src/main/java/com/ruoyi/studentInformation/mapper/ClazzMapper.java",
"snippet": "public interface ClazzMapper\n{\n /**\n * 查询班级信息\n *\n * @param id 班级信息主键\n * @return 班级信息\n */\n public Clazz selectClazzById(Long ... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.studentInformation.mapper.ClazzMapper;
import com.ruoyi.studentInformation.domain.Clazz;
import com.ruoyi.studentInformation.service.IClazzService; | 1,191 | package com.ruoyi.studentInformation.service.impl;
/**
* 班级信息Service业务层处理
*
* @author ruoyi
* @date 2023-11-07
*/
@Service
public class ClazzServiceImpl implements IClazzService
{
@Autowired | package com.ruoyi.studentInformation.service.impl;
/**
* 班级信息Service业务层处理
*
* @author ruoyi
* @date 2023-11-07
*/
@Service
public class ClazzServiceImpl implements IClazzService
{
@Autowired | private ClazzMapper clazzMapper; | 0 | 2023-11-25 02:50:45+00:00 | 2k |
isXander/YetAnotherUILib | src/main/java/dev/isxander/yaul3/YAUL.java | [
{
"identifier": "ImageRendererManager",
"path": "src/main/java/dev/isxander/yaul3/api/image/ImageRendererManager.java",
"snippet": "public interface ImageRendererManager {\n static ImageRendererManager getInstance() {\n return YAUL.getInstance().imageRendererManager;\n }\n\n <T extends I... | import dev.isxander.yaul3.api.image.ImageRendererManager;
import dev.isxander.yaul3.impl.image.ImageRendererManagerImpl;
import net.fabricmc.api.ClientModInitializer; | 1,193 | package dev.isxander.yaul3;
public class YAUL implements ClientModInitializer {
private static YAUL instance = null; | package dev.isxander.yaul3;
public class YAUL implements ClientModInitializer {
private static YAUL instance = null; | public ImageRendererManager imageRendererManager; | 0 | 2023-11-25 13:11:05+00:00 | 2k |
huangwei021230/memo | app/src/main/java/com/huawei/cloud/drive/hms/CloudDBManager.java | [
{
"identifier": "MemoInfo",
"path": "app/src/main/java/com/huawei/cloud/drive/bean/MemoInfo.java",
"snippet": "@PrimaryKeys({\"id\"})\npublic final class MemoInfo extends CloudDBZoneObject implements Serializable {\n private Long id;\n\n private String title;\n\n private String content;\n\n ... | import android.content.Context;
import android.util.Log;
import com.huawei.agconnect.cloud.database.AGConnectCloudDB;
import com.huawei.agconnect.cloud.database.CloudDBZone;
import com.huawei.agconnect.cloud.database.CloudDBZoneConfig;
import com.huawei.agconnect.cloud.database.CloudDBZoneObjectList;
import com.huawei.agconnect.cloud.database.CloudDBZoneQuery;
import com.huawei.agconnect.cloud.database.CloudDBZoneSnapshot;
import com.huawei.agconnect.cloud.database.ListenerHandler;
import com.huawei.agconnect.cloud.database.OnSnapshotListener;
import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException;
import com.huawei.cloud.drive.bean.MemoInfo;
import com.huawei.cloud.drive.bean.ObjectTypeInfoHelper;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; | 888 | package com.huawei.cloud.drive.hms;
/**
* Proxying implementation of CloudDBZone.
*/
public class CloudDBManager {
private static final String TAG = "CloudDBManager";
private AGConnectCloudDB mCloudDB;
private CloudDBZone mCloudDBZone;
private ListenerHandler mRegister;
private CloudDBZoneConfig mConfig;
private UiCallBack mUiCallBack = UiCallBack.DEFAULT;
private CloudDBZoneOpenCallback mCloudDBZoneOpenCallback;
public interface CloudDBZoneOpenCallback {
void onCloudDBZoneOpened(CloudDBZone cloudDBZone);
}
public interface MemoCallback { | package com.huawei.cloud.drive.hms;
/**
* Proxying implementation of CloudDBZone.
*/
public class CloudDBManager {
private static final String TAG = "CloudDBManager";
private AGConnectCloudDB mCloudDB;
private CloudDBZone mCloudDBZone;
private ListenerHandler mRegister;
private CloudDBZoneConfig mConfig;
private UiCallBack mUiCallBack = UiCallBack.DEFAULT;
private CloudDBZoneOpenCallback mCloudDBZoneOpenCallback;
public interface CloudDBZoneOpenCallback {
void onCloudDBZoneOpened(CloudDBZone cloudDBZone);
}
public interface MemoCallback { | void onSuccess(List<MemoInfo> memoInfoList); | 0 | 2023-11-25 07:44:41+00:00 | 2k |
kkyesyes/Multi-userCommunicationSystem-Client | src/com/kk/qqclient/service/UserClientService.java | [
{
"identifier": "Message",
"path": "src/com/kk/qqcommon/Message.java",
"snippet": "public class Message implements Serializable {\n public static final long serialVersionUID = 1L;\n\n private String sender;\n private String getter;\n\n private String content;\n private String sendTime;\n ... | import com.kk.qqcommon.Message;
import com.kk.qqcommon.MessageType;
import com.kk.qqcommon.Settings;
import com.kk.qqcommon.User;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket; | 1,061 | package com.kk.qqclient.service;
/**
* 用户注册和登录验证
*
* @author KK
* @version 1.0
*/
public class UserClientService {
private User u = new User();
private Socket socket;
/**
* 验证用户是否合法
* @param userId 用户ID
* @param pwd 用户密码
* @return 是否合法
*/
public boolean checkUser(String userId, String pwd) {
boolean b = false;
u.setUserId(userId);
u.setPasswd(pwd);
try {
socket = new Socket("115.236.153.174", 48255);
// 将用户信息发送至服务端验证登录
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(u);
// 读取从服务器回复的Message对象
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message ms = (Message)ois.readObject();
// 服务端返回登录是否成功 | package com.kk.qqclient.service;
/**
* 用户注册和登录验证
*
* @author KK
* @version 1.0
*/
public class UserClientService {
private User u = new User();
private Socket socket;
/**
* 验证用户是否合法
* @param userId 用户ID
* @param pwd 用户密码
* @return 是否合法
*/
public boolean checkUser(String userId, String pwd) {
boolean b = false;
u.setUserId(userId);
u.setPasswd(pwd);
try {
socket = new Socket("115.236.153.174", 48255);
// 将用户信息发送至服务端验证登录
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(u);
// 读取从服务器回复的Message对象
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
Message ms = (Message)ois.readObject();
// 服务端返回登录是否成功 | if (ms.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)) { | 1 | 2023-11-22 16:29:22+00:00 | 2k |
PacktPublishing/Mastering-the-Java-Virtual-Machine | chapter11/processor/src/main/java/expert/os/processor/FieldAnalyzer.java | [
{
"identifier": "MapperException",
"path": "chapter11/api/src/main/java/expert/os/api/MapperException.java",
"snippet": "public class MapperException extends RuntimeException {\n\n public MapperException(String message) {\n super(message);\n }\n\n public MapperException(String message, T... | import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import expert.os.api.Column;
import expert.os.api.Id;
import expert.os.api.MapperException;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import javax.tools.JavaFileObject;
import java.io.IOException;
import java.io.Writer;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import static expert.os.processor.ProcessorUtil.capitalize;
import static expert.os.processor.ProcessorUtil.getPackageName;
import static expert.os.processor.ProcessorUtil.getSimpleNameAsString; | 772 | package expert.os.processor;
public class FieldAnalyzer implements Supplier<String> {
private static final String TEMPLATE = "fieldmetadata.mustache";
private static final Predicate<Element> IS_METHOD = el -> el.getKind() == ElementKind.METHOD;
public static final Function<Element, String> ELEMENT_TO_STRING = el -> el.getSimpleName().toString();
private final Element field;
private final Mustache template;
private final ProcessingEnvironment processingEnv;
private final TypeElement entity;
FieldAnalyzer(Element field, ProcessingEnvironment processingEnv,
TypeElement entity) {
this.field = field;
this.processingEnv = processingEnv;
this.entity = entity;
this.template = createTemplate();
}
@Override
public String get() {
FieldModel metadata = getMetaData();
Filer filer = processingEnv.getFiler();
JavaFileObject fileObject = getFileObject(metadata, filer);
try (Writer writer = fileObject.openWriter()) {
template.execute(writer, metadata);
} catch (IOException exception) {
throw new MapperException("An error to compile the class: " +
metadata.getQualified(), exception);
}
return metadata.getQualified();
}
private JavaFileObject getFileObject(FieldModel metadata, Filer filer) {
try {
return filer.createSourceFile(metadata.getQualified(), entity);
} catch (IOException exception) {
throw new MapperException("An error to create the class: " +
metadata.getQualified(), exception);
}
}
private FieldModel getMetaData() {
final String fieldName = field.getSimpleName().toString();
final Predicate<Element> validName = el -> el.getSimpleName().toString() | package expert.os.processor;
public class FieldAnalyzer implements Supplier<String> {
private static final String TEMPLATE = "fieldmetadata.mustache";
private static final Predicate<Element> IS_METHOD = el -> el.getKind() == ElementKind.METHOD;
public static final Function<Element, String> ELEMENT_TO_STRING = el -> el.getSimpleName().toString();
private final Element field;
private final Mustache template;
private final ProcessingEnvironment processingEnv;
private final TypeElement entity;
FieldAnalyzer(Element field, ProcessingEnvironment processingEnv,
TypeElement entity) {
this.field = field;
this.processingEnv = processingEnv;
this.entity = entity;
this.template = createTemplate();
}
@Override
public String get() {
FieldModel metadata = getMetaData();
Filer filer = processingEnv.getFiler();
JavaFileObject fileObject = getFileObject(metadata, filer);
try (Writer writer = fileObject.openWriter()) {
template.execute(writer, metadata);
} catch (IOException exception) {
throw new MapperException("An error to compile the class: " +
metadata.getQualified(), exception);
}
return metadata.getQualified();
}
private JavaFileObject getFileObject(FieldModel metadata, Filer filer) {
try {
return filer.createSourceFile(metadata.getQualified(), entity);
} catch (IOException exception) {
throw new MapperException("An error to create the class: " +
metadata.getQualified(), exception);
}
}
private FieldModel getMetaData() {
final String fieldName = field.getSimpleName().toString();
final Predicate<Element> validName = el -> el.getSimpleName().toString() | .contains(capitalize(fieldName)); | 1 | 2023-11-23 12:21:20+00:00 | 2k |
ryosoraa/Elrys-RestClient | src/main/java/com/elrys/elrysrestclient/service/implement/UserServiceImpl.java | [
{
"identifier": "UtilsConfiguration",
"path": "src/main/java/com/elrys/elrysrestclient/configuration/UtilsConfiguration.java",
"snippet": "@Configuration\npublic class UtilsConfiguration{\n\n @Bean\n public Encode encode(){\n return new Encode();\n }\n\n @Bean\n public ObjectMapper... | import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.ExistsRequest;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import com.elrys.elrysrestclient.configuration.UtilsConfiguration;
import com.elrys.elrysrestclient.enums.Index;
import com.elrys.elrysrestclient.model.DataModel;
import com.elrys.elrysrestclient.model.LoginModel;
import com.elrys.elrysrestclient.model.UserModel;
import com.elrys.elrysrestclient.response.BodyResponse;
import com.elrys.elrysrestclient.response.DataResponse;
import com.elrys.elrysrestclient.service.interfaces.ClientService;
import com.elrys.elrysrestclient.service.interfaces.UserService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import netscape.javascript.JSObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.UUID; | 1,204 | package com.elrys.elrysrestclient.service.implement;
@Service
public class UserServiceImpl implements UserService {
@Autowired | package com.elrys.elrysrestclient.service.implement;
@Service
public class UserServiceImpl implements UserService {
@Autowired | ClientService client; | 7 | 2023-11-22 04:24:35+00:00 | 2k |
ugale-deepak3010/JavaReactCRUDFullStack_UserDatProject-Backend | FullStack_Project_SpringBoot_React/src/main/java/com/FullStack_Project_SpringBoot_React/Controller/UserDataController.java | [
{
"identifier": "UserData",
"path": "FullStack_Project_SpringBoot_React/src/main/java/com/FullStack_Project_SpringBoot_React/Model/UserData.java",
"snippet": "@Entity\npublic class UserData {\n\t@Id\n\t@GeneratedValue\n\tprivate Long id;\n\tprivate String username;\n\tprivate String name;\n\tprivate Str... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.FullStack_Project_SpringBoot_React.Model.UserData;
import com.FullStack_Project_SpringBoot_React.Project_Exception.UserDataNotFoundException;
import com.FullStack_Project_SpringBoot_React.Repository.UserRepository; | 678 | package com.FullStack_Project_SpringBoot_React.Controller;
@RestController
@CrossOrigin("http://localhost:3000/")
public class UserDataController {
@Autowired
UserRepository userRepository;
@PostMapping("user")
public UserData postUserDataByAPI(@RequestBody UserData userData) {
userRepository.save(userData);
return userData;
}
@GetMapping("user")
public List<UserData> getUserDataByAPI() {
return userRepository.findAll();
}
@GetMapping("user/{id}")
public UserData getUserDataByIdinAPI(@PathVariable Long id) { | package com.FullStack_Project_SpringBoot_React.Controller;
@RestController
@CrossOrigin("http://localhost:3000/")
public class UserDataController {
@Autowired
UserRepository userRepository;
@PostMapping("user")
public UserData postUserDataByAPI(@RequestBody UserData userData) {
userRepository.save(userData);
return userData;
}
@GetMapping("user")
public List<UserData> getUserDataByAPI() {
return userRepository.findAll();
}
@GetMapping("user/{id}")
public UserData getUserDataByIdinAPI(@PathVariable Long id) { | return userRepository.findById(id).orElseThrow(()->new UserDataNotFoundException(id)); | 1 | 2023-11-22 17:00:07+00:00 | 2k |
partypankes/ProgettoCalcolatrice2023 | ProgrammableCalculator/src/main/java/group21/calculator/type/StackNumber.java | [
{
"identifier": "InsufficientOperandsException",
"path": "ProgrammableCalculator/src/main/java/group21/calculator/exceptions/InsufficientOperandsException.java",
"snippet": "public class InsufficientOperandsException extends RuntimeException{\n /**\n * Constructor for InsufficientOperandsExceptio... | import group21.calculator.exceptions.InsufficientOperandsException;
import group21.calculator.exceptions.StackIsEmptyException;
import java.util.Stack; | 820 | package group21.calculator.type;
/**
* This class represents a stack specifically designed for holding ComplexNumber objects.
* It provides various stack operations such as push, pop, peek, and additional operations
* like duplicate, swap, and over, tailored for use in a calculator context. This stack acts
* as the memory of the calculator, storing the numbers upon which operations are performed.
*/
public class StackNumber {
private final Stack<ComplexNumber> stack;
/**
* Constructor for the StackNumber class. Initializes a new Stack object to hold ComplexNumber instances.
*/
public StackNumber() {
stack = new Stack<>();
}
/**
* Gets the current size of the stack.
*
* @return The size of the stack.
*/
public int getStackSize() {
return stack.size();
}
/**
* Checks if the stack is empty.
*
* @return True if the stack is empty, false otherwise.
*/
public boolean isEmpty() {
return stack.isEmpty();
}
/**
* Pushes a ComplexNumber onto the stack.
*
* @param number The ComplexNumber to be added to the stack.
*/
public void pushNumber(ComplexNumber number){
stack.push(number);
}
/**
* Peeks at the top element of the stack without removing it.
*
* @return The ComplexNumber at the top of the stack.
* @throws StackIsEmptyException If the stack is empty.
*/
public ComplexNumber peekNumber() throws StackIsEmptyException{
if (isEmpty()){
throw new StackIsEmptyException();
}else{
return stack.peek ();
}
}
/**
* Removes and returns the top element of the stack.
*
* @return The ComplexNumber removed from the top of the stack.
* @throws StackIsEmptyException If the stack is empty.
*/
public ComplexNumber dropNumber() throws StackIsEmptyException{
if(isEmpty()){
throw new StackIsEmptyException();
}else{
return stack.pop();
}
}
/**
* Clears the stack of all elements.
*/
public void clearNumber(){
stack.clear();
}
/**
* Duplicates the top element of the stack.
*
* @throws StackIsEmptyException If the stack is empty.
*/
public void dupNumber() throws StackIsEmptyException{
if (isEmpty()){
throw new StackIsEmptyException();
}else{
pushNumber(peekNumber());
}
}
/**
* Swaps the top two elements of the stack.
*
* @throws StackIsEmptyException If the stack is empty.
* @throws InsufficientOperandsException If there are less than two elements in the stack.
*/ | package group21.calculator.type;
/**
* This class represents a stack specifically designed for holding ComplexNumber objects.
* It provides various stack operations such as push, pop, peek, and additional operations
* like duplicate, swap, and over, tailored for use in a calculator context. This stack acts
* as the memory of the calculator, storing the numbers upon which operations are performed.
*/
public class StackNumber {
private final Stack<ComplexNumber> stack;
/**
* Constructor for the StackNumber class. Initializes a new Stack object to hold ComplexNumber instances.
*/
public StackNumber() {
stack = new Stack<>();
}
/**
* Gets the current size of the stack.
*
* @return The size of the stack.
*/
public int getStackSize() {
return stack.size();
}
/**
* Checks if the stack is empty.
*
* @return True if the stack is empty, false otherwise.
*/
public boolean isEmpty() {
return stack.isEmpty();
}
/**
* Pushes a ComplexNumber onto the stack.
*
* @param number The ComplexNumber to be added to the stack.
*/
public void pushNumber(ComplexNumber number){
stack.push(number);
}
/**
* Peeks at the top element of the stack without removing it.
*
* @return The ComplexNumber at the top of the stack.
* @throws StackIsEmptyException If the stack is empty.
*/
public ComplexNumber peekNumber() throws StackIsEmptyException{
if (isEmpty()){
throw new StackIsEmptyException();
}else{
return stack.peek ();
}
}
/**
* Removes and returns the top element of the stack.
*
* @return The ComplexNumber removed from the top of the stack.
* @throws StackIsEmptyException If the stack is empty.
*/
public ComplexNumber dropNumber() throws StackIsEmptyException{
if(isEmpty()){
throw new StackIsEmptyException();
}else{
return stack.pop();
}
}
/**
* Clears the stack of all elements.
*/
public void clearNumber(){
stack.clear();
}
/**
* Duplicates the top element of the stack.
*
* @throws StackIsEmptyException If the stack is empty.
*/
public void dupNumber() throws StackIsEmptyException{
if (isEmpty()){
throw new StackIsEmptyException();
}else{
pushNumber(peekNumber());
}
}
/**
* Swaps the top two elements of the stack.
*
* @throws StackIsEmptyException If the stack is empty.
* @throws InsufficientOperandsException If there are less than two elements in the stack.
*/ | public void swapNumber() throws StackIsEmptyException, InsufficientOperandsException{ | 0 | 2023-11-19 16:11:56+00:00 | 2k |
Staffilon/KestraDataOrchestrator | IoT Simulator/src/main/java/net/acesinc/data/json/generator/log/WampLogger.java | [
{
"identifier": "OnConnectHandler",
"path": "IoT Simulator/src/main/java/net/acesinc/data/json/util/OnConnectHandler.java",
"snippet": "public interface OnConnectHandler {\n void connected(Session session);\n}"
},
{
"identifier": "WampClient",
"path": "IoT Simulator/src/main/java/net/aces... | import java.time.LocalDateTime;
import java.util.Map;
import java.util.Queue;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.crossbar.autobahn.wamp.Session;
import net.acesinc.data.json.util.OnConnectHandler;
import net.acesinc.data.json.util.WampClient; | 782 | package net.acesinc.data.json.generator.log;
public class WampLogger extends AbstractEventLogger {
private static final Logger log = LogManager.getLogger(WampLogger.class);
private static final String PRODUCER_TYPE_NAME = "wamp";
private static final String URL = "url";
private static final String REALM = "realm";
private static final String TOPIC = "topic";
| package net.acesinc.data.json.generator.log;
public class WampLogger extends AbstractEventLogger {
private static final Logger log = LogManager.getLogger(WampLogger.class);
private static final String PRODUCER_TYPE_NAME = "wamp";
private static final String URL = "url";
private static final String REALM = "realm";
private static final String TOPIC = "topic";
| private WampClient wampClient=null; | 1 | 2023-11-26 10:57:17+00:00 | 2k |
Invadermonky/JustEnoughMagiculture | src/main/java/com/invadermonky/justenoughmagiculture/configs/mods/JEMConfigGrimoireOfGaia.java | [
{
"identifier": "JustEnoughMagiculture",
"path": "src/main/java/com/invadermonky/justenoughmagiculture/JustEnoughMagiculture.java",
"snippet": "@Mod(\n modid = JustEnoughMagiculture.MOD_ID,\n name = JustEnoughMagiculture.MOD_NAME,\n version = JustEnoughMagiculture.MOD_VERSION,\n ... | import com.invadermonky.justenoughmagiculture.JustEnoughMagiculture;
import com.invadermonky.justenoughmagiculture.util.ConfigHelper.MobJER;
import com.invadermonky.justenoughmagiculture.util.ModIds.ConstantNames;
import net.minecraftforge.common.config.Config.Comment;
import net.minecraftforge.common.config.Config.RequiresMcRestart; | 1,448 | package com.invadermonky.justenoughmagiculture.configs.mods;
public class JEMConfigGrimoireOfGaia {
private static final String MOD_NAME = ConstantNames.GRIMOIRE_OF_GAIA; | package com.invadermonky.justenoughmagiculture.configs.mods;
public class JEMConfigGrimoireOfGaia {
private static final String MOD_NAME = ConstantNames.GRIMOIRE_OF_GAIA; | private static final String LANG_KEY = "config." + JustEnoughMagiculture.MOD_ALIAS + ":"; | 0 | 2023-11-19 23:09:14+00:00 | 2k |
spring-cloud/spring-functions-catalog | supplier/spring-jdbc-supplier/src/main/java/org/springframework/cloud/fn/supplier/jdbc/JdbcSupplierConfiguration.java | [
{
"identifier": "ComponentCustomizer",
"path": "common/spring-config-common/src/main/java/org/springframework/cloud/fn/common/config/ComponentCustomizer.java",
"snippet": "@FunctionalInterface\npublic interface ComponentCustomizer<T> {\n\n\tvoid customize(T component);\n\n}"
},
{
"identifier": "... | import org.springframework.cloud.function.context.PollableBean;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.core.MessageSource;
import org.springframework.integration.jdbc.JdbcPollingChannelAdapter;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.sql.DataSource;
import reactor.core.publisher.Flux;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.fn.common.config.ComponentCustomizer;
import org.springframework.cloud.fn.splitter.SplitterFunctionConfiguration; | 1,224 | /*
* Copyright 2019-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.fn.supplier.jdbc;
/**
* JDBC supplier auto-configuration.
*
* @author Soby Chacko
* @author Artem Bilan
*/
@AutoConfiguration(after = { DataSourceAutoConfiguration.class, SplitterFunctionConfiguration.class })
@EnableConfigurationProperties(JdbcSupplierProperties.class)
public class JdbcSupplierConfiguration {
private final JdbcSupplierProperties properties;
private final DataSource dataSource;
public JdbcSupplierConfiguration(JdbcSupplierProperties properties, DataSource dataSource) {
this.properties = properties;
this.dataSource = dataSource;
}
@Bean
public MessageSource<Object> jdbcMessageSource( | /*
* Copyright 2019-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.fn.supplier.jdbc;
/**
* JDBC supplier auto-configuration.
*
* @author Soby Chacko
* @author Artem Bilan
*/
@AutoConfiguration(after = { DataSourceAutoConfiguration.class, SplitterFunctionConfiguration.class })
@EnableConfigurationProperties(JdbcSupplierProperties.class)
public class JdbcSupplierConfiguration {
private final JdbcSupplierProperties properties;
private final DataSource dataSource;
public JdbcSupplierConfiguration(JdbcSupplierProperties properties, DataSource dataSource) {
this.properties = properties;
this.dataSource = dataSource;
}
@Bean
public MessageSource<Object> jdbcMessageSource( | @Nullable ComponentCustomizer<JdbcPollingChannelAdapter> jdbcPollingChannelAdapterCustomizer) { | 0 | 2023-11-21 04:03:30+00:00 | 2k |
Elliott-byte/easyevent | src/main/java/com/example/easyevent/service/BookingEntityService.java | [
{
"identifier": "BookingEntity",
"path": "src/main/java/com/example/easyevent/entity/BookingEntity.java",
"snippet": "@Data\n@Entity\n@Builder\n@RequiredArgsConstructor\n@AllArgsConstructor\n@Table(name = \"tb_booking\")\npublic class BookingEntity {\n @Id\n @GeneratedValue(strategy = GenerationTy... | import com.example.easyevent.entity.BookingEntity;
import com.example.easyevent.entity.EventEntity;
import com.example.easyevent.entity.UserEntity;
import com.example.easyevent.repository.BookingEntityRepository;
import com.example.easyevent.repository.EventEntityRepository;
import com.example.easyevent.type.Booking;
import com.example.easyevent.type.Event;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors; | 1,307 | package com.example.easyevent.service;
@Service
@AllArgsConstructor
@Slf4j
public class BookingEntityService {
BookingEntityRepository bookingEntityRepository;
EventEntityRepository eventEntityRepository; | package com.example.easyevent.service;
@Service
@AllArgsConstructor
@Slf4j
public class BookingEntityService {
BookingEntityRepository bookingEntityRepository;
EventEntityRepository eventEntityRepository; | public Booking saveBooking(Long eventId, UserEntity userEntity) { | 5 | 2023-11-20 11:18:56+00:00 | 2k |
EnigmaGuest/fnk-server | service-core/service-core-system/src/main/java/fun/isite/service/core/system/entity/SystemMenu.java | [
{
"identifier": "BaseEntity",
"path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/entity/BaseEntity.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic abstract class BaseEntity<T extends Model<T>> extends Model<... | import com.baomidou.mybatisplus.annotation.TableName;
import fun.isite.service.common.db.entity.BaseEntity;
import fun.isite.service.core.system.enums.MenuTypeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor; | 790 | package fun.isite.service.core.system.entity;
/**
* 系统菜单
*
* @author Enigma
* @since 2023-12-18
*/
@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("system_menu")
@Schema(name = "SystemMenu", description = "系统菜单")
public class SystemMenu extends BaseEntity<SystemMenu> {
/**
* 上级ID
*/
@Schema(description="上级ID")
private String rootId;
/**
* 菜单名称
*/
@Schema(description="菜单名称")
private String name;
/**
* 路由key全局唯一
*/
@Schema(description="路由key全局唯一")
private String routeKey;
/**
* 显示顺序
*/
@Schema(description="显示顺序")
private Integer orderSort;
/**
* 是否为网页
*/
@Schema(description="是否为网页")
private Boolean isIframe;
/**
* 请求路径
*/
@Schema(description="请求路径")
private String path;
/**
* icones
*/
@Schema(description="icones")
private String icon;
/**
* 本地icon
*/
@Schema(description="本地icon")
private String localIcon;
/**
* 是否显示
*/
@Schema(description="是否显示")
private Boolean visible;
/**
* 权限标识
*/
@Schema(description="权限标识")
private String permission;
/**
* 菜单类型(table目录 menu菜单 button按钮)
*/
@Schema(description="菜单类型(table目录 menu菜单 button按钮)") | package fun.isite.service.core.system.entity;
/**
* 系统菜单
*
* @author Enigma
* @since 2023-12-18
*/
@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("system_menu")
@Schema(name = "SystemMenu", description = "系统菜单")
public class SystemMenu extends BaseEntity<SystemMenu> {
/**
* 上级ID
*/
@Schema(description="上级ID")
private String rootId;
/**
* 菜单名称
*/
@Schema(description="菜单名称")
private String name;
/**
* 路由key全局唯一
*/
@Schema(description="路由key全局唯一")
private String routeKey;
/**
* 显示顺序
*/
@Schema(description="显示顺序")
private Integer orderSort;
/**
* 是否为网页
*/
@Schema(description="是否为网页")
private Boolean isIframe;
/**
* 请求路径
*/
@Schema(description="请求路径")
private String path;
/**
* icones
*/
@Schema(description="icones")
private String icon;
/**
* 本地icon
*/
@Schema(description="本地icon")
private String localIcon;
/**
* 是否显示
*/
@Schema(description="是否显示")
private Boolean visible;
/**
* 权限标识
*/
@Schema(description="权限标识")
private String permission;
/**
* 菜单类型(table目录 menu菜单 button按钮)
*/
@Schema(description="菜单类型(table目录 menu菜单 button按钮)") | private MenuTypeEnum type; | 1 | 2023-12-26 01:55:01+00:00 | 2k |
yutianqaq/BypassAV-Online | BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/service/impl/CompileServiceImpl.java | [
{
"identifier": "CompilationResult",
"path": "BypassAVOnline-Backend/src/main/java/com/yutian4090/bypass/controller/domain/CompilationResult.java",
"snippet": "@Getter\n@Setter\npublic class CompilationResult {\n private byte[] fileBytes;\n private String fileName;\n\n public CompilationResult(... | import com.yutian4090.bypass.controller.domain.CompilationResult;
import com.yutian4090.bypass.dto.CompilationResponseDTO;
import com.yutian4090.bypass.dto.CompileRequestDTO;
import com.yutian4090.bypass.service.CompileService;
import com.yutian4090.bypass.utils.CodeCompilationUtils;
import org.springframework.stereotype.Service;
import java.io.IOException;
import static com.yutian4090.bypass.utils.FileProcessor.saveFile; | 1,588 | package com.yutian4090.bypass.service.impl;
@Service
public class CompileServiceImpl implements CompileService {
@Override | package com.yutian4090.bypass.service.impl;
@Service
public class CompileServiceImpl implements CompileService {
@Override | public CompilationResponseDTO compileCodeC(CompileRequestDTO request) throws IOException { | 2 | 2023-12-28 06:22:12+00:00 | 2k |
codingmiao/hppt | ss/src/main/java/org/wowtools/hppt/ss/StartSs.java | [
{
"identifier": "Constant",
"path": "common/src/main/java/org/wowtools/hppt/common/util/Constant.java",
"snippet": "public class Constant {\n public static final ObjectMapper jsonObjectMapper = new ObjectMapper();\n\n public static final ObjectMapper ymlMapper = new ObjectMapper(new YAMLFactory())... | import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.core.config.Configurator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ErrorPageErrorHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.wowtools.common.utils.ResourcesReader;
import org.wowtools.hppt.common.util.Constant;
import org.wowtools.hppt.ss.pojo.SsConfig;
import org.wowtools.hppt.ss.servlet.*;
import java.io.File; | 959 | package org.wowtools.hppt.ss;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSs {
public static final SsConfig config;
static {
Configurator.reconfigure(new File(ResourcesReader.getRootPath(StartSs.class) + "/log4j2.xml").toURI());
try { | package org.wowtools.hppt.ss;
/**
* @author liuyu
* @date 2023/11/25
*/
@Slf4j
public class StartSs {
public static final SsConfig config;
static {
Configurator.reconfigure(new File(ResourcesReader.getRootPath(StartSs.class) + "/log4j2.xml").toURI());
try { | config = Constant.ymlMapper.readValue(ResourcesReader.readStr(StartSs.class, "ss.yml"), SsConfig.class); | 0 | 2023-12-22 14:14:27+00:00 | 2k |
3arthqu4ke/phobot | src/main/java/me/earth/phobot/modules/client/AccountSpoof.java | [
{
"identifier": "AuthenticationEvent",
"path": "src/main/java/me/earth/phobot/event/AuthenticationEvent.java",
"snippet": "public class AuthenticationEvent extends CancellableEvent {\n\n}"
},
{
"identifier": "IServerboundHelloPacket",
"path": "src/main/java/me/earth/phobot/mixins/network/ISe... | import com.mojang.authlib.GameProfile;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import me.earth.phobot.event.AuthenticationEvent;
import me.earth.phobot.mixins.network.IServerboundHelloPacket;
import me.earth.phobot.settings.UUIDSetting;
import me.earth.pingbypass.PingBypass;
import me.earth.pingbypass.api.command.CommandSource;
import me.earth.pingbypass.api.command.impl.builder.ExtendedLiteralArgumentBuilder;
import me.earth.pingbypass.api.command.impl.module.HasCustomModuleCommand;
import me.earth.pingbypass.api.event.impl.PingBypassInitializedEvent;
import me.earth.pingbypass.api.event.listeners.generic.Listener;
import me.earth.pingbypass.api.module.impl.Categories;
import me.earth.pingbypass.api.module.impl.ModuleImpl;
import me.earth.pingbypass.api.setting.Setting;
import me.earth.pingbypass.commons.event.CancellingListener;
import me.earth.pingbypass.commons.event.network.PacketEvent;
import net.minecraft.ChatFormatting;
import net.minecraft.client.server.IntegratedServer;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.login.ServerboundHelloPacket;
import org.apache.commons.lang3.mutable.MutableObject;
import java.util.Optional;
import java.util.Random;
import java.util.UUID; | 931 | package me.earth.phobot.modules.client;
public class AccountSpoof extends ModuleImpl implements HasCustomModuleCommand {
private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
private final Setting<String> name = string("Name", "Phobot", "The name to spoof");
private final Setting<UUID> uuid = new UUIDSetting().withName("UUID")
.withDescription("The UUID of to spoof.")
.register(this);
private final Setting<Boolean> rnd = bool("Random", false, "Gives you a random name every time the game starts.");
public AccountSpoof(PingBypass pingBypass) {
super(pingBypass, "AccountSpoof", Categories.CLIENT, "Act like someone else on cracked servers."); | package me.earth.phobot.modules.client;
public class AccountSpoof extends ModuleImpl implements HasCustomModuleCommand {
private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_";
private final Setting<String> name = string("Name", "Phobot", "The name to spoof");
private final Setting<UUID> uuid = new UUIDSetting().withName("UUID")
.withDescription("The UUID of to spoof.")
.register(this);
private final Setting<Boolean> rnd = bool("Random", false, "Gives you a random name every time the game starts.");
public AccountSpoof(PingBypass pingBypass) {
super(pingBypass, "AccountSpoof", Categories.CLIENT, "Act like someone else on cracked servers."); | listen(new CancellingListener<>(AuthenticationEvent.class)); | 0 | 2023-12-22 14:32:16+00:00 | 2k |
Video-Hub-Org/video-hub | backend/src/main/java/org/videohub/service/RedBookService.java | [
{
"identifier": "VideoHubConstants",
"path": "backend/src/main/java/org/videohub/constant/VideoHubConstants.java",
"snippet": "public class VideoHubConstants {\n // 文件下载路径,默认为项目同级目录下\n public static final String VIDEOHUB_FILEPATH = \"videoHubDownload/\";\n\n public static final String USER_AGEN... | import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.videohub.constant.VideoHubConstants;
import org.videohub.utils.VideoHubUtils;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 1,248 | package org.videohub.service;
/**
* 小红书笔记下载实现类
*
* @author @fmz200
* @date 2023-12-18
*/
@Slf4j
public class RedBookService {
// 下载视频超时时间,默认60秒
@Value("${videoDownloadTimeout}")
private static int videoDownloadTimeout;
// 下载文件的保存位置
@Value("${fileSavePath}")
private static String fileSavePath;
private static final ExecutorService executorService = Executors.newCachedThreadPool();
public static void downloadNodeBatch(String url) {
try {
if (videoDownloadTimeout < 1)
videoDownloadTimeout = 180;
if (!StringUtils.hasText(fileSavePath)) | package org.videohub.service;
/**
* 小红书笔记下载实现类
*
* @author @fmz200
* @date 2023-12-18
*/
@Slf4j
public class RedBookService {
// 下载视频超时时间,默认60秒
@Value("${videoDownloadTimeout}")
private static int videoDownloadTimeout;
// 下载文件的保存位置
@Value("${fileSavePath}")
private static String fileSavePath;
private static final ExecutorService executorService = Executors.newCachedThreadPool();
public static void downloadNodeBatch(String url) {
try {
if (videoDownloadTimeout < 1)
videoDownloadTimeout = 180;
if (!StringUtils.hasText(fileSavePath)) | fileSavePath = VideoHubConstants.VIDEOHUB_FILEPATH; | 0 | 2023-12-23 03:43:13+00:00 | 2k |
PENEKhun/baekjoon-java-starter | src/main/java/kr/huni/BojStarter.java | [
{
"identifier": "CodeGenerator",
"path": "src/main/java/kr/huni/code_generator/CodeGenerator.java",
"snippet": "public interface CodeGenerator {\n\n GeneratedCode generate(Problem problem);\n}"
},
{
"identifier": "CodeOpenManager",
"path": "src/main/java/kr/huni/code_runner/CodeOpenManager.... | import java.io.IOException;
import kr.huni.code_generator.CodeGenerator;
import kr.huni.code_generator.GeneratedCode;
import kr.huni.code_runner.CodeOpenManager;
import kr.huni.file_generator.JavaSourceCodeFile;
import kr.huni.os.OperatingSystem;
import kr.huni.problem_parser.BaekjoonProblemParser;
import kr.huni.problem_parser.Problem;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; | 1,196 | package kr.huni;
@Slf4j
@RequiredArgsConstructor
public class BojStarter {
private final CodeOpenManager codeOpenManager;
private final JavaSourceCodeFile fileUtil;
private final CodeGenerator codeGenerator; | package kr.huni;
@Slf4j
@RequiredArgsConstructor
public class BojStarter {
private final CodeOpenManager codeOpenManager;
private final JavaSourceCodeFile fileUtil;
private final CodeGenerator codeGenerator; | private final BaekjoonProblemParser problemParser; | 4 | 2023-12-22 09:23:38+00:00 | 2k |
ydb-platform/ydb-java-dialects | hibernate-dialect/src/test/java/tech/ydb/hibernate/BaseTest.java | [
{
"identifier": "YdbDialect",
"path": "hibernate-dialect-v5/src/main/java/tech/ydb/hibernate/dialect/YdbDialect.java",
"snippet": "public class YdbDialect extends Dialect {\n private static final int IN_EXPRESSION_COUNT_LIMIT = 10_000;\n\n private static final Exporter<ForeignKey> FOREIGN_KEY_EMPT... | import jakarta.persistence.EntityManager;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.extension.RegisterExtension;
import tech.ydb.hibernate.dialect.YdbDialect;
import tech.ydb.hibernate.entity.Group;
import tech.ydb.hibernate.entity.Student;
import tech.ydb.jdbc.YdbDriver;
import tech.ydb.test.junit5.YdbHelperExtension;
import java.util.Properties;
import java.util.stream.Stream; | 1,420 | package tech.ydb.hibernate;
/**
* @author Kirill Kurdyukov
*/
public abstract class BaseTest {
@RegisterExtension
public static final YdbHelperExtension YDB_HELPER_EXTENSION = new YdbHelperExtension();
protected static SessionFactory SESSION_FACTORY;
@BeforeAll
static void beforeAll() {
StringBuilder jdbc = new StringBuilder("jdbc:ydb:")
.append(YDB_HELPER_EXTENSION.useTls() ? "grpcs://" : "grpc://")
.append(YDB_HELPER_EXTENSION.endpoint())
.append(YDB_HELPER_EXTENSION.database());
if (YDB_HELPER_EXTENSION.authToken() != null) {
jdbc.append("?").append("token=").append(YDB_HELPER_EXTENSION.authToken());
}
Properties properties = new Properties();
properties.put(Environment.DRIVER, YdbDriver.class.getName());
properties.put(Environment.URL, jdbc.toString()); | package tech.ydb.hibernate;
/**
* @author Kirill Kurdyukov
*/
public abstract class BaseTest {
@RegisterExtension
public static final YdbHelperExtension YDB_HELPER_EXTENSION = new YdbHelperExtension();
protected static SessionFactory SESSION_FACTORY;
@BeforeAll
static void beforeAll() {
StringBuilder jdbc = new StringBuilder("jdbc:ydb:")
.append(YDB_HELPER_EXTENSION.useTls() ? "grpcs://" : "grpc://")
.append(YDB_HELPER_EXTENSION.endpoint())
.append(YDB_HELPER_EXTENSION.database());
if (YDB_HELPER_EXTENSION.authToken() != null) {
jdbc.append("?").append("token=").append(YDB_HELPER_EXTENSION.authToken());
}
Properties properties = new Properties();
properties.put(Environment.DRIVER, YdbDriver.class.getName());
properties.put(Environment.URL, jdbc.toString()); | properties.put(Environment.DIALECT, YdbDialect.class.getName()); | 0 | 2023-12-25 18:31:13+00:00 | 2k |
Patbox/GlideAway | src/main/java/eu/pb4/glideaway/datagen/ItemTagsProvider.java | [
{
"identifier": "GlideItemTags",
"path": "src/main/java/eu/pb4/glideaway/item/GlideItemTags.java",
"snippet": "public class GlideItemTags {\n public static final TagKey<Item> HANG_GLIDERS = of(\"hand_gliders\");\n public static final TagKey<Item> SPECIAL_HANG_GLIDERS = of(\"special_hand_gliders\")... | import eu.pb4.glideaway.item.GlideItemTags;
import eu.pb4.glideaway.item.GlideItems;
import net.fabricmc.fabric.api.datagen.v1.FabricDataOutput;
import net.fabricmc.fabric.api.datagen.v1.provider.FabricTagProvider;
import net.minecraft.registry.RegistryWrapper;
import org.jetbrains.annotations.Nullable;
import java.util.concurrent.CompletableFuture; | 1,312 | package eu.pb4.glideaway.datagen;
class ItemTagsProvider extends FabricTagProvider.ItemTagProvider {
public ItemTagsProvider(FabricDataOutput output, CompletableFuture<RegistryWrapper.WrapperLookup> registriesFuture, @Nullable FabricTagProvider.BlockTagProvider blockTagProvider) {
super(output, registriesFuture, blockTagProvider);
}
@Override
protected void configure(RegistryWrapper.WrapperLookup arg) {
this.getOrCreateTagBuilder(GlideItemTags.HANG_GLIDERS) | package eu.pb4.glideaway.datagen;
class ItemTagsProvider extends FabricTagProvider.ItemTagProvider {
public ItemTagsProvider(FabricDataOutput output, CompletableFuture<RegistryWrapper.WrapperLookup> registriesFuture, @Nullable FabricTagProvider.BlockTagProvider blockTagProvider) {
super(output, registriesFuture, blockTagProvider);
}
@Override
protected void configure(RegistryWrapper.WrapperLookup arg) {
this.getOrCreateTagBuilder(GlideItemTags.HANG_GLIDERS) | .add(GlideItems.HANG_GLIDER) | 1 | 2023-12-22 11:00:52+00:00 | 2k |
danielfeitopin/MUNICS-SAPP-P1 | src/main/java/es/storeapp/business/utils/ExceptionGenerationUtils.java | [
{
"identifier": "AuthenticationException",
"path": "src/main/java/es/storeapp/business/exceptions/AuthenticationException.java",
"snippet": "public class AuthenticationException extends Exception {\n \n private static final long serialVersionUID = 9047626511480506926L;\n\n public Authentication... | import es.storeapp.business.exceptions.AuthenticationException;
import es.storeapp.business.exceptions.DuplicatedResourceException;
import es.storeapp.business.exceptions.InstanceNotFoundException;
import es.storeapp.business.exceptions.InvalidStateException;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component; | 673 | package es.storeapp.business.utils;
@Component
public class ExceptionGenerationUtils {
@Autowired
private MessageSource messageSource;
public InstanceNotFoundException toInstanceNotFoundException(Long id, String type, String messageKey)
throws InstanceNotFoundException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{type, id}, locale);
return new InstanceNotFoundException(id, type, message);
}
public DuplicatedResourceException toDuplicatedResourceException(String resource, String value, String messageKey)
throws DuplicatedResourceException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{value, resource}, locale);
return new DuplicatedResourceException(resource, value, message);
}
| package es.storeapp.business.utils;
@Component
public class ExceptionGenerationUtils {
@Autowired
private MessageSource messageSource;
public InstanceNotFoundException toInstanceNotFoundException(Long id, String type, String messageKey)
throws InstanceNotFoundException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{type, id}, locale);
return new InstanceNotFoundException(id, type, message);
}
public DuplicatedResourceException toDuplicatedResourceException(String resource, String value, String messageKey)
throws DuplicatedResourceException {
Locale locale = LocaleContextHolder.getLocale();
String message = messageSource.getMessage(messageKey, new Object[]{value, resource}, locale);
return new DuplicatedResourceException(resource, value, message);
}
| public AuthenticationException toAuthenticationException(String messageKey, String user) | 0 | 2023-12-24 19:24:49+00:00 | 2k |
Brath1024/SensiCheck | src/main/java/cn/brath/sensicheck/utils/SensiCheckUtil.java | [
{
"identifier": "SensiCheckType",
"path": "src/main/java/cn/brath/sensicheck/constants/SensiCheckType.java",
"snippet": "public enum SensiCheckType {\n\n /**\n * 替换\n */\n REPLACE,\n\n /**\n * 抛异常\n */\n ERROR,\n\n /**\n * 不做动作\n */\n NON,\n\n}"
},
{
"id... | import cn.brath.sensicheck.constants.SensiCheckType;
import cn.brath.sensicheck.strategy.SensiCheckContext;
import cn.brath.sensicheck.strategy.SensiCheckStrategy;
import java.util.List;
import java.util.stream.Collectors; | 876 | package cn.brath.sensicheck.utils;
public class SensiCheckUtil {
private static final String DEFAULT_REPLACE_VALUE = "*";
/**
* 单字符串检测,默认替换值为"*"
*/
public static String check(String text) {
return check(text, SensiCheckType.REPLACE);
}
/**
* 单字符串检测,自定义替换值
*/
public static String check(String text, String replaceValue) {
return check(text, replaceValue, SensiCheckType.REPLACE);
}
/**
* 单字符串检测,自定义过滤策略
*/
public static String check(String text, SensiCheckType type) {
return check(text, DEFAULT_REPLACE_VALUE, type);
}
/**
* 单字符串检测,自定义替换值和过滤策略
*/
public static String check(String text, String replaceValue, SensiCheckType type) { | package cn.brath.sensicheck.utils;
public class SensiCheckUtil {
private static final String DEFAULT_REPLACE_VALUE = "*";
/**
* 单字符串检测,默认替换值为"*"
*/
public static String check(String text) {
return check(text, SensiCheckType.REPLACE);
}
/**
* 单字符串检测,自定义替换值
*/
public static String check(String text, String replaceValue) {
return check(text, replaceValue, SensiCheckType.REPLACE);
}
/**
* 单字符串检测,自定义过滤策略
*/
public static String check(String text, SensiCheckType type) {
return check(text, DEFAULT_REPLACE_VALUE, type);
}
/**
* 单字符串检测,自定义替换值和过滤策略
*/
public static String check(String text, String replaceValue, SensiCheckType type) { | SensiCheckStrategy strategyService = SensiCheckContext.getInstance().getStrategyService(type); | 1 | 2023-12-28 04:50:04+00:00 | 2k |
RoderickQiu/SUSTech_CSE_Projects | CS109_2022_Fall/Chess/chessComponent/EmptySlotComponent.java | [
{
"identifier": "ClickController",
"path": "CS109_2022_Fall/Chess/controller/ClickController.java",
"snippet": "public class ClickController {\r\n private final Chessboard chessboard;\r\n private SquareComponent first;\r\n\r\n public ClickController(Chessboard chessboard) {\r\n this.ches... | import Chess.controller.ClickController;
import Chess.model.ChessColor;
import Chess.model.ChessboardPoint;
import java.awt.*;
| 1,378 | package Chess.chessComponent;
/**
* 这个类表示棋盘上的空棋子的格子
*/
public class EmptySlotComponent extends SquareComponent {
public EmptySlotComponent(ChessboardPoint chessboardPoint, Point location, ClickController clickController, int chess_size) {
| package Chess.chessComponent;
/**
* 这个类表示棋盘上的空棋子的格子
*/
public class EmptySlotComponent extends SquareComponent {
public EmptySlotComponent(ChessboardPoint chessboardPoint, Point location, ClickController clickController, int chess_size) {
| super(chessboardPoint, location, ChessColor.NONE, clickController, chess_size, 0, 100);
| 1 | 2023-12-31 05:50:13+00:00 | 2k |
Ertinox45/ImmersiveAddon | src/main/java/fr/dynamx/addons/immersive/server/ServerEventHandler.java | [
{
"identifier": "ImmersiveAddon",
"path": "src/main/java/fr/dynamx/addons/immersive/ImmersiveAddon.java",
"snippet": "@Mod(modid = ImmersiveAddon.ID, name = ImmersiveAddon.NAME, version = \"1.0\", dependencies = \"before: dynamxmod\")\n@DynamXAddon(modid = ImmersiveAddon.ID, name = ImmersiveAddon.NAME, ... | import com.jme3.math.Vector3f;
import fr.dynamx.addons.immersive.ImmersiveAddon;
import fr.dynamx.addons.immersive.ImmersiveAddonConfig;
import fr.dynamx.addons.immersive.common.modules.DamageCarModule;
import fr.dynamx.api.events.PhysicsEvent;
import fr.dynamx.api.physics.BulletShapeType;
import fr.dynamx.api.physics.EnumBulletShapeType;
import fr.dynamx.common.entities.BaseVehicleEntity;
import fr.dynamx.common.entities.modules.SeatsModule;
import fr.dynamx.utils.DynamXUtils;
import net.minecraft.entity.Entity;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side; | 1,575 | package fr.dynamx.addons.immersive.server;
@Mod.EventBusSubscriber(value = {Side.SERVER}, modid = ImmersiveAddon.ID)
public class ServerEventHandler {
@SubscribeEvent
public void onDynxCollide(PhysicsEvent.PhysicsCollision e) { | package fr.dynamx.addons.immersive.server;
@Mod.EventBusSubscriber(value = {Side.SERVER}, modid = ImmersiveAddon.ID)
public class ServerEventHandler {
@SubscribeEvent
public void onDynxCollide(PhysicsEvent.PhysicsCollision e) { | if(e.getCollisionInfo().getEntityB().getType().equals(EnumBulletShapeType.TERRAIN) && ImmersiveAddonConfig.enableCarDamage) { | 1 | 2023-12-30 08:33:54+00:00 | 2k |
Patbox/serveruifix | src/main/java/eu/pb4/serveruifix/polydex/PolydexCompatImpl.java | [
{
"identifier": "GuiTextures",
"path": "src/main/java/eu/pb4/serveruifix/util/GuiTextures.java",
"snippet": "public class GuiTextures {\n public static final GuiElement EMPTY = icon16(\"empty\").get().build();\n public static final Function<Text, Text> STONECUTTER = background(\"stonecutter\");\n\... | import eu.pb4.polydex.api.v1.recipe.*;
import eu.pb4.serveruifix.util.GuiTextures;
import eu.pb4.serveruifix.util.GuiUtils;
import eu.pb4.sgui.api.elements.GuiElement;
import net.minecraft.recipe.RecipeType;
import net.minecraft.text.Text; | 1,018 | package eu.pb4.serveruifix.polydex;
public class PolydexCompatImpl {
public static void register() {
}
public static GuiElement getButton(RecipeType<?> type) {
var category = PolydexCategory.of(type); | package eu.pb4.serveruifix.polydex;
public class PolydexCompatImpl {
public static void register() {
}
public static GuiElement getButton(RecipeType<?> type) {
var category = PolydexCategory.of(type); | return GuiTextures.POLYDEX_BUTTON.get() | 0 | 2023-12-28 23:01:30+00:00 | 2k |
psobiech/opengr8on | tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPWriteRequestPacket.java | [
{
"identifier": "TFTPPacketType",
"path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTPPacketType.java",
"snippet": "public enum TFTPPacketType {\n UNKNOWN(\n 0,\n payload -> {\n throw new TFTPPacketException(\"Bad packet. Invalid TFTP operator code.\");\n }\n ... | import java.net.InetAddress;
import pl.psobiech.opengr8on.tftp.TFTPPacketType;
import pl.psobiech.opengr8on.tftp.TFTPTransferMode;
import pl.psobiech.opengr8on.tftp.exceptions.TFTPPacketException;
import pl.psobiech.opengr8on.util.SocketUtil.Payload; | 1,367 | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.tftp.packets;
public class TFTPWriteRequestPacket extends TFTPRequestPacket {
public TFTPWriteRequestPacket(Payload payload) throws TFTPPacketException { | /*
* OpenGr8on, open source extensions to systems based on Grenton devices
* Copyright (C) 2023 Piotr Sobiech
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pl.psobiech.opengr8on.tftp.packets;
public class TFTPWriteRequestPacket extends TFTPRequestPacket {
public TFTPWriteRequestPacket(Payload payload) throws TFTPPacketException { | super(TFTPPacketType.WRITE_REQUEST, payload); | 0 | 2023-12-23 09:56:14+00:00 | 2k |
Daniil-Tsiunchyk/DatsBlack-Hackathon | Gold/src/main/java/org/example/scripts/ScriptMap.java | [
{
"identifier": "BattleMap",
"path": "Gold/src/main/java/org/example/models/BattleMap.java",
"snippet": "@Data\npublic class BattleMap {\n private int width;\n private int height;\n private List<Island> islands;\n\n @Data\n public static class Island {\n private int[][] map;\n ... | import com.google.gson.Gson;
import org.example.models.BattleMap;
import org.example.models.ScanResult;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import static org.example.Const.*; | 849 | package org.example.scripts;
public class ScriptMap {
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame("Battle Map");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 1000));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(1000, e -> updateMap());
timer.start();
updateMap();
}
private static void updateMap() {
try { | package org.example.scripts;
public class ScriptMap {
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame("Battle Map");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 1000));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(1000, e -> updateMap());
timer.start();
updateMap();
}
private static void updateMap() {
try { | BattleMap battleMap = fetchBattleMap(); | 0 | 2023-12-23 11:29:47+00:00 | 2k |
Pigmice2733/frc-2024 | src/main/java/frc/robot/commands/actions/HandoffToShooter.java | [
{
"identifier": "AutoConfig",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public static class AutoConfig {\n public final static double INTAKE_MOVE_TIME = 3;\n public final static double INTAKE_FEED_TIME = 1;\n public final static double FLYWHEEL_SPINUP_TIME = 3;\n\n}"
},
... | import com.pigmice.frc.lib.controller_rumbler.ControllerRumbler;
import edu.wpi.first.wpilibj.GenericHID.RumbleType;
import edu.wpi.first.wpilibj2.command.Commands;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import frc.robot.Constants.AutoConfig;
import frc.robot.Constants.IntakeConfig.IntakeState;
import frc.robot.subsystems.Intake;
import frc.robot.subsystems.Shooter; | 1,194 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.actions;
public class HandoffToShooter extends SequentialCommandGroup {
public HandoffToShooter(Intake intake, Shooter shooter) {
addCommands(intake.setTargetState(IntakeState.UP), | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.commands.actions;
public class HandoffToShooter extends SequentialCommandGroup {
public HandoffToShooter(Intake intake, Shooter shooter) {
addCommands(intake.setTargetState(IntakeState.UP), | Commands.waitSeconds(AutoConfig.INTAKE_MOVE_TIME), intake.runWheelsBackward(), | 0 | 2023-12-30 06:06:45+00:00 | 2k |
NeckitWin/Medallions | src/main/java/net/neckitwin/medallions/common/CommonProxy.java | [
{
"identifier": "ModBlocks",
"path": "src/main/java/net/neckitwin/medallions/common/handler/ModBlocks.java",
"snippet": "public class ModBlocks {\n public static final BlockMegaChest MEGA_CHEST = new BlockMegaChest();\n public static void register() {\n GameRegistry.registerBlock(MEGA_CHEST... | import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import net.neckitwin.medallions.common.handler.ModBlocks;
import net.neckitwin.medallions.common.handler.ModItems;
import net.neckitwin.medallions.common.handler.ModRecipes; | 1,356 | package net.neckitwin.medallions.common;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent event) {
ModItems.register(); | package net.neckitwin.medallions.common;
public class CommonProxy {
public void preInit(FMLPreInitializationEvent event) {
ModItems.register(); | ModRecipes.register(); | 2 | 2023-12-29 23:19:12+00:00 | 2k |
373675032/kaka-shop | src/main/java/world/xuewei/service/impl/CommodityServiceImpl.java | [
{
"identifier": "Classify",
"path": "src/main/java/world/xuewei/entity/Classify.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Classify implements Serializable {\n\n private static final long serialVersionUID = 466451867991947870L;\n\n /**\n * 主键ID\n ... | import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Service;
import world.xuewei.entity.Classify;
import world.xuewei.entity.Commodity;
import world.xuewei.service.BaseService;
import world.xuewei.service.CommodityService;
import java.math.BigDecimal;
import java.util.List; | 1,519 | package world.xuewei.service.impl;
/**
* @author XUEW
* @ClassName CommodityServiceImpl
* 商品【咖啡豆】表(Commodity)表业务接口实现类
* @date 2021-02-28 21:07:20
* @Version 1.0
**/
@Service("commodityService")
public class CommodityServiceImpl extends BaseService implements CommodityService {
@Override | package world.xuewei.service.impl;
/**
* @author XUEW
* @ClassName CommodityServiceImpl
* 商品【咖啡豆】表(Commodity)表业务接口实现类
* @date 2021-02-28 21:07:20
* @Version 1.0
**/
@Service("commodityService")
public class CommodityServiceImpl extends BaseService implements CommodityService {
@Override | public boolean insert(Commodity commodity) { | 1 | 2023-12-27 15:17:13+00:00 | 2k |
fatorius/DUCO-Android-Miner | DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/threads/MiningThread.java | [
{
"identifier": "DUCOS1Hasher",
"path": "DuinoCoinMiner/app/src/main/java/com/fatorius/duinocoinminer/algorithms/DUCOS1Hasher.java",
"snippet": "public class DUCOS1Hasher {\n private int lastNonce;\n private float hashingTimeDeltaSeconds;\n\n public DUCOS1Hasher(){\n }\n\n public int mine... | import android.os.Build;
import android.util.Log;
import com.fatorius.duinocoinminer.algorithms.DUCOS1Hasher;
import com.fatorius.duinocoinminer.infos.MinerInfo;
import com.fatorius.duinocoinminer.tcp.Client;
import java.io.IOException; | 1,280 | package com.fatorius.duinocoinminer.threads;
public class MiningThread implements Runnable{
static{
System.loadLibrary("ducohasher");
}
public final static String MINING_THREAD_NAME_ID = "duinocoin_mining_thread";
String ip;
int port;
int threadNo;
Client tcpClient;
String username;
DUCOS1Hasher hasher;
float miningEfficiency;
ServiceCommunicationMethods service;
public MiningThread(String ip, int port, String username, float miningEfficiency, int threadNo, ServiceCommunicationMethods service) throws IOException {
this.ip = ip;
this.port = port;
this.username = username;
this.miningEfficiency = miningEfficiency;
this.service = service;
this.threadNo = threadNo;
hasher = new DUCOS1Hasher();
Log.d("Mining thread" + threadNo, threadNo + " created");
}
@Override
public void run() {
Log.d("Mining thread" + threadNo, threadNo + " started");
try {
String responseData;
try {
tcpClient = new Client(ip, port);
} catch (IOException e) {
throw new RuntimeException(e);
}
while (!Thread.currentThread().isInterrupted()) {
tcpClient.send("JOB," + username + ",LOW");
try {
responseData = tcpClient.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
Log.d("Thread " + threadNo + " | JOB received", responseData);
String[] values = responseData.split(",");
String lastBlockHash = values[0];
String expectedHash = values[1];
int difficulty = Integer.parseInt(values[2]);
int nonce = hasher.mine(lastBlockHash, expectedHash, difficulty, miningEfficiency);
float timeElapsed = hasher.getTimeElapsed();
float hashrate = hasher.getHashrate();
Log.d("Thread " + threadNo + " | Nonce found", nonce + " Time elapsed: " + timeElapsed + "s Hashrate: " + (int) hashrate);
service.newShareSent();
| package com.fatorius.duinocoinminer.threads;
public class MiningThread implements Runnable{
static{
System.loadLibrary("ducohasher");
}
public final static String MINING_THREAD_NAME_ID = "duinocoin_mining_thread";
String ip;
int port;
int threadNo;
Client tcpClient;
String username;
DUCOS1Hasher hasher;
float miningEfficiency;
ServiceCommunicationMethods service;
public MiningThread(String ip, int port, String username, float miningEfficiency, int threadNo, ServiceCommunicationMethods service) throws IOException {
this.ip = ip;
this.port = port;
this.username = username;
this.miningEfficiency = miningEfficiency;
this.service = service;
this.threadNo = threadNo;
hasher = new DUCOS1Hasher();
Log.d("Mining thread" + threadNo, threadNo + " created");
}
@Override
public void run() {
Log.d("Mining thread" + threadNo, threadNo + " started");
try {
String responseData;
try {
tcpClient = new Client(ip, port);
} catch (IOException e) {
throw new RuntimeException(e);
}
while (!Thread.currentThread().isInterrupted()) {
tcpClient.send("JOB," + username + ",LOW");
try {
responseData = tcpClient.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
Log.d("Thread " + threadNo + " | JOB received", responseData);
String[] values = responseData.split(",");
String lastBlockHash = values[0];
String expectedHash = values[1];
int difficulty = Integer.parseInt(values[2]);
int nonce = hasher.mine(lastBlockHash, expectedHash, difficulty, miningEfficiency);
float timeElapsed = hasher.getTimeElapsed();
float hashrate = hasher.getHashrate();
Log.d("Thread " + threadNo + " | Nonce found", nonce + " Time elapsed: " + timeElapsed + "s Hashrate: " + (int) hashrate);
service.newShareSent();
| tcpClient.send(nonce + "," + (int) hashrate + "," + MinerInfo.MINER_NAME + "," + Build.MODEL); | 1 | 2023-12-27 06:00:05+00:00 | 2k |
tommyskeff/JObserve | src/main/java/dev/tommyjs/jobserve/observer/ObserverList.java | [
{
"identifier": "AttributeKey",
"path": "src/main/java/dev/tommyjs/jobserve/attribute/AttributeKey.java",
"snippet": "public class AttributeKey<T> {\n\n private static final Object LOCK = new Object();\n private static final Random RANDOM = new SecureRandom();\n\n private final int id;\n pri... | import dev.tommyjs.jobserve.attribute.AttributeKey;
import dev.tommyjs.jobserve.attribute.AttributeObservable;
import dev.tommyjs.jobserve.observer.key.DuplexKey;
import dev.tommyjs.jobserve.observer.key.MonoKey;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer; | 1,026 | package dev.tommyjs.jobserve.observer;
public class ObserverList {
private final Lock mutex;
private final List<ObserverSubscription> subscriptions;
public ObserverList() {
this.mutex = new ReentrantLock();
this.subscriptions = new ArrayList<>();
}
public <T> @NotNull ObserverSubscription observe(@NotNull Observable object, @NotNull MonoKey<T> key, @NotNull Consumer<T> consumer) {
ObserverSubscription sub = object.observe(key, consumer);
add(sub);
return sub;
}
public <K, V> @NotNull ObserverSubscription observe(@NotNull Observable object, @NotNull DuplexKey<K, V> key, @NotNull BiConsumer<K, V> consumer) {
ObserverSubscription sub = object.observe(key, consumer);
add(sub);
return sub;
}
| package dev.tommyjs.jobserve.observer;
public class ObserverList {
private final Lock mutex;
private final List<ObserverSubscription> subscriptions;
public ObserverList() {
this.mutex = new ReentrantLock();
this.subscriptions = new ArrayList<>();
}
public <T> @NotNull ObserverSubscription observe(@NotNull Observable object, @NotNull MonoKey<T> key, @NotNull Consumer<T> consumer) {
ObserverSubscription sub = object.observe(key, consumer);
add(sub);
return sub;
}
public <K, V> @NotNull ObserverSubscription observe(@NotNull Observable object, @NotNull DuplexKey<K, V> key, @NotNull BiConsumer<K, V> consumer) {
ObserverSubscription sub = object.observe(key, consumer);
add(sub);
return sub;
}
| public @NotNull <T> ObserverSubscription observeAttribute(@NotNull AttributeObservable object, @NotNull AttributeKey<T> key, @NotNull Consumer<T> consumer) { | 1 | 2023-12-26 17:02:45+00:00 | 2k |
fanxiaoning/framifykit | framifykit-starter/framifykit-starter-logistics/src/main/java/com/framifykit/starter/logistics/platform/kd100/client/DefaultKD100Client.java | [
{
"identifier": "ServiceException",
"path": "framifykit-starter/framifykit-common/src/main/java/com/famifykit/starter/common/exception/ServiceException.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic final class ServiceException extends RuntimeException {\n\n /**\n * 错误码\n ... | import com.famifykit.starter.common.exception.ServiceException;
import com.framifykit.starter.logistics.platform.kd100.util.HttpUtils;
import lombok.Data; | 858 | package com.framifykit.starter.logistics.platform.kd100.client;
/**
* <p>
* 快递100默认请求客户端 //TODO 待重构
* </p>
* @author fxn
* @since 1.0.0
**/
@Data
public class DefaultKD100Client implements IKD100Client {
private String key;
private String customer;
private String secret;
private String userId;
public DefaultKD100Client(String key, String customer, String secret) {
this.key = key;
this.customer = customer;
this.secret = secret;
}
@Override | package com.framifykit.starter.logistics.platform.kd100.client;
/**
* <p>
* 快递100默认请求客户端 //TODO 待重构
* </p>
* @author fxn
* @since 1.0.0
**/
@Data
public class DefaultKD100Client implements IKD100Client {
private String key;
private String customer;
private String secret;
private String userId;
public DefaultKD100Client(String key, String customer, String secret) {
this.key = key;
this.customer = customer;
this.secret = secret;
}
@Override | public String execute(String url, Object req) throws ServiceException { | 0 | 2023-12-31 03:48:33+00:00 | 2k |
yangpluseven/Simulate-Something | simulation/src/simulator/GridMap.java | [
{
"identifier": "Constants",
"path": "simulation/src/constants/Constants.java",
"snippet": "public class Constants {\n\n\tpublic static final Size INIT_GRID_SIZE = new Size(10, 10);\n\tpublic static final Size NUM_OF_COL_ROW = new Size(50, 30);\n\tpublic static final int BACKGROUND_Z_ORDER = 0;\n\tpubli... | import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import constants.Constants;
import entities.Location;
import entities.Pair;
import entities.SimuObject;
import entities.Size; | 1,439 | package simulator;
/**
* GridMap takes up all the SimuObjects in the simulation.
*
* @author pluseven
*/
public class GridMap implements Map<Location, simulator.GridMap.Grid> {
private Grid[][] grids; | package simulator;
/**
* GridMap takes up all the SimuObjects in the simulation.
*
* @author pluseven
*/
public class GridMap implements Map<Location, simulator.GridMap.Grid> {
private Grid[][] grids; | private Size numCR; | 4 | 2023-12-23 13:51:12+00:00 | 2k |
zxx1119/best-adrules | src/main/java/org/fordes/adg/rule/AdgRuleApplication.java | [
{
"identifier": "OutputConfig",
"path": "src/main/java/org/fordes/adg/rule/config/OutputConfig.java",
"snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"application.output\")\npublic class OutputConfig {\n\n /**\n * 输出文件路径\n */\n private String path;\n\n /**\n * 输出文件... | import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ExecutorBuilder;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fordes.adg.rule.config.OutputConfig;
import org.fordes.adg.rule.config.RuleConfig;
import org.fordes.adg.rule.enums.RuleType;
import org.fordes.adg.rule.thread.LocalRuleThread;
import org.fordes.adg.rule.thread.RemoteRuleThread;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor; | 1,278 | package org.fordes.adg.rule;
@Slf4j
@Component
@AllArgsConstructor
@SpringBootApplication
public class AdgRuleApplication implements ApplicationRunner {
private final static int N = Runtime.getRuntime().availableProcessors();
private final RuleConfig ruleConfig;
| package org.fordes.adg.rule;
@Slf4j
@Component
@AllArgsConstructor
@SpringBootApplication
public class AdgRuleApplication implements ApplicationRunner {
private final static int N = Runtime.getRuntime().availableProcessors();
private final RuleConfig ruleConfig;
| private final OutputConfig outputConfig; | 0 | 2023-12-30 04:47:07+00:00 | 2k |
bmarwell/sipper | impl/src/main/java/io/github/bmarwell/sipper/impl/DefaultSipClientBuilder.java | [
{
"identifier": "SipClient",
"path": "api/src/main/java/io/github/bmarwell/sipper/api/SipClient.java",
"snippet": "public interface SipClient {\n\n /**\n * The connect method will, despite its name, not only try to establish a network connection, but also\n * send LOGIN commands via the REGIS... | import io.github.bmarwell.sipper.api.SipClient;
import io.github.bmarwell.sipper.api.SipClientBuilder;
import io.github.bmarwell.sipper.api.SipConfiguration; | 1,100 | /*
* Copyright (C) 2023-2024 The SIPper project team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.bmarwell.sipper.impl;
public class DefaultSipClientBuilder implements SipClientBuilder {
@Override | /*
* Copyright (C) 2023-2024 The SIPper project team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.bmarwell.sipper.impl;
public class DefaultSipClientBuilder implements SipClientBuilder {
@Override | public SipClient create(SipConfiguration sipConfiguration) { | 0 | 2023-12-28 13:13:07+00:00 | 2k |
Deenu143/GradleParser | app/src/main/java/org/deenu/gradle/script/visitors/GradleScriptVisitor.java | [
{
"identifier": "Dependency",
"path": "app/src/main/java/org/deenu/gradle/models/Dependency.java",
"snippet": "public class Dependency {\n\n private String configuration;\n private String group;\n private String name;\n private String version;\n\n public Dependency(String group, String name, String... | import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.codehaus.groovy.ast.CodeVisitorSupport;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.TupleExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.deenu.gradle.models.Dependency;
import org.deenu.gradle.models.FlatDir;
import org.deenu.gradle.models.Include;
import org.deenu.gradle.models.Plugin;
import org.deenu.gradle.models.Repository; | 1,489 | package org.deenu.gradle.script.visitors;
public class GradleScriptVisitor extends CodeVisitorSupport {
private Stack<Boolean> blockStatementStack = new Stack<>();
private int pluginsLastLineNumber = -1;
private String pluginsConfigurationName;
private boolean inPlugins = false;
private List<Plugin> plugins = new ArrayList<>();
private int repositoriesLastLineNumber = -1;
private String repositoriesConfigurationName;
private boolean inRepositories = false;
private List<Repository> repositories = new ArrayList<>();
private int buildscriptRepositoriesLastLineNumber = -1;
private String buildscriptRepositoriesConfigurationName;
private boolean inBuildScriptRepositories = false;
private List<Repository> buildscriptRepositories = new ArrayList<>();
private int buildscriptLastLineNumber = -1;
private String buildscriptConfigurationName;
private boolean inBuildScript = false;
private int allprojectsLastLineNumber = -1;
private String allprojectsConfigurationName;
private boolean inAllProjects = false;
private int allprojectsRepositoriesLastLineNumber = -1;
private String allprojectsRepositoriesConfigurationName;
private boolean inAllProjectsRepositories = false;
private List<Repository> allprojectsRepositories = new ArrayList<>();
private String rootProjectName;
private int includeLastLineNumber = -1;
private String includeConfigurationName;
private boolean inInclude = false; | package org.deenu.gradle.script.visitors;
public class GradleScriptVisitor extends CodeVisitorSupport {
private Stack<Boolean> blockStatementStack = new Stack<>();
private int pluginsLastLineNumber = -1;
private String pluginsConfigurationName;
private boolean inPlugins = false;
private List<Plugin> plugins = new ArrayList<>();
private int repositoriesLastLineNumber = -1;
private String repositoriesConfigurationName;
private boolean inRepositories = false;
private List<Repository> repositories = new ArrayList<>();
private int buildscriptRepositoriesLastLineNumber = -1;
private String buildscriptRepositoriesConfigurationName;
private boolean inBuildScriptRepositories = false;
private List<Repository> buildscriptRepositories = new ArrayList<>();
private int buildscriptLastLineNumber = -1;
private String buildscriptConfigurationName;
private boolean inBuildScript = false;
private int allprojectsLastLineNumber = -1;
private String allprojectsConfigurationName;
private boolean inAllProjects = false;
private int allprojectsRepositoriesLastLineNumber = -1;
private String allprojectsRepositoriesConfigurationName;
private boolean inAllProjectsRepositories = false;
private List<Repository> allprojectsRepositories = new ArrayList<>();
private String rootProjectName;
private int includeLastLineNumber = -1;
private String includeConfigurationName;
private boolean inInclude = false; | private List<Include> includes = new ArrayList<>(); | 2 | 2023-12-27 10:10:31+00:00 | 2k |
refutix/flink-sql-template-jar | flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/SqlRunner.java | [
{
"identifier": "SqlParseUtil",
"path": "flink-sql-runner-common/src/main/java/org/refutix/flink/sql/template/common/SqlParseUtil.java",
"snippet": "public class SqlParseUtil {\n\n private static final String STATEMENT_DELIMITER = \";\";\n\n private static final String MASK = \"--.*$\";\n\n pri... | import java.util.Properties;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.EnvironmentSettings;
import org.apache.flink.table.api.TableEnvironment;
import org.apache.flink.table.api.internal.TableEnvironmentInternal;
import org.apache.flink.table.delegation.Parser;
import org.apache.flink.table.operations.Operation;
import org.refutix.flink.sql.template.common.SqlParseUtil;
import org.refutix.flink.sql.template.provider.sql.FlinkSqlProvider;
import org.refutix.flink.sql.template.provider.sql.FlinkSqlProviderFactory;
import java.time.ZoneId;
import java.util.List; | 987 | /*
* 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.refutix.flink.sql.template;
/**
* Main class for executing SQL scripts.
*/
public class SqlRunner {
public static void main(String[] args) {
ParameterTool parameterTool = ParameterTool.fromArgs(args);
Properties properties = parameterTool.getProperties(); | /*
* 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.refutix.flink.sql.template;
/**
* Main class for executing SQL scripts.
*/
public class SqlRunner {
public static void main(String[] args) {
ParameterTool parameterTool = ParameterTool.fromArgs(args);
Properties properties = parameterTool.getProperties(); | FlinkSqlProvider provider = FlinkSqlProviderFactory.getProvider(properties); | 1 | 2023-12-25 16:29:40+00:00 | 2k |
NickReset/JavaNPM | src/main/java/social/nickrest/npm/module/NPMStaticPackage.java | [
{
"identifier": "NPM",
"path": "src/main/java/social/nickrest/npm/NPM.java",
"snippet": "@Getter @Setter\npublic class NPM {\n\n public static final String BASE_URL = \"https://registry.npmjs.org\";\n\n private final File nodeModulesDir;\n private NPMLogger logger;\n\n public NPM(File nodeMo... | import lombok.experimental.UtilityClass;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import social.nickrest.npm.NPM;
import social.nickrest.npm.util.IOUtils;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.function.Consumer; | 807 | package social.nickrest.npm.module;
@UtilityClass
public class NPMStaticPackage {
public String getLatestVersion(String packageName) {
try {
URL url = new URL(String.format("%s/%s", NPM.BASE_URL, packageName));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
| package social.nickrest.npm.module;
@UtilityClass
public class NPMStaticPackage {
public String getLatestVersion(String packageName) {
try {
URL url = new URL(String.format("%s/%s", NPM.BASE_URL, packageName));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
| String response = IOUtils.readConnection(connection); | 1 | 2023-12-22 20:46:10+00:00 | 2k |
Prototik/TheConfigLib | common/src/main/java/dev/tcl/config/api/autogen/CustomImage.java | [
{
"identifier": "EmptyCustomImageFactory",
"path": "common/src/main/java/dev/tcl/config/impl/autogen/EmptyCustomImageFactory.java",
"snippet": "public class EmptyCustomImageFactory implements CustomImage.CustomImageFactory<Object> {\n\n @Override\n public CompletableFuture<ImageRenderer> createIma... | import dev.tcl.config.impl.autogen.EmptyCustomImageFactory;
import dev.tcl.config.api.ConfigField;
import dev.tcl.gui.image.ImageRenderer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.concurrent.CompletableFuture; | 900 | package dev.tcl.config.api.autogen;
/**
* Defines a custom image for an option.
* Without this annotation, the option factory will look
* for the resource {@code modid:textures/tcl/$config_id_path/$fieldName.webp}.
* WEBP was chosen as the default format because file sizes are greatly reduced,
* which is important to keep your JAR size down, if you're so bothered.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomImage {
/**
* The resource path to the image, a {@link net.minecraft.resources.ResourceLocation}
* is constructed with the namespace being the modid of the config, and the path being
* this value.
* <p>
* The following file formats are supported:
* <ul>
* <li>{@code .png}</li>
* <li>{@code .webp}</li>
* <li>{@code .jpg}, {@code .jpeg}</li>
* </ul>
* <p>
* If left blank, then {@link CustomImage#factory()} is used.
*/
String value() default "";
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int width() default 0;
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int height() default 0;
/**
* The factory to create the image with.
* For the average user, this should not be used as it breaks out of the
* API-safe environment where things could change at any time, but required
* when creating anything advanced with the {@link ImageRenderer}.
* <p>
* The factory should contain a public, no-args constructor that will be
* invoked via reflection.
*
* @return the class of the factory
*/
Class<? extends CustomImageFactory<?>> factory() default EmptyCustomImageFactory.class;
interface CustomImageFactory<T> { | package dev.tcl.config.api.autogen;
/**
* Defines a custom image for an option.
* Without this annotation, the option factory will look
* for the resource {@code modid:textures/tcl/$config_id_path/$fieldName.webp}.
* WEBP was chosen as the default format because file sizes are greatly reduced,
* which is important to keep your JAR size down, if you're so bothered.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CustomImage {
/**
* The resource path to the image, a {@link net.minecraft.resources.ResourceLocation}
* is constructed with the namespace being the modid of the config, and the path being
* this value.
* <p>
* The following file formats are supported:
* <ul>
* <li>{@code .png}</li>
* <li>{@code .webp}</li>
* <li>{@code .jpg}, {@code .jpeg}</li>
* </ul>
* <p>
* If left blank, then {@link CustomImage#factory()} is used.
*/
String value() default "";
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int width() default 0;
/**
* The width of the image, in pixels.
* <strong>This is only required when using a PNG with {@link CustomImage#value()}</strong>
*/
int height() default 0;
/**
* The factory to create the image with.
* For the average user, this should not be used as it breaks out of the
* API-safe environment where things could change at any time, but required
* when creating anything advanced with the {@link ImageRenderer}.
* <p>
* The factory should contain a public, no-args constructor that will be
* invoked via reflection.
*
* @return the class of the factory
*/
Class<? extends CustomImageFactory<?>> factory() default EmptyCustomImageFactory.class;
interface CustomImageFactory<T> { | CompletableFuture<ImageRenderer> createImage(T value, ConfigField<T> field, OptionAccess access); | 2 | 2023-12-25 14:48:27+00:00 | 2k |
flyingpig2016/itheima_web_project | tlias-web-management/src/main/java/com/itheima/controller/LoginController.java | [
{
"identifier": "Emp",
"path": "tlias-web-management/src/main/java/com/itheima/pojo/Emp.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Emp {\n private Integer id;\n private String username;\n private String password;\n private String name;\n private Short ... | import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map; | 955 | package com.itheima.controller;
@Slf4j
@RestController
public class LoginController {
@Autowired
private EmpService empService;
@PostMapping("/login")
public Result login(@RequestBody Emp emp) {
log.info("员工正在登录: {}", emp);
Emp res = empService.login(emp);
log.info("登录返回信息:{} ", res);
// 登录成功,生成令牌,下发令牌
if (res != null) {
Map<String, Object> claims = new HashMap<>();
claims.put("id", res.getId());
claims.put("name", res.getName());
claims.put("username", res.getUsername());
| package com.itheima.controller;
@Slf4j
@RestController
public class LoginController {
@Autowired
private EmpService empService;
@PostMapping("/login")
public Result login(@RequestBody Emp emp) {
log.info("员工正在登录: {}", emp);
Emp res = empService.login(emp);
log.info("登录返回信息:{} ", res);
// 登录成功,生成令牌,下发令牌
if (res != null) {
Map<String, Object> claims = new HashMap<>();
claims.put("id", res.getId());
claims.put("name", res.getName());
claims.put("username", res.getUsername());
| String jwt = JwtUtils.generateJwt(claims); | 3 | 2023-12-25 08:52:04+00:00 | 2k |
vadage/rs4j | src/main/java/space/provided/rs/option/Option.java | [
{
"identifier": "ValueAccessError",
"path": "src/main/java/space/provided/rs/error/ValueAccessError.java",
"snippet": "public final class ValueAccessError extends Error {\n\n public ValueAccessError(String message) {\n super(message);\n }\n}"
},
{
"identifier": "ArgInvokable",
"... | import space.provided.rs.error.ValueAccessError;
import space.provided.rs.ops.ArgInvokable;
import space.provided.rs.ops.ArgVoidInvokable;
import space.provided.rs.ops.Invokable;
import space.provided.rs.ops.PlainInvokable;
import space.provided.rs.result.Result;
import java.util.function.Predicate; | 1,585 | package space.provided.rs.option;
public final class Option<Some> {
private final Some some;
private final OptionType type;
private Option(Some some, OptionType type) {
this.some = some;
this.type = type;
}
public static <Some> Option<Some> some(Some some) {
return new Option<>(some, OptionType.SOME);
}
public static <Some> Option<Some> none() {
return new Option<>(null, OptionType.NONE);
}
public boolean isSome() {
return type.equals(OptionType.SOME);
}
public boolean isNone() {
return !isSome();
}
public boolean isSomeAnd(ArgInvokable<Some, Boolean> invokable) {
return switch (type) {
case NONE -> false;
case SOME -> invokable.invoke(some);
};
}
| package space.provided.rs.option;
public final class Option<Some> {
private final Some some;
private final OptionType type;
private Option(Some some, OptionType type) {
this.some = some;
this.type = type;
}
public static <Some> Option<Some> some(Some some) {
return new Option<>(some, OptionType.SOME);
}
public static <Some> Option<Some> none() {
return new Option<>(null, OptionType.NONE);
}
public boolean isSome() {
return type.equals(OptionType.SOME);
}
public boolean isNone() {
return !isSome();
}
public boolean isSomeAnd(ArgInvokable<Some, Boolean> invokable) {
return switch (type) {
case NONE -> false;
case SOME -> invokable.invoke(some);
};
}
| public Some unwrap() throws ValueAccessError { | 0 | 2023-12-27 15:33:17+00:00 | 2k |
wicksonZhang/Spring-Cloud | 02-spring-cloud-payment-2100/src/main/java/cn/wickson/cloud/payment/controller/PaymentController.java | [
{
"identifier": "PaymentRespDTO",
"path": "01-spring-cloud-common/src/main/java/cn/wickson/cloud/common/model/dto/PaymentRespDTO.java",
"snippet": "@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class PaymentRespDTO implements ResultUnpacked... | import cn.wickson.cloud.common.model.dto.PaymentRespDTO;
import cn.wickson.cloud.common.model.vo.PaymentCreateReqVO;
import cn.wickson.cloud.payment.service.IPaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource; | 650 | package cn.wickson.cloud.payment.controller;
/**
* 支付服务-控制类
*
* @author ZhangZiHeng
* @date 2023-12-27
*/
@Slf4j
@Validated
@RestController
@RequestMapping("/payment")
public class PaymentController {
@Resource
private IPaymentService paymentService;
/**
* 创建支付订单
*
* @param paymentVO 订单信息
*/
@PostMapping(value = "/create") | package cn.wickson.cloud.payment.controller;
/**
* 支付服务-控制类
*
* @author ZhangZiHeng
* @date 2023-12-27
*/
@Slf4j
@Validated
@RestController
@RequestMapping("/payment")
public class PaymentController {
@Resource
private IPaymentService paymentService;
/**
* 创建支付订单
*
* @param paymentVO 订单信息
*/
@PostMapping(value = "/create") | public void create(@RequestBody PaymentCreateReqVO paymentVO) { | 1 | 2023-12-27 09:42:02+00:00 | 2k |
lunasaw/voglander | voglander-manager/src/main/java/io/github/lunasaw/voglander/manager/manager/DeviceConfigManager.java | [
{
"identifier": "DeviceConstant",
"path": "voglander-common/src/main/java/io/github/lunasaw/voglander/common/constant/DeviceConstant.java",
"snippet": "public interface DeviceConstant {\n\n interface DeviceCommandService {\n String DEVICE_AGREEMENT_SERVICE_NAME_GB28181 = \"GbDeviceCommandServi... | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.lunasaw.voglander.common.constant.DeviceConstant;
import io.github.lunasaw.voglander.manager.service.DeviceConfigService;
import io.github.lunasaw.voglander.repository.entity.DeviceConfigDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import java.util.Optional; | 1,076 | package io.github.lunasaw.voglander.manager.manager;
/**
* @author luna
* @date 2024/1/1
*/
@Component
public class DeviceConfigManager {
@Autowired
private DeviceConfigService deviceConfigService;
public String getSystemValueWithDefault(String key, String defaultValue) {
return getByValue(DeviceConstant.LocalConfig.DEVICE_ID, key, defaultValue);
}
public String getSystemValue(String key) {
return getByValue(DeviceConstant.LocalConfig.DEVICE_ID, key, null);
}
public String getByValue(String deviceId, String key, String defaultValue) { | package io.github.lunasaw.voglander.manager.manager;
/**
* @author luna
* @date 2024/1/1
*/
@Component
public class DeviceConfigManager {
@Autowired
private DeviceConfigService deviceConfigService;
public String getSystemValueWithDefault(String key, String defaultValue) {
return getByValue(DeviceConstant.LocalConfig.DEVICE_ID, key, defaultValue);
}
public String getSystemValue(String key) {
return getByValue(DeviceConstant.LocalConfig.DEVICE_ID, key, null);
}
public String getByValue(String deviceId, String key, String defaultValue) { | DeviceConfigDO byKey = getByKey(deviceId, key); | 2 | 2023-12-27 07:28:18+00:00 | 2k |
GrailStack/grail-codegen | src/main/java/com/itgrail/grail/codegen/service/impl/DbServiceImpl.java | [
{
"identifier": "DBProperties",
"path": "src/main/java/com/itgrail/grail/codegen/components/db/database/DBProperties.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class DBProperties {\n\n private String dbType;\n private String dbUrl;\n private String dbUserName;\n private Strin... | import com.google.common.base.Preconditions;
import com.itgrail.grail.codegen.components.db.database.DBProperties;
import com.itgrail.grail.codegen.components.db.database.Database;
import com.itgrail.grail.codegen.components.db.database.DatabaseFactory;
import com.itgrail.grail.codegen.service.DbService;
import com.itgrail.grail.codegen.service.dto.DbTablesReqDTO;
import com.itgrail.grail.codegen.service.dto.DbTablesRespDTO;
import com.itgrail.grail.codegen.utils.CommonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects; | 1,556 | package com.itgrail.grail.codegen.service.impl;
/**
* @author xujin
* created at 2019/6/6 18:13
**/
@Service
public class DbServiceImpl implements DbService {
@Override
public DbTablesRespDTO getDbTables(DbTablesReqDTO reqDTO) {
checkParams(reqDTO);
DbTablesRespDTO respDTO = new DbTablesRespDTO();
DBProperties dbProperties = new DBProperties();
dbProperties.setDbType(reqDTO.getDbType()).setDbUrl(reqDTO.getDbUrl());
dbProperties.setDbUserName(reqDTO.getDbUserName()).setDbPassword(reqDTO.getDbPassword());
Database database = null;
try { | package com.itgrail.grail.codegen.service.impl;
/**
* @author xujin
* created at 2019/6/6 18:13
**/
@Service
public class DbServiceImpl implements DbService {
@Override
public DbTablesRespDTO getDbTables(DbTablesReqDTO reqDTO) {
checkParams(reqDTO);
DbTablesRespDTO respDTO = new DbTablesRespDTO();
DBProperties dbProperties = new DBProperties();
dbProperties.setDbType(reqDTO.getDbType()).setDbUrl(reqDTO.getDbUrl());
dbProperties.setDbUserName(reqDTO.getDbUserName()).setDbPassword(reqDTO.getDbPassword());
Database database = null;
try { | database = DatabaseFactory.create(dbProperties); | 2 | 2023-12-30 15:32:55+00:00 | 2k |
akl7777777/ShellApiLogOptimizer | src/main/java/link/shellgpt/plugin/business/log/service/impl/LogServiceImpl.java | [
{
"identifier": "LogMapper",
"path": "src/main/java/link/shellgpt/plugin/business/log/dao/LogMapper.java",
"snippet": "public interface LogMapper extends BaseEsMapper<Log> {\n}"
},
{
"identifier": "Log",
"path": "src/main/java/link/shellgpt/plugin/business/log/model/Log.java",
"snippet":... | import cn.easyes.core.biz.EsPageInfo;
import cn.easyes.core.conditions.select.LambdaEsQueryWrapper;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import link.shellgpt.plugin.business.log.dao.LogMapper;
import link.shellgpt.plugin.business.log.model.Log;
import link.shellgpt.plugin.business.log.service.LogService;
import org.springframework.stereotype.Service;
import java.util.List; | 669 | package link.shellgpt.plugin.business.log.service.impl;
@Service
public class LogServiceImpl implements LogService {
| package link.shellgpt.plugin.business.log.service.impl;
@Service
public class LogServiceImpl implements LogService {
| private final LogMapper logMapper; | 0 | 2023-12-28 09:54:45+00:00 | 2k |
viceice/verbrauchsapp | app/src/main/java/de/anipe/verbrauchsapp/fragments/LocalImportFragment.java | [
{
"identifier": "CarLocalImportTask",
"path": "app/src/main/java/de/anipe/verbrauchsapp/tasks/CarLocalImportTask.java",
"snippet": "public class CarLocalImportTask extends AsyncTask<File, Void, Void> {\n private Activity mCon;\n private ProgressDialog myprogsdial;\n private int dataSets = 0;\n ... | import java.io.File;
import java.util.ArrayList;
import java.util.Map;
import de.anipe.verbrauchsapp.tasks.CarLocalImportTask;
import de.anipe.verbrauchsapp.tasks.UpdateLocalCarList; | 1,001 | package de.anipe.verbrauchsapp.fragments;
public class LocalImportFragment extends ImportFragment {
private Map<String, File> fileMapping;
public void update(ArrayList<String> names, Map<String, File> fileMapping) {
this.fileMapping = fileMapping;
update(names);
}
@Override
public void refresh() { | package de.anipe.verbrauchsapp.fragments;
public class LocalImportFragment extends ImportFragment {
private Map<String, File> fileMapping;
public void update(ArrayList<String> names, Map<String, File> fileMapping) {
this.fileMapping = fileMapping;
update(names);
}
@Override
public void refresh() { | new UpdateLocalCarList(this).execute(); | 1 | 2023-12-28 12:33:52+00:00 | 2k |
drSolutions-OpenSource/Utilizar_JDBC | psql/src/main/java/dao/TelefonesDAO.java | [
{
"identifier": "SingleConnection",
"path": "psql/src/main/java/conexaojdbc/SingleConnection.java",
"snippet": "public class SingleConnection {\n\tprivate static Connection connection = null;\n\n\tstatic {\n\t\tconectar();\n\t}\n\n\tpublic SingleConnection() {\n\t\tconectar();\n\t}\n\n\tprivate static v... | 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 org.postgresql.util.PSQLException;
import conexaojdbc.SingleConnection;
import model.Telefones; | 760 | package dao;
/**
* Telefones dos usuários
*
* @author Diego Mendes Rodrigues
* @version 1.0
*/
public class TelefonesDAO {
private Connection connection;
private String erro;
/**
* Construtor que realiza a conexão com o banco de dados
*/
public TelefonesDAO() { | package dao;
/**
* Telefones dos usuários
*
* @author Diego Mendes Rodrigues
* @version 1.0
*/
public class TelefonesDAO {
private Connection connection;
private String erro;
/**
* Construtor que realiza a conexão com o banco de dados
*/
public TelefonesDAO() { | connection = SingleConnection.getConnection(); | 0 | 2023-12-30 14:50:31+00:00 | 2k |
TuffetSpider/artismithery-0.0.1-1.20.1 | src/main/java/net/tuffetspider/artismithery/Artismithery.java | [
{
"identifier": "ModBlocks",
"path": "src/main/java/net/tuffetspider/artismithery/block/ModBlocks.java",
"snippet": "public class ModBlocks {\n public static final Block ARTISAN_TABLE = registerBlock(\"artisan_table\",\n new Block(FabricBlockSettings.copyOf(Blocks.CRAFTING_TABLE)));\n\n ... | import net.fabricmc.api.ModInitializer;
import net.tuffetspider.artismithery.block.ModBlocks;
import net.tuffetspider.artismithery.item.ModItemGroups;
import net.tuffetspider.artismithery.item.ModItems;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 870 | package net.tuffetspider.artismithery;
public class Artismithery implements ModInitializer {
public static final String MOD_ID = "artismithery";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
ModItemGroups.registerItemGroups(); | package net.tuffetspider.artismithery;
public class Artismithery implements ModInitializer {
public static final String MOD_ID = "artismithery";
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
ModItemGroups.registerItemGroups(); | ModItems.registerModItems(); | 2 | 2023-12-29 21:59:26+00:00 | 2k |
lushi78778/springboot-api-rapid-development-templates | src/main/java/top/lushi787778/api/interceptor/Interceptor.java | [
{
"identifier": "Result",
"path": "src/main/java/top/lushi787778/api/model/Result.java",
"snippet": "@Data\npublic class Result {\n\n /**\n * 100\tContinue\t继续。客户端应继续其请求\n * 200\tOK\t请求成功。一般用于GET与POST请求\n * 202\tAccepted\t已接受。已经接受请求,但未处理完成\n * 203\tParameter required\t错误的使用方法\n * ... | import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static top.lushi787778.api.utils.JWTCommonUtil.checkToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.lushi787778.api.model.Result;
import top.lushi787778.api.utils.JsonUtil; | 1,134 | /**
* MIT License
*
* Copyright (c) 2022 lushi78778
*
* 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 top.lushi787778.api.interceptor;
/**
* @ClassName Interceptor
* @Description 拦截器
* @Author lushi
* @Date 2022/1/20 19:06
*/
@Component
public class Interceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(Interceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { | /**
* MIT License
*
* Copyright (c) 2022 lushi78778
*
* 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 top.lushi787778.api.interceptor;
/**
* @ClassName Interceptor
* @Description 拦截器
* @Author lushi
* @Date 2022/1/20 19:06
*/
@Component
public class Interceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(Interceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { | Result result = new Result(); | 0 | 2023-12-30 23:51:52+00:00 | 2k |
1752597830/admin-common | qf-admin/back/admin-init-main/src/main/java/com/qf/web/controller/SysMenuController.java | [
{
"identifier": "BaseResponse",
"path": "qf-admin/back/admin-init-main/src/main/java/com/qf/common/utils/BaseResponse.java",
"snippet": "@Data\npublic class BaseResponse<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 响应码\n */\n private Stri... | import com.qf.common.utils.BaseResponse;
import com.qf.web.domain.dto.MenuOptionsDto;
import com.qf.web.domain.vo.RouteVo;
import com.qf.web.service.SysMenuService;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List; | 1,141 | package com.qf.web.controller;
/**
* @author : sin
* @date : 2023/12/15 19:08
* @Description :
*/
@RestController
@RequestMapping("/menus")
@Tag(name = "03.菜单接口")
public class SysMenuController {
@Resource
SysMenuService sysMenuService;
/**
* 获取路由信息
*/
@Schema(title = "获取路由")
@GetMapping("/routes")
public BaseResponse getRoutes() {
List<RouteVo> routes = sysMenuService.getRoutes();
return BaseResponse.success(routes);
}
/**
* 获取权限树
*/
@Schema(title = "获取权限树")
@GetMapping("/options")
public BaseResponse getPerms() { | package com.qf.web.controller;
/**
* @author : sin
* @date : 2023/12/15 19:08
* @Description :
*/
@RestController
@RequestMapping("/menus")
@Tag(name = "03.菜单接口")
public class SysMenuController {
@Resource
SysMenuService sysMenuService;
/**
* 获取路由信息
*/
@Schema(title = "获取路由")
@GetMapping("/routes")
public BaseResponse getRoutes() {
List<RouteVo> routes = sysMenuService.getRoutes();
return BaseResponse.success(routes);
}
/**
* 获取权限树
*/
@Schema(title = "获取权限树")
@GetMapping("/options")
public BaseResponse getPerms() { | List<MenuOptionsDto> sysMenus = sysMenuService.getMenuOptions(); | 1 | 2023-12-30 13:42:53+00:00 | 2k |
JIGerss/Salus | salus-web/src/main/java/team/glhf/salus/service/PageService.java | [
{
"identifier": "DetailVo",
"path": "salus-pojo/src/main/java/team/glhf/salus/vo/detail/DetailVo.java",
"snippet": "@Data\r\n@Builder\r\npublic class DetailVo implements Serializable {\r\n\r\n private DetailUserVo host;\r\n\r\n private String articleId;\r\n\r\n private String title;\r\n\r\n ... | import team.glhf.salus.dto.page.*;
import team.glhf.salus.vo.detail.DetailVo;
import team.glhf.salus.vo.dynamic.DynamicVo;
import team.glhf.salus.vo.gym.PlaceDetailVo;
import team.glhf.salus.vo.gym.PlacePageVo;
import team.glhf.salus.vo.index.IndexListArticleVo;
import team.glhf.salus.vo.index.IndexVo;
import team.glhf.salus.vo.user.UserPageVo;
| 1,014 | package team.glhf.salus.service;
/**
* @author Steveny
* @since 2023/11/12
*/
public interface PageService {
/**
* 请求首页
*/
IndexVo getIndexPage(IndexReq indexReq);
/**
* 请求额外的文章
*/
IndexListArticleVo getIndexArticles(IndexListArticleReq indexReq);
/**
* 请求用户页面
*/
| package team.glhf.salus.service;
/**
* @author Steveny
* @since 2023/11/12
*/
public interface PageService {
/**
* 请求首页
*/
IndexVo getIndexPage(IndexReq indexReq);
/**
* 请求额外的文章
*/
IndexListArticleVo getIndexArticles(IndexListArticleReq indexReq);
/**
* 请求用户页面
*/
| UserPageVo getUserPage(String userId);
| 6 | 2023-12-23 15:03:37+00:00 | 2k |
swsm/proxynet | proxynet-common/src/main/java/com/swsm/proxynet/common/handler/ProxyNetMessageEncoder.java | [
{
"identifier": "ProxyNetMessage",
"path": "proxynet-common/src/main/java/com/swsm/proxynet/common/model/ProxyNetMessage.java",
"snippet": "@Data\npublic class ProxyNetMessage {\n\n public static final byte CONNECT = 0x01;\n public static final byte CONNECT_RESP = 0x02;\n public static final by... | import com.swsm.proxynet.common.model.ProxyNetMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_INFO_SIZE;
import static com.swsm.proxynet.common.Constants.PROXY_MESSAGE_TYPE_SIZE; | 737 | package com.swsm.proxynet.common.handler;
/**
* @author liujie
* @date 2023-04-15
*/
public class ProxyNetMessageEncoder extends MessageToByteEncoder<ProxyNetMessage> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage, ByteBuf byteBuf) throws Exception { | package com.swsm.proxynet.common.handler;
/**
* @author liujie
* @date 2023-04-15
*/
public class ProxyNetMessageEncoder extends MessageToByteEncoder<ProxyNetMessage> {
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, ProxyNetMessage proxyNetMessage, ByteBuf byteBuf) throws Exception { | int bodyLength = PROXY_MESSAGE_TYPE_SIZE + PROXY_MESSAGE_INFO_SIZE; | 1 | 2023-12-25 03:25:38+00:00 | 2k |
Trodev-IT/ScanHub | app/src/main/java/com/trodev/scanhub/fragments/EmailFragment.java | [
{
"identifier": "EmailAdapter",
"path": "app/src/main/java/com/trodev/scanhub/adapters/EmailAdapter.java",
"snippet": "public class EmailAdapter extends RecyclerView.Adapter<EmailAdapter.MyViewHolder> {\n\n private Context context;\n private ArrayList<EmailModel> list;\n private String category... | import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.trodev.scanhub.R;
import com.trodev.scanhub.adapters.EmailAdapter;
import com.trodev.scanhub.models.EmailModel;
import java.util.ArrayList; | 1,070 | package com.trodev.scanhub.fragments;
public class EmailFragment extends Fragment {
private RecyclerView recyclerView;
DatabaseReference reference; | package com.trodev.scanhub.fragments;
public class EmailFragment extends Fragment {
private RecyclerView recyclerView;
DatabaseReference reference; | ArrayList<EmailModel> list; | 1 | 2023-12-26 05:10:38+00:00 | 2k |
DMSAranda/backend-usersapp | src/main/java/com/dms/backend/usersapp/backendusersapp/services/UserServiceImpl.java | [
{
"identifier": "IUser",
"path": "src/main/java/com/dms/backend/usersapp/backendusersapp/models/IUser.java",
"snippet": "public interface IUser {\n\n boolean isAdmin();\n \n}"
},
{
"identifier": "UserDto",
"path": "src/main/java/com/dms/backend/usersapp/backendusersapp/models/dto/UserD... | import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dms.backend.usersapp.backendusersapp.models.IUser;
import com.dms.backend.usersapp.backendusersapp.models.dto.UserDto;
import com.dms.backend.usersapp.backendusersapp.models.dto.mapper.DtoMapperUser;
import com.dms.backend.usersapp.backendusersapp.models.entities.Role;
import com.dms.backend.usersapp.backendusersapp.models.entities.User;
import com.dms.backend.usersapp.backendusersapp.models.request.UserRequest;
import com.dms.backend.usersapp.backendusersapp.repositories.RoleRepository;
import com.dms.backend.usersapp.backendusersapp.repositories.UserRepository; | 1,211 | package com.dms.backend.usersapp.backendusersapp.services;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository repository;
@Autowired | package com.dms.backend.usersapp.backendusersapp.services;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserRepository repository;
@Autowired | private RoleRepository repository2; | 6 | 2023-12-29 15:55:27+00:00 | 2k |
singuuu/java-spring-api | src/main/java/com/singu/api/controllers/auth/AuthenticationController.java | [
{
"identifier": "AuthenticationRequest",
"path": "src/main/java/com/singu/api/domains/requests/AuthenticationRequest.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AuthenticationRequest {\n\n String password;\n private String email;\n}"
},
{
"iden... | import com.singu.api.domains.requests.AuthenticationRequest;
import com.singu.api.domains.requests.RegisterRequest;
import com.singu.api.domains.responses.AuthenticationResponse;
import com.singu.api.services.AuthenticationService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
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;
import java.io.IOException; | 1,116 | package com.singu.api.controllers.auth;
@RestController
@RequiredArgsConstructor
@Tag(name = "Authentication")
@RequestMapping("/api/v1/auth")
public class AuthenticationController {
private final AuthenticationService service;
@PostMapping("/register") | package com.singu.api.controllers.auth;
@RestController
@RequiredArgsConstructor
@Tag(name = "Authentication")
@RequestMapping("/api/v1/auth")
public class AuthenticationController {
private final AuthenticationService service;
@PostMapping("/register") | public ResponseEntity<AuthenticationResponse> register( | 2 | 2023-12-28 17:32:16+00:00 | 2k |
vnlemanhthanh/sfg-spring-6-webapp | src/main/java/com/vnlemanhthanh/spring6webapp/services/BookServiceImpl.java | [
{
"identifier": "Book",
"path": "src/main/java/com/vnlemanhthanh/spring6webapp/domain/Book.java",
"snippet": "@Entity\npublic class Book {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n private Long id;\n private String title;\n private String isbn;\n\n @ManyToMany\n @J... | import org.springframework.stereotype.Service;
import com.vnlemanhthanh.spring6webapp.domain.Book;
import com.vnlemanhthanh.spring6webapp.repositories.BookRepository; | 660 | /*
* Copyright (c) 2023. vnlemanhthanh.com
*/
package com.vnlemanhthanh.spring6webapp.services;
@Service
public class BookServiceImpl implements BookService {
| /*
* Copyright (c) 2023. vnlemanhthanh.com
*/
package com.vnlemanhthanh.spring6webapp.services;
@Service
public class BookServiceImpl implements BookService {
| private final BookRepository bookRepository; | 1 | 2023-12-25 07:31:22+00:00 | 2k |
jordqubbe/Extras | src/main/java/dev/jordgubbe/extras/commands/Vanish.java | [
{
"identifier": "Main",
"path": "src/main/java/dev/jordgubbe/extras/Main.java",
"snippet": "public final class Main extends JavaPlugin {\n\n public void configMethods() {\n getConfig().options().copyDefaults(true);\n saveDefaultConfig();\n }\n\n private void registerCommands() {\n... | import dev.jordgubbe.extras.Main;
import dev.jordgubbe.extras.utils.ColorUtils;
import dev.jordgubbe.extras.utils.ConsoleUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.UUID; | 1,290 | package dev.jordgubbe.extras.commands;
public class Vanish implements CommandExecutor {
private final ArrayList<UUID> vanished = new ArrayList<>();
private final Main plugin;
public Vanish(Main plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] strings) {
if (!(sender instanceof Player player)) { | package dev.jordgubbe.extras.commands;
public class Vanish implements CommandExecutor {
private final ArrayList<UUID> vanished = new ArrayList<>();
private final Main plugin;
public Vanish(Main plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String s, String[] strings) {
if (!(sender instanceof Player player)) { | sender.sendMessage(ColorUtils.format(ConsoleUtils.NOT_A_PLAYER.print())); | 2 | 2023-12-27 06:37:11+00:00 | 2k |
LogDeArgentina/server | src/main/java/me/drpuc/lda/service/impl/FileServiceImpl.java | [
{
"identifier": "User",
"path": "src/main/java/me/drpuc/lda/entity/User.java",
"snippet": "@Entity\n@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@Table(name = \"\\\"user\\\"\")\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n @Column(unique = true, ... | import lombok.RequiredArgsConstructor;
import me.drpuc.lda.entity.User;
import me.drpuc.lda.entity.VerificationFile;
import me.drpuc.lda.repository.FileRepository;
import me.drpuc.lda.service.FileService;
import me.drpuc.lda.repository.FileContentStore;
import org.springframework.core.io.InputStreamResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.LinkedList;
import java.util.List;
import java.util.Set; | 871 | package me.drpuc.lda.service.impl;
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
private final FileRepository fileRepository; | package me.drpuc.lda.service.impl;
@Service
@RequiredArgsConstructor
public class FileServiceImpl implements FileService {
private final FileRepository fileRepository; | private final FileContentStore fileContentStore; | 4 | 2023-12-24 16:58:17+00:00 | 2k |
strokegmd/StrokeClient | stroke/client/commands/impl/FriendsListCommand.java | [
{
"identifier": "StrokeClient",
"path": "stroke/client/StrokeClient.java",
"snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpubli... | import net.stroke.client.StrokeClient;
import net.stroke.client.commands.BaseCommand;
import net.stroke.client.util.FriendsManager;
| 1,006 | package net.stroke.client.commands.impl;
public class FriendsListCommand extends BaseCommand {
public FriendsListCommand() {
super("friends list", 2);
}
public boolean onChatMessage(String message) {
if(!message.contains(this.chatName)) {
return false;
}
| package net.stroke.client.commands.impl;
public class FriendsListCommand extends BaseCommand {
public FriendsListCommand() {
super("friends list", 2);
}
public boolean onChatMessage(String message) {
if(!message.contains(this.chatName)) {
return false;
}
| String friendsNumber = Integer.toString(FriendsManager.friends.size());
| 2 | 2023-12-31 10:56:59+00:00 | 2k |
Supriya2301/EVotingSystem-SpringJPA | EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/services/VotingService.java | [
{
"identifier": "Election",
"path": "EVotingSystem/src/main/java/com/codingninjas/EVotingSystem/entities/Election.java",
"snippet": "@Entity\npublic class Election {\n\t@Id\n\t@GeneratedValue(strategy= GenerationType.AUTO)\n\tprivate long id;\n\t\n\t@Column(unique=true)\n\tprivate String name;\n\n\tpubl... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.codingninjas.EVotingSystem.entities.Election;
import com.codingninjas.EVotingSystem.entities.ElectionChoice;
import com.codingninjas.EVotingSystem.entities.User;
import com.codingninjas.EVotingSystem.entities.Vote;
import com.codingninjas.EVotingSystem.repositories.ElectionChoiceRepository;
import com.codingninjas.EVotingSystem.repositories.ElectionRepository;
import com.codingninjas.EVotingSystem.repositories.UserRepository;
import com.codingninjas.EVotingSystem.repositories.VoteRepository; | 1,493 | package com.codingninjas.EVotingSystem.services;
@Service
public class VotingService {
@Autowired
VoteRepository voteRepository;
@Autowired | package com.codingninjas.EVotingSystem.services;
@Service
public class VotingService {
@Autowired
VoteRepository voteRepository;
@Autowired | UserRepository userRepository; | 6 | 2023-12-30 06:54:58+00:00 | 2k |
piovas-lu/condominio | src/main/java/app/condominio/controller/PeriodoController.java | [
{
"identifier": "Periodo",
"path": "src/main/java/app/condominio/domain/Periodo.java",
"snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"periodos\")\r\npublic class Periodo implements Serializable, Comparable<Periodo> {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.ID... | import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import app.condominio.domain.Periodo;
import app.condominio.service.PeriodoService;
| 1,369 | package app.condominio.controller;
@Controller
@RequestMapping("sindico/periodos")
public class PeriodoController {
@Autowired
private PeriodoService periodoService;
@ModelAttribute("ativo")
public String[] ativo() {
return new String[] { "contabilidade", "periodos" };
}
@GetMapping({ "", "/", "/lista" })
public ModelAndView getPeriodos(@RequestParam("pagina") Optional<Integer> pagina,
@RequestParam("tamanho") Optional<Integer> tamanho, ModelMap model) {
model.addAttribute("periodos",
periodoService.listarPagina(PageRequest.of(pagina.orElse(1) - 1, tamanho.orElse(20))));
model.addAttribute("conteudo", "periodoLista");
return new ModelAndView("fragmentos/layoutSindico", model);
}
@GetMapping("/cadastro")
| package app.condominio.controller;
@Controller
@RequestMapping("sindico/periodos")
public class PeriodoController {
@Autowired
private PeriodoService periodoService;
@ModelAttribute("ativo")
public String[] ativo() {
return new String[] { "contabilidade", "periodos" };
}
@GetMapping({ "", "/", "/lista" })
public ModelAndView getPeriodos(@RequestParam("pagina") Optional<Integer> pagina,
@RequestParam("tamanho") Optional<Integer> tamanho, ModelMap model) {
model.addAttribute("periodos",
periodoService.listarPagina(PageRequest.of(pagina.orElse(1) - 1, tamanho.orElse(20))));
model.addAttribute("conteudo", "periodoLista");
return new ModelAndView("fragmentos/layoutSindico", model);
}
@GetMapping("/cadastro")
| public ModelAndView getPeriodoCadastro(@ModelAttribute("periodo") Periodo periodo) {
| 0 | 2023-12-29 22:19:42+00:00 | 2k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.