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 |
---|---|---|---|---|---|---|---|---|---|---|
haystack666/HaystackMerchandiseStore | src/com/haystack/FruitShop/Main/showMyCart.java | [
{
"identifier": "FruitInfo",
"path": "src/com/haystack/FruitShop/info/FruitInfo.java",
"snippet": "public class FruitInfo {\r\n private String FruitId;\r\n private String FruitName;\r\n private String FruitType;\r\n private String FruitIntroduce;\r\n private String FruitPrice;\r\n private String FruitQuantity;\r\n\r\n public FruitInfo(String fruitId, String fruitName, String fruittype, String fruitIntroduce, String fruitPrice, String fruitQuantity) {\r\n this.FruitId = fruitId;\r\n this.FruitName = fruitName;\r\n this.FruitType = fruittype;\r\n this.FruitIntroduce = fruitIntroduce;\r\n this.FruitPrice = fruitPrice;\r\n this.FruitQuantity = fruitQuantity;\r\n }\r\n\r\n public FruitInfo() {\r\n\r\n }\r\n\r\n public String getFruitId() {\r\n return FruitId;\r\n }\r\n\r\n public void setFruitId(String fruitId) {\r\n FruitId = fruitId;\r\n }\r\n\r\n public String getFruitName() {\r\n return FruitName;\r\n }\r\n\r\n public void setFruitName(String fruitName) {\r\n FruitName = fruitName;\r\n }\r\n\r\n public String getFruitType() {\r\n return FruitType;\r\n }\r\n\r\n public void setFruitType(String fruittype) {\r\n FruitType = fruittype;\r\n }\r\n\r\n public String getFruitIntroduce() {\r\n return FruitIntroduce;\r\n }\r\n\r\n public void setFruitIntroduce(String fruitIntroduce) {\r\n FruitIntroduce = fruitIntroduce;\r\n }\r\n\r\n public String getFruitPrice() {\r\n return FruitPrice;\r\n }\r\n\r\n public void setFruitPrice(String fruitPrice) {\r\n FruitPrice = fruitPrice;\r\n }\r\n\r\n public String getFruitQuantity() {\r\n return FruitQuantity;\r\n }\r\n\r\n public void setFruitQuantity(String fruitQuantity) {\r\n FruitQuantity = fruitQuantity;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"FruitInfo{\" +\r\n \"FruitId=\" + FruitId +\r\n \", FruitName='\" + FruitName + '\\'' +\r\n \", FruitType='\" + FruitType + '\\'' +\r\n \", FruitIntroduce='\" + FruitIntroduce + '\\'' +\r\n \", FruitPrice=\" + FruitPrice +\r\n \", FruitQuantity=\" + FruitQuantity +\r\n '}';\r\n }\r\n}\r"
},
{
"identifier": "DBConnect",
"path": "src/com/haystack/util/DBConnect.java",
"snippet": "public class DBConnect {\r\n public static Connection getConn() throws ClassNotFoundException, SQLException {\r\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\r\n String sqlurl = \"jdbc:mysql://localhost:3306/YourDatabaseName?useSSL=false&serverTimezone=UTC\";\r\n String sqlusername = \"root\";\r\n String sqlpassword = \"YourDatabasePassword\";\r\n Connection connection = DriverManager.getConnection(sqlurl, sqlusername, sqlpassword);\r\n return connection;\r\n }\r\n public static void closeConnection(Statement statement, Connection connection) throws SQLException {\r\n statement.close();\r\n connection.close();\r\n }\r\n\r\n public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection) throws SQLException {\r\n statement.close();\r\n closeConnection(statement,connection);\r\n }\r\n}\r"
}
] | import com.haystack.FruitShop.info.FruitInfo;
import com.haystack.util.DBConnect;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
| 1,110 | package com.haystack.FruitShop.Main;
@WebServlet("/showMyCart")
public class showMyCart extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 检查session是否存在
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("username") == null || session.getAttribute("password") == null) {
response.getWriter().write("尚未登录,前往<a href='login.jsp' >登录</a>");
return;
}
String usernameInSession = String.valueOf(session.getAttribute("username"));
try {
Connection conn = DBConnect.getConn();
// 创建 PreparedStatement
String sql = "SELECT * FROM myshopcart WHERE whoAdd = ? ORDER BY CAST(id AS SIGNED)";
try (PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
preparedStatement.setString(1, usernameInSession);
// 执行查询并获取结果集
ResultSet resultSet = preparedStatement.executeQuery();
// 将查询结果存储到List中
| package com.haystack.FruitShop.Main;
@WebServlet("/showMyCart")
public class showMyCart extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 检查session是否存在
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("username") == null || session.getAttribute("password") == null) {
response.getWriter().write("尚未登录,前往<a href='login.jsp' >登录</a>");
return;
}
String usernameInSession = String.valueOf(session.getAttribute("username"));
try {
Connection conn = DBConnect.getConn();
// 创建 PreparedStatement
String sql = "SELECT * FROM myshopcart WHERE whoAdd = ? ORDER BY CAST(id AS SIGNED)";
try (PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
preparedStatement.setString(1, usernameInSession);
// 执行查询并获取结果集
ResultSet resultSet = preparedStatement.executeQuery();
// 将查询结果存储到List中
| List<FruitInfo> FruitInfo = new ArrayList<>();
| 0 | 2023-12-08 07:46:48+00:00 | 2k |
muchfish/ruoyi-vue-pro-sample | yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/service/property/ProductPropertyService.java | [
{
"identifier": "PageResult",
"path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/pojo/PageResult.java",
"snippet": "@Schema(description = \"分页结果\")\n@Data\npublic final class PageResult<T> implements Serializable {\n\n @Schema(description = \"数据\", requiredMode = Schema.RequiredMode.REQUIRED)\n private List<T> list;\n\n @Schema(description = \"总量\", requiredMode = Schema.RequiredMode.REQUIRED)\n private Long total;\n\n public PageResult() {\n }\n\n public PageResult(List<T> list, Long total) {\n this.list = list;\n this.total = total;\n }\n\n public PageResult(Long total) {\n this.list = new ArrayList<>();\n this.total = total;\n }\n\n public static <T> PageResult<T> empty() {\n return new PageResult<>(0L);\n }\n\n public static <T> PageResult<T> empty(Long total) {\n return new PageResult<>(total);\n }\n\n}"
},
{
"identifier": "ProductPropertyCreateReqVO",
"path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/property/vo/property/ProductPropertyCreateReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 属性项创建 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\npublic class ProductPropertyCreateReqVO extends ProductPropertyBaseVO {\n\n\n}"
},
{
"identifier": "ProductPropertyListReqVO",
"path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/property/vo/property/ProductPropertyListReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 属性项 List Request VO\")\n@Data\n@ToString(callSuper = true)\npublic class ProductPropertyListReqVO {\n\n @Schema(description = \"属性名称\", example = \"颜色\")\n private String name;\n\n}"
},
{
"identifier": "ProductPropertyPageReqVO",
"path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/property/vo/property/ProductPropertyPageReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 属性项 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\npublic class ProductPropertyPageReqVO extends PageParam {\n\n @Schema(description = \"名称\", example = \"颜色\")\n private String name;\n\n @Schema(description = \"状态\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"1\")\n private Integer status;\n\n @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)\n @Schema(description = \"创建时间\")\n private LocalDateTime[] createTime;\n\n}"
},
{
"identifier": "ProductPropertyUpdateReqVO",
"path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/property/vo/property/ProductPropertyUpdateReqVO.java",
"snippet": "@Schema(description = \"管理后台 - 属性项更新 Request VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\npublic class ProductPropertyUpdateReqVO extends ProductPropertyBaseVO {\n\n @Schema(description = \"主键\", requiredMode = Schema.RequiredMode.REQUIRED, example = \"1\")\n @NotNull(message = \"主键不能为空\")\n private Long id;\n\n}"
},
{
"identifier": "ProductPropertyDO",
"path": "yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/dal/dataobject/property/ProductPropertyDO.java",
"snippet": "@TableName(\"product_property\")\n@KeySequence(\"product_property_seq\") // 用于 Oracle、PostgreSQL、Kingbase、DB2、H2 数据库的主键自增。如果是 MySQL 等数据库,可不写。\n@Data\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ProductPropertyDO extends BaseDO {\n\n /**\n * SPU 单规格时,默认属性 id\n */\n public static final Long ID_DEFAULT = 0L;\n /**\n * SPU 单规格时,默认属性名字\n */\n public static final String NAME_DEFAULT = \"默认\";\n\n /**\n * 主键\n */\n @TableId\n private Long id;\n /**\n * 名称\n */\n private String name;\n /**\n * 状态\n */\n private Integer status;\n /**\n * 备注\n */\n private String remark;\n\n}"
}
] | import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.product.controller.admin.property.vo.property.ProductPropertyCreateReqVO;
import cn.iocoder.yudao.module.product.controller.admin.property.vo.property.ProductPropertyListReqVO;
import cn.iocoder.yudao.module.product.controller.admin.property.vo.property.ProductPropertyPageReqVO;
import cn.iocoder.yudao.module.product.controller.admin.property.vo.property.ProductPropertyUpdateReqVO;
import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyDO;
import javax.validation.Valid;
import java.util.Collection;
import java.util.List; | 1,446 | package cn.iocoder.yudao.module.product.service.property;
/**
* 商品属性项 Service 接口
*
* @author 芋道源码
*/
public interface ProductPropertyService {
/**
* 创建属性项
* 注意,如果已经存在该属性项,直接返回它的编号即可
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createProperty(@Valid ProductPropertyCreateReqVO createReqVO);
/**
* 更新属性项
*
* @param updateReqVO 更新信息
*/
void updateProperty(@Valid ProductPropertyUpdateReqVO updateReqVO);
/**
* 删除属性项
*
* @param id 编号
*/
void deleteProperty(Long id);
/**
* 获得属性项列表
*
* @param listReqVO 集合查询
* @return 属性项集合
*/ | package cn.iocoder.yudao.module.product.service.property;
/**
* 商品属性项 Service 接口
*
* @author 芋道源码
*/
public interface ProductPropertyService {
/**
* 创建属性项
* 注意,如果已经存在该属性项,直接返回它的编号即可
*
* @param createReqVO 创建信息
* @return 编号
*/
Long createProperty(@Valid ProductPropertyCreateReqVO createReqVO);
/**
* 更新属性项
*
* @param updateReqVO 更新信息
*/
void updateProperty(@Valid ProductPropertyUpdateReqVO updateReqVO);
/**
* 删除属性项
*
* @param id 编号
*/
void deleteProperty(Long id);
/**
* 获得属性项列表
*
* @param listReqVO 集合查询
* @return 属性项集合
*/ | List<ProductPropertyDO> getPropertyList(ProductPropertyListReqVO listReqVO); | 5 | 2023-12-08 02:48:42+00:00 | 2k |
awesome-java-web/groovy-script-executor | src/main/java/com/github/awesome/scripting/groovy/GroovyScriptExecutor.java | [
{
"identifier": "LocalCacheManager",
"path": "src/main/java/com/github/awesome/scripting/groovy/cache/LocalCacheManager.java",
"snippet": "public class LocalCacheManager implements LocalCache {\n\n private LocalCache localCache;\n\n public static LocalCacheManager newBuilder() {\n return new LocalCacheManager();\n }\n\n public LocalCacheManager use(LocalCache localCache) {\n this.localCache = localCache;\n return this;\n }\n\n public LocalCacheManager useDefaultCache() {\n Cache<String, GroovyObject> defaultCache = Caffeine.newBuilder()\n .initialCapacity(1)\n .maximumSize(10)\n .expireAfterAccess(Duration.ofDays(1))\n .recordStats()\n .build();\n this.localCache = new CaffeineLocalCache(defaultCache);\n return this;\n }\n\n @Override\n public GroovyObject getIfPresent(String key) {\n return this.localCache.getIfPresent(key);\n }\n\n @Override\n public void put(String key, GroovyObject groovyObject) {\n this.localCache.put(key, groovyObject);\n }\n\n @Override\n public String stats() {\n return this.localCache.stats();\n }\n\n}"
},
{
"identifier": "GroovyObjectInvokeMethodException",
"path": "src/main/java/com/github/awesome/scripting/groovy/exception/GroovyObjectInvokeMethodException.java",
"snippet": "public class GroovyObjectInvokeMethodException extends RuntimeException {\n\n public GroovyObjectInvokeMethodException(String message) {\n super(message);\n }\n\n}"
},
{
"identifier": "GroovyScriptParseException",
"path": "src/main/java/com/github/awesome/scripting/groovy/exception/GroovyScriptParseException.java",
"snippet": "public class GroovyScriptParseException extends RuntimeException {\n\n public GroovyScriptParseException(String message) {\n super(message);\n }\n\n}"
},
{
"identifier": "InvalidGroovyScriptException",
"path": "src/main/java/com/github/awesome/scripting/groovy/exception/InvalidGroovyScriptException.java",
"snippet": "public class InvalidGroovyScriptException extends RuntimeException {\n\n public InvalidGroovyScriptException(String message) {\n super(message);\n }\n\n}"
},
{
"identifier": "DefaultGroovyScriptSecurityChecker",
"path": "src/main/java/com/github/awesome/scripting/groovy/security/DefaultGroovyScriptSecurityChecker.java",
"snippet": "public class DefaultGroovyScriptSecurityChecker implements GroovyScriptSecurityChecker {\n\n @Override\n public Collection<String> shouldInterceptKeywords() {\n DefaultShouldInterceptKeywords[] keywords = DefaultShouldInterceptKeywords.values();\n return Arrays.stream(keywords).map(DefaultShouldInterceptKeywords::getKeyword).collect(Collectors.toSet());\n }\n\n @Override\n public void checkOrThrow(String script) {\n Collection<String> keywords = shouldInterceptKeywords();\n for (String keyword : keywords) {\n if (script.contains(keyword)) {\n final String errorMessage = String.format(\n \"Groovy script contains potentially unsafe keyword: '%s', %s, please notice the following keywords are all considered unsafe: %s\",\n keyword, Objects.requireNonNull(DefaultShouldInterceptKeywords.fromKeyword(keyword)).getExplanation(), keywords\n );\n throw new GroovyScriptSecurityException(errorMessage);\n }\n }\n }\n\n}"
},
{
"identifier": "GroovyScriptSecurityChecker",
"path": "src/main/java/com/github/awesome/scripting/groovy/security/GroovyScriptSecurityChecker.java",
"snippet": "public interface GroovyScriptSecurityChecker {\n\n Collection<String> shouldInterceptKeywords();\n\n void checkOrThrow(String script);\n}"
},
{
"identifier": "Md5Utils",
"path": "src/main/java/com/github/awesome/scripting/groovy/util/Md5Utils.java",
"snippet": "public final class Md5Utils {\n\n private static final String MESSAGE_DIGEST_ALGORITHM_MD5 = \"MD5\";\n\n private Md5Utils() {\n throw new UnsupportedOperationException(\"Utility class should not be instantiated\");\n }\n\n public static byte[] md5(String input) {\n try {\n MessageDigest md5 = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM_MD5);\n return md5.digest(input.getBytes(StandardCharsets.UTF_8));\n } catch (NoSuchAlgorithmException e) {\n return new byte[0];\n }\n }\n\n public static String md5Hex(String input) {\n StringBuilder sb = new StringBuilder();\n byte[] digest = md5(input);\n for (byte b : digest) {\n sb.append(String.format(\"%02x\", b));\n }\n return sb.toString();\n }\n\n}"
}
] | import com.github.awesome.scripting.groovy.cache.LocalCacheManager;
import com.github.awesome.scripting.groovy.exception.GroovyObjectInvokeMethodException;
import com.github.awesome.scripting.groovy.exception.GroovyScriptParseException;
import com.github.awesome.scripting.groovy.exception.InvalidGroovyScriptException;
import com.github.awesome.scripting.groovy.security.DefaultGroovyScriptSecurityChecker;
import com.github.awesome.scripting.groovy.security.GroovyScriptSecurityChecker;
import com.github.awesome.scripting.groovy.util.Md5Utils;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.IOException; | 1,185 | package com.github.awesome.scripting.groovy;
public class GroovyScriptExecutor {
private LocalCacheManager localCacheManager;
| package com.github.awesome.scripting.groovy;
public class GroovyScriptExecutor {
private LocalCacheManager localCacheManager;
| private GroovyScriptSecurityChecker groovyScriptSecurityChecker; | 5 | 2023-12-11 03:30:22+00:00 | 2k |
ItzOverS/CoReScreen | src/main/java/me/overlight/corescreen/ClientSettings/Modules/RenderDistance.java | [
{
"identifier": "CSModule",
"path": "src/main/java/me/overlight/corescreen/ClientSettings/CSModule.java",
"snippet": "public class CSModule {\n private final String name, permission;\n\n public String getName() {\n return name;\n }\n\n public String getPermission() {\n return permission;\n }\n\n public CSModule(String name, String permission) {\n this.permission = permission;\n this.name = name;\n }\n\n public String getValue(Player player) {\n return null;\n }\n}"
},
{
"identifier": "ClientSettingsGrabber",
"path": "src/main/java/me/overlight/corescreen/ClientSettings/ClientSettingsGrabber.java",
"snippet": "public class ClientSettingsGrabber extends PacketListenerAbstract {\n private final static HashMap<String, PlayerClientSettings> settings = new HashMap<>();\n @Override\n public void onPacketPlayReceive(PacketPlayReceiveEvent e) {\n if(e.getPacketId() == PacketType.Play.Client.SETTINGS){\n WrappedPacketInSettings packet = new WrappedPacketInSettings(e.getNMSPacket());\n settings.put(e.getPlayer().getName(), new PlayerClientSettings(packet.getViewDistance(), packet.getChatVisibility(), packet.getLocale(), packet.getDisplayedSkinParts()));\n }\n }\n\n public static PlayerClientSettings getSettings(Player player){\n return settings.getOrDefault(player.getName(), null);\n }\n\n public static class PlayerClientSettings {\n private final int renderDistance;\n private final WrappedPacketInSettings.ChatVisibility chatVisibility;\n private final String locale;\n private final Set<WrappedPacketInSettings.DisplayedSkinPart> displayedSkinPartSet;\n\n public PlayerClientSettings(int renderDistance, WrappedPacketInSettings.ChatVisibility chatVisibility, String locale, Set<WrappedPacketInSettings.DisplayedSkinPart> displayedSkinPartSet) {\n this.renderDistance = renderDistance;\n this.chatVisibility = chatVisibility;\n this.locale = locale;\n this.displayedSkinPartSet = displayedSkinPartSet;\n }\n\n public int getRenderDistance() {\n return renderDistance;\n }\n\n public WrappedPacketInSettings.ChatVisibility getChatVisibility() {\n return chatVisibility;\n }\n\n public String getLocale() {\n return locale;\n }\n\n public Set<WrappedPacketInSettings.DisplayedSkinPart> getDisplayedSkinPartSet() {\n return displayedSkinPartSet;\n }\n }\n}"
}
] | import me.overlight.corescreen.ClientSettings.CSModule;
import me.overlight.corescreen.ClientSettings.ClientSettingsGrabber;
import org.bukkit.entity.Player; | 645 | package me.overlight.corescreen.ClientSettings.Modules;
public class RenderDistance extends CSModule {
public RenderDistance() {
super("RenderDistance", "renderdistance");
}
@Override
public String getValue(Player player) { | package me.overlight.corescreen.ClientSettings.Modules;
public class RenderDistance extends CSModule {
public RenderDistance() {
super("RenderDistance", "renderdistance");
}
@Override
public String getValue(Player player) { | return String.valueOf(ClientSettingsGrabber.getSettings(player).getRenderDistance()); | 1 | 2023-12-07 16:34:39+00:00 | 2k |
liangyuanpeng/lank8s.cn | java/springboot/src/main/java/cn/lank8s/springboot/listener/ApplicationReadyEventListener.java | [
{
"identifier": "LocationServerConfig",
"path": "java/springboot/src/main/java/cn/lank8s/springboot/bean/LocationServerConfig.java",
"snippet": "@Data\n@ConfigurationProperties(prefix = \"kafeidou.forward.servers\")\n@Configuration\npublic class LocationServerConfig {\n Map<String, List<String>> servers = Maps.newLinkedHashMap();\n}"
},
{
"identifier": "ThreadHelper",
"path": "java/springboot/src/main/java/cn/lank8s/springboot/helper/ThreadHelper.java",
"snippet": "public class ThreadHelper {\n\n public static final ExecutorService executorService = Executors.newFixedThreadPool(3);\n}"
},
{
"identifier": "ConfigMapConfigWatcher",
"path": "java/springboot/src/main/java/cn/lank8s/springboot/region/ConfigMapConfigWatcher.java",
"snippet": "@Slf4j\npublic class ConfigMapConfigWatcher {\n\n public ConfigMapConfigWatcher(){\n\n }\n\n public void watch() throws IOException, ApiException {\n ApiClient client = Config.defaultClient();\n // infinite timeout\n OkHttpClient httpClient =\n client.getHttpClient().newBuilder().readTimeout(0, TimeUnit.SECONDS).build();\n client.setHttpClient(httpClient);\n Configuration.setDefaultApiClient(client);\n\n CoreV1Api api = new CoreV1Api();\n\n Watch<V1ConfigMap> watch =\n Watch.createWatch(\n client,\n api.listNamespacedConfigMapCall(\"default\", \"\", false,\n null, null, null, null, null, null, null, true, new ApiCallback() {\n @Override\n public void onFailure(ApiException e, int statusCode, Map responseHeaders) {\n\n }\n\n @Override\n public void onSuccess(Object result, int statusCode, Map responseHeaders) {\n\n }\n\n @Override\n public void onUploadProgress(long bytesWritten, long contentLength, boolean done) {\n\n }\n\n @Override\n public void onDownloadProgress(long bytesRead, long contentLength, boolean done) {\n\n }\n }),\n new TypeToken<Watch.Response<V1ConfigMap>>() {}.getType());\n\n try {\n for (Watch.Response<V1ConfigMap> item : watch) {\n log.info(\"{}|{}|{}\",item.type,item.object.getMetadata().getNamespace(), item.object.getMetadata().getName());\n }\n } finally {\n watch.close();\n }\n }\n\n}"
}
] | import cn.lank8s.springboot.bean.LocationServerConfig;
import cn.lank8s.springboot.helper.ThreadHelper;
import cn.lank8s.springboot.region.ConfigMapConfigWatcher;
import io.kubernetes.client.openapi.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.io.IOException; | 718 | package cn.lank8s.springboot.listener;
@Component
@Slf4j
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
LocationServerConfig locationServerConfig;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
log.info("locationServerConfig:{}",locationServerConfig); | package cn.lank8s.springboot.listener;
@Component
@Slf4j
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
LocationServerConfig locationServerConfig;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
log.info("locationServerConfig:{}",locationServerConfig); | ThreadHelper.executorService.execute(()->{ | 1 | 2023-12-09 15:30:38+00:00 | 2k |
Erdi-Topuzlu/RentACar_Tobeto_Project | src/main/java/com/tobeto/RentACar/controllers/ModelsController.java | [
{
"identifier": "ModelService",
"path": "src/main/java/com/tobeto/RentACar/services/abstracts/ModelService.java",
"snippet": "public interface ModelService {\n void add(AddModelRequest request);\n void update(UpdateModelRequest request);\n\n DeleteModelRequest delete(int id);\n\n List<GetAllModelResponse>getAll();\n\n GetByIdModelResponse getById(int id);\n\n boolean existsById (int id);\n}"
},
{
"identifier": "AddModelRequest",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/requests/model/AddModelRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AddModelRequest {\n\n @NotBlank(message = Messages.modelNameNotEmpty)\n @Size(min = 2, message = Messages.modelNameSize)\n private String name;\n\n @NotNull(message = Messages.brandIdNotEmpty)\n @Positive(message = Messages.brandIdPositive)\n private int brandId;\n}"
},
{
"identifier": "DeleteModelRequest",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/requests/model/DeleteModelRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class DeleteModelRequest {\n private int id;\n}"
},
{
"identifier": "UpdateModelRequest",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/requests/model/UpdateModelRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UpdateModelRequest {\n private int id;\n\n @NotBlank(message = Messages.modelNameNotEmpty)\n @Size(min = 2, message = Messages.modelNameSize)\n private String name;\n\n @NotNull(message = Messages.brandIdNotEmpty)\n @Positive(message = Messages.brandIdPositive)\n private int brandId;\n}"
},
{
"identifier": "GetAllModelResponse",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/responses/model/GetAllModelResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetAllModelResponse {\n private String name;\n private String brandName;\n}"
},
{
"identifier": "GetByIdModelResponse",
"path": "src/main/java/com/tobeto/RentACar/services/dtos/responses/model/GetByIdModelResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetByIdModelResponse{\n private String name;\n private String brandName;\n}"
}
] | import com.tobeto.RentACar.services.abstracts.ModelService;
import com.tobeto.RentACar.services.dtos.requests.model.AddModelRequest;
import com.tobeto.RentACar.services.dtos.requests.model.DeleteModelRequest;
import com.tobeto.RentACar.services.dtos.requests.model.UpdateModelRequest;
import com.tobeto.RentACar.services.dtos.responses.model.GetAllModelResponse;
import com.tobeto.RentACar.services.dtos.responses.model.GetByIdModelResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 740 | package com.tobeto.RentACar.controllers;
@RestController
@RequestMapping("api/v1/models")
@AllArgsConstructor
public class ModelsController {
private final ModelService modelService;
@GetMapping
public List<GetAllModelResponse>getAll(){
return modelService.getAll();
}
@GetMapping("/{id}")
public GetByIdModelResponse getById(@PathVariable int id){
return modelService.getById(id);
}
@DeleteMapping("/{id}") | package com.tobeto.RentACar.controllers;
@RestController
@RequestMapping("api/v1/models")
@AllArgsConstructor
public class ModelsController {
private final ModelService modelService;
@GetMapping
public List<GetAllModelResponse>getAll(){
return modelService.getAll();
}
@GetMapping("/{id}")
public GetByIdModelResponse getById(@PathVariable int id){
return modelService.getById(id);
}
@DeleteMapping("/{id}") | public DeleteModelRequest delete(@PathVariable int id){ | 2 | 2023-12-11 08:33:34+00:00 | 2k |
Khoshimjonov/SalahTimes | src/main/java/uz/khoshimjonov/api/Api.java | [
{
"identifier": "NominatimResponse",
"path": "src/main/java/uz/khoshimjonov/dto/NominatimResponse.java",
"snippet": "public class NominatimResponse implements Serializable {\n @SerializedName(\"place_id\")\n @Expose\n private Integer placeId;\n @SerializedName(\"licence\")\n @Expose\n private String licence;\n @SerializedName(\"osm_type\")\n @Expose\n private String osmType;\n @SerializedName(\"osm_id\")\n @Expose\n private Integer osmId;\n @SerializedName(\"lat\")\n @Expose\n private String lat;\n @SerializedName(\"lon\")\n @Expose\n private String lon;\n @SerializedName(\"class\")\n @Expose\n private String _class;\n @SerializedName(\"type\")\n @Expose\n private String type;\n @SerializedName(\"place_rank\")\n @Expose\n private Integer placeRank;\n @SerializedName(\"importance\")\n @Expose\n private Float importance;\n @SerializedName(\"addresstype\")\n @Expose\n private String addressType;\n @SerializedName(\"name\")\n @Expose\n private String name;\n @SerializedName(\"display_name\")\n @Expose\n private String displayName;\n @SerializedName(\"boundingbox\")\n @Expose\n private List<String> boundingBox;\n @Serial\n private final static long serialVersionUID = 6484686324938436909L;\n\n public Integer getPlaceId() {\n return placeId;\n }\n\n public void setPlaceId(Integer placeId) {\n this.placeId = placeId;\n }\n\n public String getLicence() {\n return licence;\n }\n\n public void setLicence(String licence) {\n this.licence = licence;\n }\n\n public String getOsmType() {\n return osmType;\n }\n\n public void setOsmType(String osmType) {\n this.osmType = osmType;\n }\n\n public Integer getOsmId() {\n return osmId;\n }\n\n public void setOsmId(Integer osmId) {\n this.osmId = osmId;\n }\n\n public String getLat() {\n return lat;\n }\n\n public void setLat(String lat) {\n this.lat = lat;\n }\n\n public String getLon() {\n return lon;\n }\n\n public void setLon(String lon) {\n this.lon = lon;\n }\n\n public String getClass_() {\n return _class;\n }\n\n public void setClass_(String _class) {\n this._class = _class;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public Integer getPlaceRank() {\n return placeRank;\n }\n\n public void setPlaceRank(Integer placeRank) {\n this.placeRank = placeRank;\n }\n\n public Float getImportance() {\n return importance;\n }\n\n public void setImportance(Float importance) {\n this.importance = importance;\n }\n\n public String getAddressType() {\n return addressType;\n }\n\n public void setAddressType(String addressType) {\n this.addressType = addressType;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public void setDisplayName(String displayName) {\n this.displayName = displayName;\n }\n\n public List<String> getBoundingBox() {\n return boundingBox;\n }\n\n public void setBoundingBox(List<String> boundingBox) {\n this.boundingBox = boundingBox;\n }\n\n}"
},
{
"identifier": "PrayerTimesResponse",
"path": "src/main/java/uz/khoshimjonov/dto/PrayerTimesResponse.java",
"snippet": "public class PrayerTimesResponse {\n @SerializedName(\"data\")\n @Expose\n private Data data;\n\n public Data getData() {\n return data;\n }\n\n}"
}
] | import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import uz.khoshimjonov.dto.NominatimResponse;
import uz.khoshimjonov.dto.PrayerTimesResponse;
import javax.net.ssl.*;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.List; | 1,222 | package uz.khoshimjonov.api;
public class Api {
private static final String AL_ADHAN_URL = "https://api.aladhan.com/v1/timings/%s?school=%s&method=%s&latitude=%s&longitude=%s";
private static final String NOMINATIM_URL = "https://nominatim.openstreetmap.org/search?format=json&limit=1&q=%s";
private final Gson GSON = new Gson();
| package uz.khoshimjonov.api;
public class Api {
private static final String AL_ADHAN_URL = "https://api.aladhan.com/v1/timings/%s?school=%s&method=%s&latitude=%s&longitude=%s";
private static final String NOMINATIM_URL = "https://nominatim.openstreetmap.org/search?format=json&limit=1&q=%s";
private final Gson GSON = new Gson();
| public PrayerTimesResponse getSalahTimes(String timings, int school, int method, String latitude, String longitude) throws Exception { | 1 | 2023-12-07 13:40:16+00:00 | 2k |
ShardMC/arte | common/src/main/java/io/shardmc/arte/common/util/lambda/PackZipperCreator.java | [
{
"identifier": "PackZipper",
"path": "common/src/main/java/io/shardmc/arte/common/pack/zipper/PackZipper.java",
"snippet": "public abstract class PackZipper {\n\n protected final Path root;\n protected final Path output;\n\n protected final Path assets;\n protected final ArteLogger logger;\n\n protected Collection<BuiltPack> packs = new ArrayList<>();\n\n public PackZipper(ArteLogger logger, Path root, Path output) throws IOException {\n this.root = Files.createDirectories(root);\n this.output = Files.createDirectories(output);\n\n this.assets = Files.createDirectories(this.root.resolve(\"assets\"));\n this.logger = logger;\n }\n\n protected Context createContext() {\n return new Context(this.logger, this.root, this.output, \"pack.mcmeta\", \"pack.png\");\n }\n\n public void zip(FilterList list, boolean scramble, Consumer<BuiltPack> consumer) {\n this.logger.info(\"Pack zipper started re-zipping!\");\n Context context = this.createContext();\n this.zip(context);\n\n this.packs = context.zip(list, scramble, consumer);\n }\n\n public void clean() throws IOException {\n try (Stream<Path> stream = Files.list(this.output)) {\n stream.parallel().forEach(path -> {\n try {\n Files.delete(path);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n });\n }\n\n this.packs.clear();\n }\n\n public Collection<BuiltPack> getPacks() {\n return packs;\n }\n\n protected abstract void zip(Context context);\n\n public static class Context {\n\n protected final ArteLogger logger;\n\n protected final Path root;\n protected final Path output;\n\n protected final List<Namespace> groups = new ArrayList<>();\n protected final List<PackFile> defaults = new ArrayList<>();\n\n public Context(ArteLogger logger, Path root, Path output, String... defaults) {\n this.logger = logger;\n\n this.root = root;\n this.output = output;\n\n for (String path : defaults) {\n this.defaults.add(new BasicPackFile(root.resolve(path)));\n }\n }\n\n public Context addNamespace(String name, Collection<Path> files) {\n this.groups.add(new Namespace(name, files));\n return this;\n }\n\n public Collection<BuiltPack> zip(FilterList list, boolean scramble, Consumer<BuiltPack> consumer) {\n List<BuiltPack> packs = new ArrayList<>();\n ThreadPool pool = new ThreadPool(this.logger);\n\n for (Namespace group : this.groups) {\n pool.add(() -> {\n try {\n Path generated = this.output.resolve(group.name() + \".zip\");\n try (Zip zip = new Zip(this.root, generated, scramble)) {\n group.zip(zip);\n\n for (PackFile file : this.defaults) {\n file.zip(zip);\n }\n }\n\n boolean force = !(list.elements().contains(\n group.name())\n ) && list.whitelist();\n\n BuiltPack pack = new BuiltPack(generated, force);\n\n consumer.accept(pack);\n packs.add(pack);\n } catch (IOException | ExecutionException | InterruptedException e) {\n this.logger.throwing(e, \"Failed to zip pack part: '\" + group + \"'\");\n }\n });\n }\n\n pool.start();\n return packs;\n }\n }\n}"
},
{
"identifier": "Arte",
"path": "common/src/main/java/io/shardmc/arte/common/Arte.java",
"snippet": "public interface Arte {\n ArteLogger logger();\n ArteConfig config();\n PackManager getPackManager();\n\n File getDataFolder();\n File getConfigFile();\n\n URL getResourceUrl(String path) throws IOException;\n\n default InputStream getResourceStream(String path) throws IOException {\n return this.getResourceUrl(path).openStream();\n }\n\n default File getResourceFile(String path) throws IOException {\n return new File(this.getResourceUrl(path).getFile());\n }\n}"
}
] | import io.shardmc.arte.common.pack.zipper.PackZipper;
import io.shardmc.arte.common.Arte;
import java.io.IOException;
import java.nio.file.Path; | 1,015 | package io.shardmc.arte.common.util.lambda;
@FunctionalInterface
public interface PackZipperCreator { | package io.shardmc.arte.common.util.lambda;
@FunctionalInterface
public interface PackZipperCreator { | PackZipper create(Arte arte, Path root, Path output) throws IOException; | 1 | 2023-12-09 10:58:32+00:00 | 2k |
nurseld/RentACar | pair2/src/main/java/com/tobeto/pair2/controllers/CarsController.java | [
{
"identifier": "CarService",
"path": "pair2/src/main/java/com/tobeto/pair2/services/abstracts/CarService.java",
"snippet": "public interface CarService {\n void add(AddCarRequest request);\n void update(UpdateCarRequest request);\n void delete(Integer id);\n List<GetAllCarResponse> getAll();\n GetByIdCarResponse getById(int id);\n boolean existsByCarId(int carId);\n}"
},
{
"identifier": "AddCarRequest",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/requests/AddCarRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class AddCarRequest {\n\n @Positive(message = \"Kilometer should be a greater than 0.\")\n private int kilometer;\n\n @NotBlank(message = \"Plate number !\")\n @Pattern(regexp = \"^(0[1-9]|[1-7][0-9]|8[01])(([A-Z])(\\\\d{4,5})|([A-Z]{2})(\\\\d{3,4})|([A-Z]{3})(\\\\d{2,3}))$\", message = \" Plate should be a valid Turkish plate format.\")\n private String plate;\n\n public void setPlate(String plate) {\n this.plate = plate != null ? plate.replaceAll(\"\\s\", \"\") : null;\n }\n\n @Min(value = 2005, message = \"Year should be 2005 or greater.\")\n @Max(value = 2024, message = \"Year should be 2024 or less.\")\n private int year;\n\n @Positive(message = \"Daily price should be a greater than 0.\")\n private double dailyPrice;\n\n @Positive(message = \"ModelId should be a greater than 0.\")\n private int modelId;\n\n @Positive(message = \"ColorId should be a greater than 0.\")\n private int colorId;\n\n}"
},
{
"identifier": "UpdateCarRequest",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/requests/UpdateCarRequest.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class UpdateCarRequest {\n\n @Positive(message = \"Doğru id girişi yapınız\")\n private Integer id;\n\n @Positive(message = \"Kilometer should be a greater than 0.\")\n private int kilometer;\n\n @NotBlank(message = \"The plate cannot be empty!\")\n @Pattern(regexp = \"^(0[1-9]|[1-7][0-9]|8[01])(([A-Z])(\\\\d{4,5})|([A-Z]{2})(\\\\d{3,4})|([A-Z]{3})(\\\\d{2,3}))$\", message = \" Plate should be a valid Turkish plate format.\")\n private String plate;\n\n public void setPlate(String plate) {\n this.plate = plate != null ? plate.replaceAll(\"\\s\", \"\") : null;\n }\n\n @Min(value = 2005, message = \"Year should be 2005 or greater.\")\n @Max(value = 2024, message = \"Year should be 2024 or less.\")\n private int year;\n\n @Positive(message = \"Daily price should be a greater than 0.\")\n private double dailyPrice;\n\n @Positive(message = \"Kilometer should be a greater than 0.\")\n private int modelId;\n\n @Positive(message = \"ColorId should be a greater than 0.\")\n private int colorId;\n}"
},
{
"identifier": "GetAllCarResponse",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/responses/GetAllCarResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetAllCarResponse {\n\n private int kilometer;\n\n private String plate;\n\n private int year;\n\n private double dailyPrice;\n\n private String modelName;\n\n private String colorName;\n\n}"
},
{
"identifier": "GetByIdCarResponse",
"path": "pair2/src/main/java/com/tobeto/pair2/services/dtos/car/responses/GetByIdCarResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class GetByIdCarResponse {\n\n private int kilometer;\n\n private String plate;\n\n private int year;\n\n private double dailyPrice;\n\n private String modelName;\n\n private String colorName;\n}"
}
] | import com.tobeto.pair2.services.abstracts.CarService;
import com.tobeto.pair2.services.dtos.car.requests.AddCarRequest;
import com.tobeto.pair2.services.dtos.car.requests.UpdateCarRequest;
import com.tobeto.pair2.services.dtos.car.responses.GetAllCarResponse;
import com.tobeto.pair2.services.dtos.car.responses.GetByIdCarResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 1,265 | package com.tobeto.pair2.controllers;
@RestController
@RequestMapping("/api/cars")
@AllArgsConstructor
public class CarsController {
private final CarService carService;
@PostMapping("/add")
public void add(@RequestBody @Valid AddCarRequest request) {
carService.add(request);
}
@PutMapping("/update")
public void update(@RequestBody @Valid UpdateCarRequest request) {
carService.update(request);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Integer id) {
carService.delete(id);
}
@GetMapping("/getAll")
public List<GetAllCarResponse> getAll() {
return carService.getAll();
}
@GetMapping("/getById/{id}") | package com.tobeto.pair2.controllers;
@RestController
@RequestMapping("/api/cars")
@AllArgsConstructor
public class CarsController {
private final CarService carService;
@PostMapping("/add")
public void add(@RequestBody @Valid AddCarRequest request) {
carService.add(request);
}
@PutMapping("/update")
public void update(@RequestBody @Valid UpdateCarRequest request) {
carService.update(request);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Integer id) {
carService.delete(id);
}
@GetMapping("/getAll")
public List<GetAllCarResponse> getAll() {
return carService.getAll();
}
@GetMapping("/getById/{id}") | public GetByIdCarResponse getById(@PathVariable int id) { | 4 | 2023-12-11 12:26:27+00:00 | 2k |
atagunay/knapsack | src/genetic/GeneticAlgorithm.java | [
{
"identifier": "KSFactory",
"path": "src/knapsack/KSFactory.java",
"snippet": "public class KSFactory implements GeneticAlgorithmFactory {\n /**\n * @return the KSInitialPopulation class specifically for knapsack problem\n */\n @Override\n public InitialPopulation createInitialPopulation() {\n return new KSInitialPopulation();\n }\n\n /**\n * @return KSFitnessCalculation class specifically for knapsack problem\n */\n @Override\n public FitnessCalculation createFitnessCalculation() {\n return new KSFitnessCalculation();\n }\n\n /**\n * @return the KSNextGeneration class specifically for knapsack problem\n */\n @Override\n public NextGeneration createNextGeneration() {\n return new KSNextGeneration();\n }\n\n /**\n * @return the KSResultDetection class specifically for knapsack problem\n */\n @Override\n public ResultDetection createResultDetection() {\n return new KSResultDetection();\n }\n}"
},
{
"identifier": "Complete",
"path": "src/state/Complete.java",
"snippet": "public class Complete implements State {\n GeneticAlgorithm geneticAlgorithm;\n\n /**\n * Constructor\n *\n * @param geneticAlgorithm the instance of GeneticAlgorithm for calling set and get state methods\n */\n public Complete(GeneticAlgorithm geneticAlgorithm) {\n this.geneticAlgorithm = geneticAlgorithm;\n }\n\n /**\n * Complete state to idle state\n */\n @Override\n public void nextStep() {\n geneticAlgorithm.setState(geneticAlgorithm.getIdleState());\n System.out.println(\"Complete -> Idle\");\n }\n}"
},
{
"identifier": "Idle",
"path": "src/state/Idle.java",
"snippet": "public class Idle implements State {\n private final GeneticAlgorithm geneticAlgorithm;\n private final GeneticAlgorithmManager geneticAlgorithmManager;\n\n /**\n * constructor\n *\n * @param geneticAlgorithm the instance of GeneticAlgorithm for calling set and get state methods\n */\n public Idle(GeneticAlgorithm geneticAlgorithm) {\n this.geneticAlgorithm = geneticAlgorithm;\n this.geneticAlgorithmManager = GeneticAlgorithmManager.getInstance(geneticAlgorithm.getFactoryKey());\n }\n\n /**\n * idle state to Complete state,\n * run genetic algorithm\n */\n @Override\n public void nextStep() {\n geneticAlgorithmManager.runGeneticAlgorithm();\n geneticAlgorithm.setState(geneticAlgorithm.getCompleteState());\n System.out.println(\"Idle -> Complete\");\n }\n}"
},
{
"identifier": "State",
"path": "src/state/State.java",
"snippet": "public interface State {\n /**\n * Move to the next state\n */\n void nextStep();\n}"
}
] | import knapsack.KSFactory;
import state.Complete;
import state.Idle;
import state.State;
import java.util.Map; | 687 | package genetic;
/**
* state machine
*/
public class GeneticAlgorithm {
private State state;
final private State idleState;
final private State completeState;
public static Map<String, GeneticAlgorithmFactory> factoryHashMap = Map.of( | package genetic;
/**
* state machine
*/
public class GeneticAlgorithm {
private State state;
final private State idleState;
final private State completeState;
public static Map<String, GeneticAlgorithmFactory> factoryHashMap = Map.of( | "knapsack", new KSFactory() | 0 | 2023-12-06 12:57:21+00:00 | 2k |
crystal-processes/crp-flowable-springboot-sample | src/main/java/org/crp/flowable/springboot/sample/AcmeAppConfiguration.java | [
{
"identifier": "ContractService",
"path": "src/main/java/org/crp/flowable/springboot/sample/services/ContractService.java",
"snippet": "public interface ContractService {\n\n /**\n * Get contract by Id.\n *\n * @param contractId contract identifier to get.\n * @return contract\n * @throws RuntimeException when contract is not found\n */\n @RuntimeUsage(\"Used in the expressions to get contract by `id`\")\n JsonNode getContract(String contractId);\n}"
},
{
"identifier": "MoneyService",
"path": "src/main/java/org/crp/flowable/springboot/sample/services/MoneyService.java",
"snippet": "public interface MoneyService {\n /**\n * Send @amount of money to @account\n *\n * @param account account to send money to.\n * @param amount amount of money to send.\n * @throws RuntimeException in case of any trouble.\n */\n @RuntimeUsage(\"Used in service task expressions.\")\n void sendMoney(String account, int amount);\n}"
},
{
"identifier": "ReportService",
"path": "src/main/java/org/crp/flowable/springboot/sample/services/ReportService.java",
"snippet": "public interface ReportService {\n\n /**\n * Create a report with:\n * | account | Amount sent |\n * |---------|-------------|\n * @return [ { \"account\": ___, \"amount\": ___}]\n */\n ArrayNode accountAmountReport();\n}"
},
{
"identifier": "DefaultContractService",
"path": "src/main/java/org/crp/flowable/springboot/sample/services/impl/DefaultContractService.java",
"snippet": "public class DefaultContractService implements ContractService {\n\n @Autowired\n private ObjectMapper objectMapper;\n\n @Override\n public JsonNode getContract(String contractId) {\n try {\n return objectMapper.readTree(\"\"\"\n {\n \"account\" : { \"owner\" : \"jlong\", \"id\":\"ABCD-123456789\" },\n \"maxAmount\": 10000\n }\"\"\");\n } catch (JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}"
},
{
"identifier": "DefaultMoneyService",
"path": "src/main/java/org/crp/flowable/springboot/sample/services/impl/DefaultMoneyService.java",
"snippet": "public class DefaultMoneyService implements MoneyService {\n\n private static final Logger LOG = LoggerFactory.getLogger(DefaultMoneyService.class);\n\n @Override\n public void sendMoney(String account, int amount) {\n LOG.info(\"Money send to ${} -> {}.\", amount, account);\n }\n}"
},
{
"identifier": "DefaultReportService",
"path": "src/main/java/org/crp/flowable/springboot/sample/services/impl/DefaultReportService.java",
"snippet": "public class DefaultReportService implements ReportService {\n\n @Autowired\n HistoryService historyService;\n @Autowired\n ObjectMapper objectMapper;\n\n @Override\n public ArrayNode accountAmountReport() {\n return getAllProcessInstances().stream().map(\n mapDataToJsonObject()\n ).collect(\n arrayNodeCollector()\n );\n }\n\n private Collector<ObjectNode, ArrayNode, ArrayNode> arrayNodeCollector() {\n return Collector.of(\n () -> objectMapper.createArrayNode(),\n ArrayNode::add,\n ArrayNode::addAll\n );\n }\n\n private Function<HistoricProcessInstance, ObjectNode> mapDataToJsonObject() {\n return process -> {\n Object contract = process.getProcessVariables().get(\"contract\");\n ObjectNode objectNode = objectMapper.createObjectNode();\n if (contract instanceof JsonNode jsonContract) {\n if (jsonContract.has(\"account\")) {\n JsonNode account = jsonContract.get(\"account\");\n if (account.has(\"id\")) {\n // version 0.2.3\n objectNode.put(\"account\", account.get(\"id\").asText());\n } else {\n // version 0.2.2\n objectNode.put(\"account\", account.asText());\n }\n } else {\n throw new RuntimeException(\"Unexpected json contract format in process \" + process.getId());\n }\n } else if (contract instanceof Contract javaSerializationContract) {\n // version 0.2.1 (version 0.2.0 java serialization was omitted).\n objectNode.put(\"account\", javaSerializationContract.getAccount().getId());\n } else if (contract instanceof String stringContract) {\n objectNode.put(\"account\", stringContract);\n } else {\n throw new RuntimeException(\"Unexpected contract format in process \"+process.getId());\n }\n objectNode.put(\"amount\", getAmount(process));\n return objectNode;\n };\n }\n\n private static Integer getAmount(HistoricProcessInstance process) {\n Object amount = process.getProcessVariables().get(\"amount\");\n return amount == null ? 0 : (Integer) amount;\n }\n\n private List<HistoricProcessInstance> getAllProcessInstances() {\n return historyService.createHistoricProcessInstanceQuery().processDefinitionKey(\"P002-processInsuranceEvent\")\n .includeProcessVariables().orderByProcessInstanceStartTime().asc().list();\n }\n}"
}
] | import org.crp.flowable.springboot.sample.services.ContractService;
import org.crp.flowable.springboot.sample.services.MoneyService;
import org.crp.flowable.springboot.sample.services.ReportService;
import org.crp.flowable.springboot.sample.services.impl.DefaultContractService;
import org.crp.flowable.springboot.sample.services.impl.DefaultMoneyService;
import org.crp.flowable.springboot.sample.services.impl.DefaultReportService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; | 1,311 | package org.crp.flowable.springboot.sample;
@Configuration
public class AcmeAppConfiguration {
@Bean
ContractService contractService() {
return new DefaultContractService();
}
@Bean
MoneyService moneyService() {
return new DefaultMoneyService();
}
@Bean
ReportService reportService() { | package org.crp.flowable.springboot.sample;
@Configuration
public class AcmeAppConfiguration {
@Bean
ContractService contractService() {
return new DefaultContractService();
}
@Bean
MoneyService moneyService() {
return new DefaultMoneyService();
}
@Bean
ReportService reportService() { | return new DefaultReportService(); | 5 | 2023-12-05 17:02:14+00:00 | 2k |
iBranch211/spring-boot-jwt-and-otp-auth | src/main/java/com/jwtauth/controller/AuthController.java | [
{
"identifier": "JwtResponse",
"path": "src/main/java/com/jwtauth/dto/JwtResponse.java",
"snippet": "public class JwtResponse implements Serializable {\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 744689680486730629L;\n\n\tString jwt;\n\n\tpublic JwtResponse(String jwt) {\n\t\tthis.jwt = jwt;\n\t}\n\n\tpublic String getJwt() {\n\t\treturn jwt;\n\t}\n\n\tpublic void setJwt(String jwt) {\n\t\tthis.jwt = jwt;\n\t}\n\n}"
},
{
"identifier": "JwtResponse2",
"path": "src/main/java/com/jwtauth/dto/JwtResponse2.java",
"snippet": "@Builder\n@Data\npublic class JwtResponse2 implements Serializable {\n\tprivate static final long serialVersionUID = 744689680486730629L;\n\n\tprivate String jwt;\n\tprivate String id;\n\tprivate String username;\n\tprivate String firstName;\n\tprivate String lastName;\n\tprivate List<String> roles;\n\n}"
},
{
"identifier": "LoginDTO",
"path": "src/main/java/com/jwtauth/dto/LoginDTO.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LoginDTO {\n\n\tprivate String username;\n\n\tprivate String password;\n\n}"
},
{
"identifier": "UserPrincipal",
"path": "src/main/java/com/jwtauth/dto/UserPrincipal.java",
"snippet": "public class UserPrincipal implements UserDetails {\n\n private static final long serialVersionUID = 1L;\n private String username;\n private String password;\n private boolean enabled;\n private Collection<? extends GrantedAuthority> authorities;\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return authorities;\n }\n @Override\n public String getPassword() {\n return password;\n }\n @Override\n public String getUsername() {\n return username;\n }\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n @Override\n public boolean isEnabled() {\n return enabled;\n }\n public void setUsername(String username) {\n this.username = username;\n }\n public void setPassword(String password) {\n this.password = password;\n }\n public void setEnabled(boolean enabled) {\n this.enabled = enabled;\n }\n public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {\n this.authorities = authorities;\n }\n}"
},
{
"identifier": "JwtProvider",
"path": "src/main/java/com/jwtauth/jwt/JwtProvider.java",
"snippet": "@Component\npublic class JwtProvider {\n\n\tSecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512);\n\n\t@Value(\"${app.jwtExpirationInMs}\")\n\tprivate int jwtExpirationInMs;\n\n\tpublic String generateToken(Authentication authentication) {\n\t\tUserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();\n\t\tDate now = new Date();\n\t\tDate expiryDate = new Date(now.getTime() + jwtExpirationInMs);\n\n\t\treturn Jwts.builder().setSubject(userPrincipal.getUsername()).setIssuedAt(new Date()).setExpiration(expiryDate)\n\t\t\t\t.signWith(key).compact();\n\t}\n\n\tpublic String getUserUsernameFromJWT(String token) {\n\t\tClaims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();\n\t\treturn claims.getSubject();\n\t}\n\n\tpublic boolean validateToken(String authToken) {\n\t\ttry {\n\t\t\tJwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken);\n\t\t\treturn true;\n\t\t} catch (SignatureException | MalformedJwtException | ExpiredJwtException | UnsupportedJwtException\n\t\t\t\t| IllegalArgumentException ex) {\n\n\t\t}\n\t\treturn false;\n\t}\n}"
},
{
"identifier": "OTPMailService",
"path": "src/main/java/com/jwtauth/service/OTPMailService.java",
"snippet": "@Service\npublic class OTPMailService {\n\n\t@Autowired\n\tMailService mailService;\n\n\t@Autowired\n\tprivate OTPService otpService;\n\n\tpublic boolean sendOTPToEmail(@NotNull String userMail) {\n\t\tfinal Context ctx = new Context();\n\t\tctx.setVariable(\"name\", userMail.split(\"@\")[0]);\n\t\tctx.setVariable(\"otp\", otpService.generateOTPForUser(userMail).getUserOTP());\n\n\t\treturn mailService.sendHTMLMail(ctx, \"otp-mail\", userMail, \"Your OTP\");\n\n\t}\n\n\tpublic boolean validateMailOTP(@NotNull LoginDTO loginDTO) {\n\t\ttry {\n\t\t\treturn otpService.validateOTP(loginDTO.getUsername(), Integer.valueOf(loginDTO.getPassword()));\n\t\t} catch (RuntimeException e) {\n\t\t\treturn false;\n\t\t}\n\n\t}\n}"
}
] | import java.util.Arrays;
import java.util.stream.Collectors;
import javax.mail.MessagingException;
import javax.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.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
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 com.jwtauth.dto.JwtResponse;
import com.jwtauth.dto.JwtResponse2;
import com.jwtauth.dto.LoginDTO;
import com.jwtauth.dto.UserPrincipal;
import com.jwtauth.jwt.JwtProvider;
import com.jwtauth.service.OTPMailService;
import lombok.extern.log4j.Log4j2; | 1,375 | package com.jwtauth.controller;
@RestController
@RequestMapping("/auth")
@Log4j2
@CrossOrigin
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired | package com.jwtauth.controller;
@RestController
@RequestMapping("/auth")
@Log4j2
@CrossOrigin
public class AuthController {
@Autowired
AuthenticationManager authenticationManager;
@Autowired | JwtProvider tokenProvider; | 4 | 2023-12-13 04:28:37+00:00 | 2k |
AdamBien/detonator | detonator/src/main/java/airhacks/App.java | [
{
"identifier": "CloudFormationStacks",
"path": "detonator/src/main/java/airhacks/detonator/cloudformation/boundary/CloudFormationStacks.java",
"snippet": "public interface CloudFormationStacks {\n\n static void removeAllStacks() {\n\n try (var client = CloudFormationClient.create()) {\n\n var request = ListStacksRequest\n .builder()\n .stackStatusFilters(StackStatus.CREATE_COMPLETE, StackStatus.UPDATE_COMPLETE)\n .build();\n var listStacksResponse = client.listStacks(request);\n listStacksResponse\n .stackSummaries()\n .stream()\n .filter(CloudFormationStacks::notCDK)\n .forEach(summary -> deleteStack(client, summary));\n\n }\n }\n\n private static void deleteStack(CloudFormationClient client, StackSummary stackSummary) {\n var stackName = stackSummary.stackName();\n var deleteRequest = DeleteStackRequest\n .builder()\n .stackName(stackName)\n .build();\n if (Dialog.proceed(stackName)) {\n Logger.info(\"deleting stack:\");\n info(stackSummary);\n client.deleteStack(deleteRequest);\n }else{\n Logger.info(\"skipping\");\n }\n\n }\n\n private static boolean notCDK(StackSummary summary) {\n var stackName = summary.stackName();\n return !stackName.equalsIgnoreCase(\"CDKToolkit\");\n }\n\n private static void info(StackSummary summary) {\n var message = \"created: %s, updated: %s, name: \".formatted(summary.creationTime(),\n summary.lastUpdatedTime(), summary.stackName());\n Logger.info(message);\n }\n}"
},
{
"identifier": "LogGroups",
"path": "detonator/src/main/java/airhacks/detonator/cloudwatch/boundary/LogGroups.java",
"snippet": "public interface LogGroups {\n\n static void removeAllLogGroups() {\n try (var client = CloudWatchLogsClient.create()) {\n client\n .describeLogGroupsPaginator()\n .stream()\n .flatMap(response -> response.logGroups().stream())\n .map(LogGroup::logGroupName)\n .forEach(groupName -> LogGroups.delete(client, groupName));\n\n }\n }\n\n static void delete(CloudWatchLogsClient client, String logGroupName) {\n var deleteRequest = DeleteLogGroupRequest.builder()\n .logGroupName(logGroupName)\n .build();\n if (Dialog.proceed(logGroupName)) {\n Logger.info(\"deleting log group:\");\n Logger.info(logGroupName);\n client.deleteLogGroup(deleteRequest);\n Logger.info(\"deleted\");\n }else{\n Logger.info(\"skipping\");\n }\n }\n}"
},
{
"identifier": "Dialog",
"path": "detonator/src/main/java/airhacks/detonator/dialog/control/Dialog.java",
"snippet": "public interface Dialog {\n\n static boolean proceed(String stackName) {\n var line = System\n .console()\n .readLine(\"delete %s [Y/y]?: \".formatted(stackName));\n return line.equalsIgnoreCase(\"y\");\n }\n\n static boolean ask(String question) {\n var line = System\n .console()\n .readLine(\"%s [Y/y]?: \".formatted(question));\n return line.equalsIgnoreCase(\"y\");\n } \n \n}"
},
{
"identifier": "Logger",
"path": "detonator/src/main/java/airhacks/detonator/log/boundary/Logger.java",
"snippet": "public interface Logger {\n\n public enum TerminalColors {\n \n INFO(\"\\u001B[34m\"), TIME(\"\\033[1;90m\"), RESET(\"\\u001B[0m\");\n \n private final String value;\n \n \n private TerminalColors(String value) {\n this.value = value;\n }\n \n public String value() {\n return this.value;\n }\n \n }\n\n static void info(String info) {\n System.out.println(info);\n }\n\n static void white(String info) {\n System.out.println(info);\n }\n \n}"
}
] | import airhacks.detonator.cloudformation.boundary.CloudFormationStacks;
import airhacks.detonator.cloudwatch.boundary.LogGroups;
import airhacks.detonator.dialog.control.Dialog;
import airhacks.detonator.log.boundary.Logger;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.services.sts.StsClient; | 1,136 | package airhacks;
/**
*
* @author airhacks.com
*/
interface App {
String version = "detonator: v0.0.6, 19.12.2023";
static void main(String... args) {
Logger.info(version);
//current accessKey
var credentialsProvider = DefaultCredentialsProvider.builder().build();
var accessKey = credentialsProvider.resolveCredentials().accessKeyId();
Logger.info(accessKey);
//who am I?
var stsClient = StsClient.create();
var response = stsClient.getCallerIdentity();
var arn = response.arn();
Logger.info(arn); | package airhacks;
/**
*
* @author airhacks.com
*/
interface App {
String version = "detonator: v0.0.6, 19.12.2023";
static void main(String... args) {
Logger.info(version);
//current accessKey
var credentialsProvider = DefaultCredentialsProvider.builder().build();
var accessKey = credentialsProvider.resolveCredentials().accessKeyId();
Logger.info(accessKey);
//who am I?
var stsClient = StsClient.create();
var response = stsClient.getCallerIdentity();
var arn = response.arn();
Logger.info(arn); | CloudFormationStacks.removeAllStacks(); | 0 | 2023-12-08 09:37:13+00:00 | 2k |
fabriciofx/cactoos-pdf | src/main/java/com/github/fabriciofx/cactoos/pdf/image/png/PngHeader.java | [
{
"identifier": "BytesAsInteger",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/BytesAsInteger.java",
"snippet": "public final class BytesAsInteger implements Scalar<Integer> {\n /**\n * Bytes.\n */\n private final Bytes bytes;\n\n /**\n * Ctor.\n *\n * @param bytes An array of bytes that represents an integer\n */\n public BytesAsInteger(final byte[] bytes) {\n this(() -> bytes);\n }\n\n /**\n * Ctor.\n *\n * @param bytes Bytes that represents an integer\n */\n public BytesAsInteger(final Bytes bytes) {\n this.bytes = bytes;\n }\n\n @Override\n public Integer value() throws Exception {\n final byte[] octets = this.bytes.asBytes();\n return ((octets[0] & 0xFF) << 24)\n | ((octets[1] & 0xFF) << 16)\n | ((octets[2] & 0xFF) << 8)\n | (octets[3] & 0xFF);\n }\n}"
},
{
"identifier": "Header",
"path": "src/main/java/com/github/fabriciofx/cactoos/pdf/image/Header.java",
"snippet": "public interface Header extends Text, Bytes {\n /**\n * Length.\n *\n * @return The length\n * @throws Exception if fails\n */\n int length() throws Exception;\n\n /**\n * Width.\n * @return Image width\n * @throws Exception if fails\n */\n int width() throws Exception;\n\n /**\n * Height.\n *\n * @return Image height\n * @throws Exception if fails\n */\n int height() throws Exception;\n\n /**\n * Bit Depth.\n *\n * @return Amount of image bit depth\n * @throws Exception if fails\n */\n int depth() throws Exception;\n\n /**\n * Color space.\n *\n * @return Color type and space\n * @throws Exception if fails\n */\n Color color() throws Exception;\n\n /**\n * Image compression level.\n *\n * @return Image compression level\n * @throws Exception if fails\n */\n int compression() throws Exception;\n\n /**\n * Image filter type.\n *\n * @return Image filter type\n * @throws Exception if fails\n */\n int filter() throws Exception;\n\n /**\n * Image interlacing.\n *\n * @return Image interlacing\n * @throws Exception if fails\n */\n int interlacing() throws Exception;\n}"
}
] | import com.github.fabriciofx.cactoos.pdf.image.BytesAsInteger;
import com.github.fabriciofx.cactoos.pdf.image.Header;
import java.util.Arrays;
import java.util.Locale;
import org.cactoos.Bytes;
import org.cactoos.text.FormattedText;
import org.cactoos.text.Joined; | 1,392 | /*
* The MIT License (MIT)
*
* Copyright (C) 2023-2024 Fabrício Barros Cabral
*
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.fabriciofx.cactoos.pdf.image.png;
/**
* PngHeader: PNG Image Header.
*
* @since 0.0.1
*
* PNG Image Header Structure:
* ----------------------------
*
* Offset Length Field Name Description
* ---------------------------------------------
* 0 8 bytes Signature PNG file signature (137 80 78 71 13 10 26
* 10)
* 8 4 bytes Chunk Length Length of the chunk data (excluding length
* and type)
* 12 4 bytes Chunk Type Type of the chunk (e.g., IHDR for image
* header)
* 16 4 bytes Width Width of the image in pixels
* 20 4 bytes Height Height of the image in pixels
* 24 1 byte Bit Depth Number of bits per sample
* 25 1 byte Color Type Type of color encoding used
* 26 1 byte Compression Compression method used
* 27 1 byte Filter Method Filtering method used
* 28 1 byte Interlace Method Interlace method used
*
* Additional chunks (not included in the header):
* - Data chunks (IDAT) containing the image data
* - Palette chunks (PLTE) for indexed-color images
* - Transparency chunks (tRNS) for specifying transparency
* - Textual information chunks (tEXt, iTXt) for metadata
* - Other optional chunks for various purposes
*/
public final class PngHeader implements Header {
/**
* PNG header bytes.
*/
private final Bytes bytes;
/**
* Ctor.
*
* @param bytes PNG header bytes
*/
public PngHeader(final Bytes bytes) {
this.bytes = bytes;
}
@Override
public int length() throws Exception { | /*
* The MIT License (MIT)
*
* Copyright (C) 2023-2024 Fabrício Barros Cabral
*
* 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 NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.fabriciofx.cactoos.pdf.image.png;
/**
* PngHeader: PNG Image Header.
*
* @since 0.0.1
*
* PNG Image Header Structure:
* ----------------------------
*
* Offset Length Field Name Description
* ---------------------------------------------
* 0 8 bytes Signature PNG file signature (137 80 78 71 13 10 26
* 10)
* 8 4 bytes Chunk Length Length of the chunk data (excluding length
* and type)
* 12 4 bytes Chunk Type Type of the chunk (e.g., IHDR for image
* header)
* 16 4 bytes Width Width of the image in pixels
* 20 4 bytes Height Height of the image in pixels
* 24 1 byte Bit Depth Number of bits per sample
* 25 1 byte Color Type Type of color encoding used
* 26 1 byte Compression Compression method used
* 27 1 byte Filter Method Filtering method used
* 28 1 byte Interlace Method Interlace method used
*
* Additional chunks (not included in the header):
* - Data chunks (IDAT) containing the image data
* - Palette chunks (PLTE) for indexed-color images
* - Transparency chunks (tRNS) for specifying transparency
* - Textual information chunks (tEXt, iTXt) for metadata
* - Other optional chunks for various purposes
*/
public final class PngHeader implements Header {
/**
* PNG header bytes.
*/
private final Bytes bytes;
/**
* Ctor.
*
* @param bytes PNG header bytes
*/
public PngHeader(final Bytes bytes) {
this.bytes = bytes;
}
@Override
public int length() throws Exception { | return new BytesAsInteger( | 0 | 2023-12-05 00:07:24+00:00 | 2k |
BeansGalaxy/Beans-Backpacks-2 | forge/src/main/java/com/beansgalaxy/backpacks/compat/JEIPlugin.java | [
{
"identifier": "Constants",
"path": "common/src/main/java/com/beansgalaxy/backpacks/Constants.java",
"snippet": "public class Constants {\n\n\tpublic static final String MOD_ID = \"beansbackpacks\";\n\tpublic static final String MOD_NAME = \"Beans' Backpacks\";\n\tpublic static final Logger LOG = LoggerFactory.getLogger(MOD_NAME);\n\n\tpublic static final HashMap<String, Traits> TRAITS_MAP = new HashMap<>();\n\tpublic static HashSet<Item> CHESTPLATE_DISABLED = new HashSet<>();\n\tpublic static HashSet<Item> DISABLES_BACK_SLOT = new HashSet<>();\n\n\tpublic static Item itemFromString(String string) {\n\t\tif (string == null)\n\t\t\treturn Items.AIR;\n\t\tString[] location = string.split(\":\");\n\t\tResourceLocation resourceLocation = new ResourceLocation(location[0], location[1]);\n return BuiltInRegistries.ITEM.get(resourceLocation);\n\t}\n\n\tpublic static void disableFromChestplate(String string) {\n\t\tItem item = itemFromString(string);\n\t\tCHESTPLATE_DISABLED.add(item.asItem());\n\t}\n\n\tpublic static ItemStack getTorsoWearables(Player player, Item item) {\n\t\tItemStack backSlot = BackSlot.get(player).getItem();\n\t\tItemStack chestplate = player.getItemBySlot(EquipmentSlot.CHEST);\n\t\treturn backSlot.is(item) ? backSlot : chestplate;\n\t}\n\n\tpublic static void disablesBackSlot(String string) {\n\t\tItem item = itemFromString(string);\n\t\tDISABLES_BACK_SLOT.add(item.asItem());\n\t}\n\n}"
},
{
"identifier": "Services",
"path": "common/src/main/java/com/beansgalaxy/backpacks/platform/Services.java",
"snippet": "public class Services {\n\n public static final NetworkHelper NETWORK = load(NetworkHelper.class);\n public static final RegistryHelper REGISTRY = load(RegistryHelper.class);\n\n public static <T> T load(Class<T> clazz) {\n\n final T loadedService = ServiceLoader.load(clazz)\n .findFirst()\n .orElseThrow(() -> new NullPointerException(\"Failed to load service for \" + clazz.getName()));\n Constants.LOG.debug(\"Loaded {} for service {}\", loadedService, clazz);\n return loadedService;\n }\n}"
}
] | import com.beansgalaxy.backpacks.Constants;
import com.beansgalaxy.backpacks.platform.Services;
import mezz.jei.api.IModPlugin;
import mezz.jei.api.JeiPlugin;
import mezz.jei.api.ingredients.subtypes.IIngredientSubtypeInterpreter;
import mezz.jei.api.registration.ISubtypeRegistration;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack; | 751 | package com.beansgalaxy.backpacks.compat;
@JeiPlugin
public class JEIPlugin implements IModPlugin {
@Override
public ResourceLocation getPluginUid() {
return new ResourceLocation(Constants.MOD_ID, "jei_plugin");
}
@Override
public void registerItemSubtypes(ISubtypeRegistration registration) {
IIngredientSubtypeInterpreter<ItemStack> interpreter = (stack, context) -> {
CompoundTag display = stack.getTagElement("display");
if (display == null)
return IIngredientSubtypeInterpreter.NONE;
String key = display.getString("key");
if (key.isEmpty())
return IIngredientSubtypeInterpreter.NONE;
return display.getAsString();
};
| package com.beansgalaxy.backpacks.compat;
@JeiPlugin
public class JEIPlugin implements IModPlugin {
@Override
public ResourceLocation getPluginUid() {
return new ResourceLocation(Constants.MOD_ID, "jei_plugin");
}
@Override
public void registerItemSubtypes(ISubtypeRegistration registration) {
IIngredientSubtypeInterpreter<ItemStack> interpreter = (stack, context) -> {
CompoundTag display = stack.getTagElement("display");
if (display == null)
return IIngredientSubtypeInterpreter.NONE;
String key = display.getString("key");
if (key.isEmpty())
return IIngredientSubtypeInterpreter.NONE;
return display.getAsString();
};
| registration.registerSubtypeInterpreter(Services.REGISTRY.getLeather(), interpreter); | 1 | 2023-12-14 21:55:00+00:00 | 2k |
CADIndie/Scout | src/main/java/pm/c7/scout/mixin/PlayerScreenHandlerMixin.java | [
{
"identifier": "Scout",
"path": "src/main/java/pm/c7/scout/Scout.java",
"snippet": "@SuppressWarnings(\"deprecation\")\npublic class Scout implements ModInitializer {\n public static final String MOD_ID = \"scout\";\n\n public static final int MAX_SATCHEL_SLOTS = 18;\n public static final int MAX_POUCH_SLOTS = 6;\n\n public static final ItemGroup ITEM_GROUP = FabricItemGroupBuilder.build(new Identifier(\"scout\", \"itemgroup\"), () -> new ItemStack(Scout.SATCHEL));\n\n public static final Item TANNED_LEATHER = new Item(new FabricItemSettings().group(ITEM_GROUP));\n public static final Item SATCHEL_STRAP = new Item(new FabricItemSettings().group(ITEM_GROUP));\n\n public static final BaseBagItem SATCHEL = new BaseBagItem(new FabricItemSettings().group(Scout.ITEM_GROUP).maxCount(1), MAX_SATCHEL_SLOTS / 2, BagType.SATCHEL);\n public static final BaseBagItem UPGRADED_SATCHEL = new BaseBagItem(new FabricItemSettings().group(Scout.ITEM_GROUP).maxCount(1).rarity(Rarity.RARE), MAX_SATCHEL_SLOTS, BagType.SATCHEL);\n public static final BaseBagItem POUCH = new BaseBagItem(new FabricItemSettings().group(Scout.ITEM_GROUP).maxCount(1), MAX_POUCH_SLOTS / 2, BagType.POUCH);\n public static final BaseBagItem UPGRADED_POUCH = new BaseBagItem(new FabricItemSettings().group(Scout.ITEM_GROUP).maxCount(1).rarity(Rarity.RARE), MAX_POUCH_SLOTS, BagType.POUCH);\n\n @Override\n public void onInitialize() {\n Registry.register(Registry.ITEM, new Identifier(MOD_ID, \"tanned_leather\"), TANNED_LEATHER);\n Registry.register(Registry.ITEM, new Identifier(MOD_ID, \"satchel_strap\"), SATCHEL_STRAP);\n\n Registry.register(Registry.ITEM, new Identifier(MOD_ID, \"satchel\"), SATCHEL);\n Registry.register(Registry.ITEM, new Identifier(MOD_ID, \"upgraded_satchel\"), UPGRADED_SATCHEL);\n Registry.register(Registry.ITEM, new Identifier(MOD_ID, \"pouch\"), POUCH);\n Registry.register(Registry.ITEM, new Identifier(MOD_ID, \"upgraded_pouch\"), UPGRADED_POUCH);\n }\n}"
},
{
"identifier": "ScoutPlayerScreenHandler",
"path": "src/main/java/pm/c7/scout/ScoutPlayerScreenHandler.java",
"snippet": "public interface ScoutPlayerScreenHandler {\n DefaultedList<BagSlot> scout$getSatchelSlots();\n DefaultedList<BagSlot> scout$getLeftPouchSlots();\n DefaultedList<BagSlot> scout$getRightPouchSlots();\n}"
},
{
"identifier": "BagSlot",
"path": "src/main/java/pm/c7/scout/screen/BagSlot.java",
"snippet": "public class BagSlot extends Slot {\n private final int index;\n public Inventory inventory;\n private boolean enabled = false;\n\n public BagSlot(int index, int x, int y) {\n super(null, index, x, y);\n this.index = index;\n }\n\n public void setInventory(Inventory inventory) {\n this.inventory = inventory;\n }\n\n public void setEnabled(boolean state) {\n enabled = state;\n }\n\n @Override\n public boolean canInsert(ItemStack stack) {\n if (stack.getItem() instanceof BaseBagItem)\n return false;\n\n return enabled && inventory != null;\n }\n\n @Override\n public boolean canTakeItems(PlayerEntity playerEntity) {\n return enabled && inventory != null;\n }\n\n @Override\n public boolean isEnabled() {\n return enabled && inventory != null;\n }\n\n @Override\n public ItemStack getStack() {\n return enabled && this.inventory != null ? this.inventory.getStack(this.index) : ItemStack.EMPTY;\n }\n\n @Override\n public void setStack(ItemStack stack) {\n if (enabled && this.inventory != null) {\n this.inventory.setStack(this.index, stack);\n this.markDirty();\n }\n }\n\n @Override\n public void markDirty() {\n if (enabled && this.inventory != null) {\n this.inventory.markDirty();\n }\n }\n\n @Override\n public ItemStack takeStack(int amount) {\n return enabled && this.inventory != null ? this.inventory.removeStack(this.index, amount) : ItemStack.EMPTY;\n }\n\n @Override\n public int getMaxItemCount() {\n return enabled && this.inventory != null ? this.inventory.getMaxCountPerStack() : 0;\n }\n}"
}
] | import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.screen.PlayerScreenHandler;
import net.minecraft.screen.ScreenHandler;
import net.minecraft.util.collection.DefaultedList;
import pm.c7.scout.Scout;
import pm.c7.scout.ScoutPlayerScreenHandler;
import pm.c7.scout.screen.BagSlot; | 1,311 | package pm.c7.scout.mixin;
@Mixin(value = PlayerScreenHandler.class, priority = 950)
public abstract class PlayerScreenHandlerMixin extends ScreenHandler implements ScoutPlayerScreenHandler {
protected PlayerScreenHandlerMixin() {
super(null, 0);
}
@Shadow
@Final
private PlayerEntity owner;
@Unique | package pm.c7.scout.mixin;
@Mixin(value = PlayerScreenHandler.class, priority = 950)
public abstract class PlayerScreenHandlerMixin extends ScreenHandler implements ScoutPlayerScreenHandler {
protected PlayerScreenHandlerMixin() {
super(null, 0);
}
@Shadow
@Final
private PlayerEntity owner;
@Unique | public final DefaultedList<BagSlot> satchelSlots = DefaultedList.ofSize(Scout.MAX_SATCHEL_SLOTS); | 2 | 2023-12-10 07:43:34+00:00 | 2k |
courage0916/mybatis-gain | src/main/java/com/gain/fill/FillListener.java | [
{
"identifier": "DatabaseService",
"path": "src/main/java/com/gain/util/DatabaseService.java",
"snippet": "@Service\npublic class DatabaseService {\n\n @Resource\n private Database database;\n\n\n\n private static final Map<String, List<String>> tables = new ConcurrentHashMap<>();\n\n @PostConstruct\n public void init(){\n try {\n Connection conn = DriverManager.getConnection(database.getUrl(), database.getUsername(), database.getPassword());\n DatabaseMetaData metaData = conn.getMetaData();\n String databaseType = metaData.getDatabaseProductName();\n\n //针对MySQL数据库进行相关生成操作\n if (databaseType.equals(\"MySQL\")) {\n //获取所有表结构\n ResultSet tableResultSet = metaData.getTables(null, \"%\", \"%\", new String[]{\"TABLE\"});\n String databaseName = conn.getCatalog();\n //循环所有表信息\n while (tableResultSet.next()) {\n String tableName = tableResultSet.getString(\"TABLE_NAME\");\n List<String> columns = new ArrayList<>();\n ResultSet columnsSet = metaData.getColumns(databaseName, database.getUsername(), tableName, null);\n while (columnsSet.next()){\n String columnName = columnsSet.getString(\"COLUMN_NAME\");\n columns.add(columnName);\n }\n tables.put(tableName,columns);\n }\n }\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n\n public List<String> findByTableName(String tableName){\n\n if(tables.containsKey(tableName)){\n return tables.get(tableName);\n }\n\n return new ArrayList<>();\n }\n\n public Boolean isExist(String tableName,String fileName){\n\n return findByTableName(tableName).contains(fileName);\n }\n}"
},
{
"identifier": "SpringContextUtil",
"path": "src/main/java/com/gain/util/SpringContextUtil.java",
"snippet": "@Component\npublic class SpringContextUtil implements ApplicationContextAware {\n\n private static ApplicationContext applicationContext;\n\n @Override\n public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {\n if(this.applicationContext==null){\n this.applicationContext = applicationContext;\n }\n }\n\n // 获取applicationContext\n public static ApplicationContext getApplicationContext() {\n return applicationContext;\n }\n\n /**\n * 通过name获取Bean\n *\n * @param name\n * @return Object 一个以所给名字注册的bean的实例\n * @throws BeansException\n */\n public static Object getBean(String name) throws BeansException {\n return getApplicationContext().getBean(name);\n }\n\n /**\n * 通过class获取Bean.\n * @param <T>\n * @param clazz\n * @return\n */\n public static <T> T getBean(Class<T> clazz){\n return getApplicationContext().getBean(clazz);\n }\n\n /**\n * 获取类型为requiredType的对象 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)\n *\n * @param name bean注册名\n * @param requiredType 返回对象类型\n * @return Object 返回requiredType类型对象\n * @throws BeansException\n */\n public <T> T getBean(String name, Class<T> requiredType) throws BeansException {\n return getApplicationContext().getBean(name, requiredType);\n }\n\n /**\n * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true\n *\n * @param name\n * @return boolean\n */\n public boolean containsBean(String name) {\n return getApplicationContext().containsBean(name);\n }\n\n /**\n * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。\n * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)\n *\n * @param name\n * @return boolean\n * @throws NoSuchBeanDefinitionException\n */\n public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {\n return getApplicationContext().isSingleton(name);\n }\n\n /**\n * @param name\n * @return Class 注册对象的类型\n * @throws NoSuchBeanDefinitionException\n */\n public Class getType(String name) throws NoSuchBeanDefinitionException {\n return getApplicationContext().getType(name);\n }\n\n /**\n * 如果给定的bean名字在bean定义中有别名,则返回这些别名\n *\n * @param name\n * @return\n * @throws NoSuchBeanDefinitionException\n */\n public String[] getAliases(String name) throws NoSuchBeanDefinitionException {\n return getApplicationContext().getAliases(name);\n }\n\n /**\n * 获取配置文件配置项的值\n *\n * @param key 配置项key\n */\n public String getEnvironmentProperty(String key) {\n return getApplicationContext().getEnvironment().getProperty(key);\n }\n\n /**\n * 获取配置文件配置项的值,未获取到时返回默认值\n *\n * @param key 配置项key\n */\n public String getEnvironmentProperty(String key, String defaultVal) {\n return getEnvironmentProperty(key) == null ? defaultVal : getEnvironmentProperty(key);\n }\n\n /**\n * 获取spring.profiles.active\n */\n public String getActiveProfile() {\n return getApplicationContext().getEnvironment().getActiveProfiles()[0];\n }\n\n}"
}
] | import com.gain.util.DatabaseService;
import com.gain.util.SpringContextUtil;
import jakarta.annotation.Resource;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.springframework.stereotype.Service;
import java.lang.reflect.Field;
import java.util.List; | 1,489 | package com.gain.fill;
public abstract class FillListener {
protected void setValue(Object obj, Field field, Object value) throws IllegalAccessException {
field.set(obj, value);
}
protected Boolean isExist(Object obj, String fileName) {
if (obj == null){
return false;
}
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (fileName.equalsIgnoreCase(field.getName())) {
return true;
}
}
return false;
}
protected Boolean isExist(String tableName, String fileName){ | package com.gain.fill;
public abstract class FillListener {
protected void setValue(Object obj, Field field, Object value) throws IllegalAccessException {
field.set(obj, value);
}
protected Boolean isExist(Object obj, String fileName) {
if (obj == null){
return false;
}
for (Field field : obj.getClass().getDeclaredFields()) {
field.setAccessible(true);
if (fileName.equalsIgnoreCase(field.getName())) {
return true;
}
}
return false;
}
protected Boolean isExist(String tableName, String fileName){ | DatabaseService databaseService = (DatabaseService) SpringContextUtil.getBean("databaseService"); | 0 | 2023-12-11 05:28:00+00:00 | 2k |
Viola-Siemens/Mod-Whitelist | src/main/java/com/hexagram2021/mod_whitelist/server/config/MWServerConfig.java | [
{
"identifier": "ModWhitelist",
"path": "src/main/java/com/hexagram2021/mod_whitelist/ModWhitelist.java",
"snippet": "public class ModWhitelist implements ModInitializer {\n\tpublic static final String MODID = \"mod_whitelist\";\n\tpublic static final String MOD_NAME = \"Mod Whitelist\";\n\tpublic static final String MOD_VERSION = FabricLoader.getInstance().getModContainer(MODID).orElseThrow().getMetadata().getVersion().getFriendlyString();\n\t\n\t@Override\n\tpublic void onInitialize() {\n\t}\n}"
},
{
"identifier": "MWLogger",
"path": "src/main/java/com/hexagram2021/mod_whitelist/common/utils/MWLogger.java",
"snippet": "public class MWLogger {\n\tpublic static final Logger LOGGER = LogUtils.getLogger();\n}"
},
{
"identifier": "MODID",
"path": "src/main/java/com/hexagram2021/mod_whitelist/ModWhitelist.java",
"snippet": "public static final String MODID = \"mod_whitelist\";"
}
] | import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hexagram2021.mod_whitelist.ModWhitelist;
import com.hexagram2021.mod_whitelist.common.utils.MWLogger;
import org.apache.commons.lang3.tuple.Pair;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static com.hexagram2021.mod_whitelist.ModWhitelist.MODID; | 999 | package com.hexagram2021.mod_whitelist.server.config;
public class MWServerConfig {
public interface IConfigValue<T extends Serializable> {
List<IConfigValue<?>> configValues = Lists.newArrayList();
String name();
T value();
void parseAsValue(JsonElement element);
void checkValueRange() throws ConfigValueException;
}
public static abstract class ListConfigValue<T extends Serializable> implements IConfigValue<ArrayList<T>> {
private final String name;
private final ArrayList<T> value;
@SafeVarargs
public ListConfigValue(String name, T... defaultValues) {
this(name, Arrays.stream(defaultValues).collect(Collectors.toCollection(Lists::newArrayList)));
configValues.add(this);
}
public ListConfigValue(String name, ArrayList<T> value) {
this.name = name;
this.value = value;
}
@Override
public void checkValueRange() throws ConfigValueException {
this.value.forEach(v -> {
if(!this.isValid(v)) {
throw new ConfigValueException(this.createExceptionDescription(v));
}
});
}
@Override
public void parseAsValue(JsonElement element) {
this.value.clear();
element.getAsJsonArray().asList().forEach(e -> this.value.add(this.parseAsElementValue(e)));
}
@Override
public String name() {
return this.name;
}
@Override
public ArrayList<T> value() {
return this.value;
}
protected abstract boolean isValid(T element);
protected abstract String createExceptionDescription(T element);
protected abstract T parseAsElementValue(JsonElement element);
}
public static class ModIdListConfigValue extends ListConfigValue<String> {
public ModIdListConfigValue(String name, String... defaultValues) {
super(name, defaultValues);
}
@SuppressWarnings("unused")
public ModIdListConfigValue(String name, ArrayList<String> value) {
super(name, value);
}
@Override
protected boolean isValid(String element) {
return Pattern.matches("[a-z\\d\\-._]+", element);
}
@Override
protected String createExceptionDescription(String element) {
return "\"%s\" is not a valid modid!".formatted(element);
}
@Override
protected String parseAsElementValue(JsonElement element) {
return element.getAsString();
}
}
public static class BoolConfigValue implements IConfigValue<Boolean> {
private final String name;
private boolean value;
public BoolConfigValue(String name, boolean value) {
this.name = name;
this.value = value;
configValues.add(this);
}
@Override
public void checkValueRange() throws ConfigValueException {
}
@Override
public void parseAsValue(JsonElement element) {
this.value = element.getAsBoolean();
}
@Override
public String name() {
return this.name;
}
@Override
public Boolean value() {
return this.value;
}
}
public static final File filePath = new File("./config/"); | package com.hexagram2021.mod_whitelist.server.config;
public class MWServerConfig {
public interface IConfigValue<T extends Serializable> {
List<IConfigValue<?>> configValues = Lists.newArrayList();
String name();
T value();
void parseAsValue(JsonElement element);
void checkValueRange() throws ConfigValueException;
}
public static abstract class ListConfigValue<T extends Serializable> implements IConfigValue<ArrayList<T>> {
private final String name;
private final ArrayList<T> value;
@SafeVarargs
public ListConfigValue(String name, T... defaultValues) {
this(name, Arrays.stream(defaultValues).collect(Collectors.toCollection(Lists::newArrayList)));
configValues.add(this);
}
public ListConfigValue(String name, ArrayList<T> value) {
this.name = name;
this.value = value;
}
@Override
public void checkValueRange() throws ConfigValueException {
this.value.forEach(v -> {
if(!this.isValid(v)) {
throw new ConfigValueException(this.createExceptionDescription(v));
}
});
}
@Override
public void parseAsValue(JsonElement element) {
this.value.clear();
element.getAsJsonArray().asList().forEach(e -> this.value.add(this.parseAsElementValue(e)));
}
@Override
public String name() {
return this.name;
}
@Override
public ArrayList<T> value() {
return this.value;
}
protected abstract boolean isValid(T element);
protected abstract String createExceptionDescription(T element);
protected abstract T parseAsElementValue(JsonElement element);
}
public static class ModIdListConfigValue extends ListConfigValue<String> {
public ModIdListConfigValue(String name, String... defaultValues) {
super(name, defaultValues);
}
@SuppressWarnings("unused")
public ModIdListConfigValue(String name, ArrayList<String> value) {
super(name, value);
}
@Override
protected boolean isValid(String element) {
return Pattern.matches("[a-z\\d\\-._]+", element);
}
@Override
protected String createExceptionDescription(String element) {
return "\"%s\" is not a valid modid!".formatted(element);
}
@Override
protected String parseAsElementValue(JsonElement element) {
return element.getAsString();
}
}
public static class BoolConfigValue implements IConfigValue<Boolean> {
private final String name;
private boolean value;
public BoolConfigValue(String name, boolean value) {
this.name = name;
this.value = value;
configValues.add(this);
}
@Override
public void checkValueRange() throws ConfigValueException {
}
@Override
public void parseAsValue(JsonElement element) {
this.value = element.getAsBoolean();
}
@Override
public String name() {
return this.name;
}
@Override
public Boolean value() {
return this.value;
}
}
public static final File filePath = new File("./config/"); | private static final File configFile = new File(filePath + "/" + MODID + "-config.json"); | 2 | 2023-12-06 12:16:52+00:00 | 2k |
sinbad-navigator/erp-crm | system/src/main/java/com/ec/sys/service/impl/SysNoticeServiceImpl.java | [
{
"identifier": "SysNotice",
"path": "system/src/main/java/com/ec/sys/domain/SysNotice.java",
"snippet": "public class SysNotice extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /**\n * 公告ID\n */\n private Long noticeId;\n\n /**\n * 公告标题\n */\n private String noticeTitle;\n\n /**\n * 公告类型(1通知 2公告)\n */\n private String noticeType;\n\n /**\n * 公告内容\n */\n private String noticeContent;\n\n /**\n * 公告状态(0正常 1关闭)\n */\n private String status;\n\n public Long getNoticeId() {\n return noticeId;\n }\n\n public void setNoticeId(Long noticeId) {\n this.noticeId = noticeId;\n }\n\n @Xss(message = \"公告标题不能包含脚本字符\")\n @NotBlank(message = \"公告标题不能为空\")\n @Size(min = 0, max = 50, message = \"公告标题不能超过50个字符\")\n public String getNoticeTitle() {\n return noticeTitle;\n }\n\n public void setNoticeTitle(String noticeTitle) {\n this.noticeTitle = noticeTitle;\n }\n\n public String getNoticeType() {\n return noticeType;\n }\n\n public void setNoticeType(String noticeType) {\n this.noticeType = noticeType;\n }\n\n public String getNoticeContent() {\n return noticeContent;\n }\n\n public void setNoticeContent(String noticeContent) {\n this.noticeContent = noticeContent;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)\n .append(\"noticeId\", getNoticeId())\n .append(\"noticeTitle\", getNoticeTitle())\n .append(\"noticeType\", getNoticeType())\n .append(\"noticeContent\", getNoticeContent())\n .append(\"status\", getStatus())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .toString();\n }\n}"
},
{
"identifier": "SysNoticeMapper",
"path": "system/src/main/java/com/ec/sys/mapper/SysNoticeMapper.java",
"snippet": "public interface SysNoticeMapper {\n /**\n * 查询公告信息\n *\n * @param noticeId 公告ID\n * @return 公告信息\n */\n public SysNotice selectNoticeById(Long noticeId);\n\n /**\n * 查询公告列表\n *\n * @param notice 公告信息\n * @return 公告集合\n */\n public List<SysNotice> selectNoticeList(SysNotice notice);\n\n /**\n * 新增公告\n *\n * @param notice 公告信息\n * @return 结果\n */\n public int insertNotice(SysNotice notice);\n\n /**\n * 修改公告\n *\n * @param notice 公告信息\n * @return 结果\n */\n public int updateNotice(SysNotice notice);\n\n /**\n * 批量删除公告\n *\n * @param noticeId 公告ID\n * @return 结果\n */\n public int deleteNoticeById(Long noticeId);\n\n /**\n * 批量删除公告信息\n *\n * @param noticeIds 需要删除的公告ID\n * @return 结果\n */\n public int deleteNoticeByIds(Long[] noticeIds);\n}"
},
{
"identifier": "ISysNoticeService",
"path": "system/src/main/java/com/ec/sys/service/ISysNoticeService.java",
"snippet": "public interface ISysNoticeService {\n /**\n * 查询公告信息\n *\n * @param noticeId 公告ID\n * @return 公告信息\n */\n public SysNotice selectNoticeById(Long noticeId);\n\n /**\n * 查询公告列表\n *\n * @param notice 公告信息\n * @return 公告集合\n */\n public List<SysNotice> selectNoticeList(SysNotice notice);\n\n /**\n * 新增公告\n *\n * @param notice 公告信息\n * @return 结果\n */\n public int insertNotice(SysNotice notice);\n\n /**\n * 修改公告\n *\n * @param notice 公告信息\n * @return 结果\n */\n public int updateNotice(SysNotice notice);\n\n /**\n * 删除公告信息\n *\n * @param noticeId 公告ID\n * @return 结果\n */\n public int deleteNoticeById(Long noticeId);\n\n /**\n * 批量删除公告信息\n *\n * @param noticeIds 需要删除的公告ID\n * @return 结果\n */\n public int deleteNoticeByIds(Long[] noticeIds);\n}"
}
] | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ec.sys.domain.SysNotice;
import com.ec.sys.mapper.SysNoticeMapper;
import com.ec.sys.service.ISysNoticeService; | 1,391 | package com.ec.sys.service.impl;
/**
* 公告 服务层实现
*
* @author ec
*/
@Service
public class SysNoticeServiceImpl implements ISysNoticeService {
@Autowired | package com.ec.sys.service.impl;
/**
* 公告 服务层实现
*
* @author ec
*/
@Service
public class SysNoticeServiceImpl implements ISysNoticeService {
@Autowired | private SysNoticeMapper noticeMapper; | 1 | 2023-12-07 14:23:12+00:00 | 2k |
SteveKunG/MinecartSpawnerRevived | src/main/java/com/stevekung/msr/mixin/client/MixinMinecartSpawner.java | [
{
"identifier": "MinecartSpawnerRevived",
"path": "src/main/java/com/stevekung/msr/MinecartSpawnerRevived.java",
"snippet": "public class MinecartSpawnerRevived\n{\n public static final String MOD_ID = \"minecart_spawner_revived\";\n public static final Logger LOGGER = LogUtils.getLogger();\n\n /**\n * Use to request SpawnData from the client side. Then sent the SpawnData into the server.\n */\n public static final ResourceLocation REQUEST_SPAWNDATA = new ResourceLocation(MOD_ID, \"request_spawndata\");\n\n /**\n * Use to send SpawnData to the client side to set spawner display.\n */\n public static final ResourceLocation SEND_SPAWNDATA = new ResourceLocation(MOD_ID, \"send_spawndata\");\n\n public static void init()\n {\n LOGGER.info(\"MinecartSpawnerRevived loaded, #PleaseAddSpawnerMinecartItem!\");\n ServerPlayNetworking.registerGlobalReceiver(MinecartSpawnerRevived.REQUEST_SPAWNDATA, MinecartSpawnerRevived::requestSpawnData);\n }\n\n public static void requestSpawnData(MinecraftServer server, ServerPlayer player, ServerGamePacketListenerImpl handler, FriendlyByteBuf buf, PacketSender responseSender)\n {\n var entityId = buf.readVarInt();\n\n // Make sure to run on the server thread because we use level.getRandom() to get SpawnData from the server side. This will prevent \"Accessing LegacyRandomSource from multiple threads\" error.\n server.execute(() ->\n {\n var spawner = (MinecartSpawner)player.level().getEntity(entityId);\n\n if (spawner != null)\n {\n var level = spawner.level();\n sendSpawnDataPacket(player, entityId, spawner.getSpawner().getOrCreateNextSpawnData(level, level.getRandom(), spawner.blockPosition()));\n }\n });\n }\n\n public static void sendSpawnDataPacket(ServerPlayer player, int entityId, SpawnData spawnData)\n {\n // If an entity to spawn is empty, ignore it.\n if (spawnData.entityToSpawn().isEmpty())\n {\n return;\n }\n\n var packetByteBuf = PacketByteBufs.create();\n packetByteBuf.writeInt(entityId);\n var compound = new CompoundTag();\n compound.put(BaseSpawner.SPAWN_DATA_TAG, SpawnData.CODEC.encodeStart(NbtOps.INSTANCE, spawnData).result().orElseThrow(() -> new IllegalStateException(\"Invalid SpawnData\")));\n packetByteBuf.writeNbt(compound);\n ServerPlayNetworking.send(player, MinecartSpawnerRevived.SEND_SPAWNDATA, packetByteBuf);\n }\n}"
},
{
"identifier": "MinecartSpawnerRevivedClient",
"path": "src/main/java/com/stevekung/msr/MinecartSpawnerRevivedClient.java",
"snippet": "public class MinecartSpawnerRevivedClient\n{\n public static void init()\n {\n ClientPlayNetworking.registerGlobalReceiver(MinecartSpawnerRevived.SEND_SPAWNDATA, MinecartSpawnerRevivedClient::setSpawnerDisplay);\n }\n\n public static void sendSpawnDataRequest(int entityId)\n {\n var buff = PacketByteBufs.create();\n buff.writeVarInt(entityId);\n ClientPlayNetworking.send(MinecartSpawnerRevived.REQUEST_SPAWNDATA, buff);\n }\n\n public static void setSpawnerDisplay(Minecraft minecraft, ClientPacketListener listener, FriendlyByteBuf buf, PacketSender responseSender)\n {\n var entityId = buf.readInt();\n var compoundTag = buf.readNbt();\n var level = minecraft.level;\n\n minecraft.execute(() ->\n {\n if (level != null)\n {\n var spawner = (MinecartSpawner)level.getEntity(entityId);\n\n if (spawner == null || compoundTag == null)\n {\n return;\n }\n\n var spawnData = SpawnData.CODEC.parse(NbtOps.INSTANCE, compoundTag.getCompound(BaseSpawner.SPAWN_DATA_TAG)).resultOrPartial(string -> MinecartSpawnerRevived.LOGGER.warn(\"Invalid SpawnData: {}\", string)).orElseGet(SpawnData::new);\n spawner.getSpawner().displayEntity = EntityType.loadEntityRecursive(spawnData.entityToSpawn(), level, Function.identity());\n }\n });\n }\n}"
},
{
"identifier": "SpawnerClientTicker",
"path": "src/main/java/com/stevekung/msr/client/renderer/SpawnerClientTicker.java",
"snippet": "public interface SpawnerClientTicker\n{\n void msr$clientTick(Level level, MinecartSpawner spawner);\n}"
}
] | import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.stevekung.msr.MinecartSpawnerRevived;
import com.stevekung.msr.MinecartSpawnerRevivedClient;
import com.stevekung.msr.client.renderer.SpawnerClientTicker;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.core.BlockPos;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.protocol.game.ClientboundAddEntityPacket;
import net.minecraft.world.entity.vehicle.AbstractMinecart;
import net.minecraft.world.entity.vehicle.MinecartSpawner;
import net.minecraft.world.level.BaseSpawner;
import net.minecraft.world.level.Level; | 1,389 | package com.stevekung.msr.mixin.client;
@Mixin(MinecartSpawner.class)
public abstract class MixinMinecartSpawner extends AbstractMinecart
{
MixinMinecartSpawner()
{
super(null, null);
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>Re-send a request SpawnData packet to the server when modifying spawner minecart data.</p>
*/
@Inject(method = "readAdditionalSaveData", at = @At("TAIL"))
private void msr$resendSpawnDataRequestOnLoad(CompoundTag compound, CallbackInfo info)
{ | package com.stevekung.msr.mixin.client;
@Mixin(MinecartSpawner.class)
public abstract class MixinMinecartSpawner extends AbstractMinecart
{
MixinMinecartSpawner()
{
super(null, null);
}
/**
* <p>Fix for <a href="https://bugs.mojang.com/browse/MC-65065">MC-65065</a></p>
*
* <p>Re-send a request SpawnData packet to the server when modifying spawner minecart data.</p>
*/
@Inject(method = "readAdditionalSaveData", at = @At("TAIL"))
private void msr$resendSpawnDataRequestOnLoad(CompoundTag compound, CallbackInfo info)
{ | if (ClientPlayNetworking.canSend(MinecartSpawnerRevived.REQUEST_SPAWNDATA)) | 0 | 2023-12-08 06:53:56+00:00 | 2k |
Serilum/Fish-On-The-Line | Fabric/src/main/java/com/natamus/fishontheline/ModFabric.java | [
{
"identifier": "FishOnTheLineEvent",
"path": "Common/src/main/java/com/natamus/fishontheline/events/FishOnTheLineEvent.java",
"snippet": "public class FishOnTheLineEvent {\n\tprivate static final HashMap<String, Integer> sounddelay = new HashMap<String, Integer>();\n\t\n\tpublic static void onPlayerTick(ServerLevel serverLevel, ServerPlayer player) {\n\t\tFishingHook fbe = player.fishing;\n\t\tif (fbe == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (ConfigHandler.mustHoldBellInOffhand) {\n\t\t\tItemStack offhandStack = player.getOffhandItem();\n\t\t\tItem offhandItem = offhandStack.getItem();\n\t\t\tif (!offhandStack.getItem().equals(Items.BELL)) {\n\t\t\t\tif (offhandItem instanceof FishingRodItem) {\n\t\t\t\t\tif (!player.getMainHandItem().getItem().equals(Items.BELL)) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tboolean fishontheline = EntityFunctions.fishingHookHasCatch(fbe);\n\t\t\n\t\tif (fishontheline) {\n\t\t\tint delay = 0;\n\t\t\t\n\t\t\tString playername = player.getName().getString();\n\t\t\tif (sounddelay.containsKey(playername)) {\n\t\t\t\tdelay = sounddelay.get(playername);\n\t\t\t}\n\t\t\t\n\t\t\tif (delay == 0) {\n\t\t\t\tserverLevel.playSound(null, player.getX(), player.getY(), player.getZ(), SoundEvents.EXPERIENCE_ORB_PICKUP, SoundSource.NEUTRAL, 0.5F, 0.4F / (GlobalVariables.random.nextFloat() * 0.4F + 0.8F));\n\t\t\t\tdelay = 7;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdelay -= 1;\n\t\t\t}\n\t\t\t\n\t\t\tsounddelay.put(playername, delay);\n\t\t}\n\t}\n}"
},
{
"identifier": "Reference",
"path": "Common/src/main/java/com/natamus/fishontheline/util/Reference.java",
"snippet": "public class Reference {\n\tpublic static final String MOD_ID = \"fishontheline\";\n\tpublic static final String NAME = \"Fish On The Line\";\n\tpublic static final String VERSION = \"3.2\";\n\tpublic static final String ACCEPTED_VERSIONS = \"[1.20.4]\";\n}"
}
] | import com.natamus.collective.check.RegisterMod;
import com.natamus.collective.fabric.callbacks.CollectivePlayerEvents;
import com.natamus.fishontheline.events.FishOnTheLineEvent;
import com.natamus.fishontheline.util.Reference;
import net.fabricmc.api.ModInitializer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer; | 658 | package com.natamus.fishontheline;
public class ModFabric implements ModInitializer {
@Override
public void onInitialize() {
setGlobalConstants();
ModCommon.init();
loadEvents();
| package com.natamus.fishontheline;
public class ModFabric implements ModInitializer {
@Override
public void onInitialize() {
setGlobalConstants();
ModCommon.init();
loadEvents();
| RegisterMod.register(Reference.NAME, Reference.MOD_ID, Reference.VERSION, Reference.ACCEPTED_VERSIONS); | 1 | 2023-12-12 09:12:39+00:00 | 2k |
FRC8806/frcBT_2023 | src/main/java/frc/robot/DashBoard.java | [
{
"identifier": "AutoMap",
"path": "src/main/java/frc/robot/commands/auto/AutoMap.java",
"snippet": "public class AutoMap {\n\tpublic static DriveTrain driveTrain = RobotContainer.driveTrain;\n\n\tpublic static final Command AutoTest1 = getPath(\"Test Path 1\")\n\t\t\t.andThen(() -> driveTrain.drive(0, 0, 0, true));\n\n\tpublic static final Command AutoTest2 = getPath(\"Zero Path\")\n\t\t\t.andThen(() -> driveTrain.drive(0, 0, 0, true));\n\n\tpublic static final Command AutoTest1001 = getPath(\"Test Path 1001\")\n\t\t\t.andThen(() -> driveTrain.drive(0, 0, 0, true));\n\n\tpublic static Map<String, Command> autoMap = Map.of(\n\t\t\t\"AutoTest1\", AutoTest1,\n\t\t\t\"AutoTest2\", AutoTest2,\n\t\t\t\"AutoTest1001\", AutoTest1001);\n\n\tprivate static PPSwerveControllerCommand getPath(String pathName) {\n\t\treturn new PPSwerveControllerCommand(\n\t\t\t\tPathPlanner.loadPath(pathName, SwerveConstants.kMaxVelocityMetersPerSecond,\n\t\t\t\t\t\tSwerveConstants.kMaxAccelerationMetersPerSecond),\n\t\t\t\tdriveTrain::getPose,\n\t\t\t\tSwerveConstants.SWERVE_KINEMATICS,\n\t\t\t\tnew PIDController(SwerveConstants.kPathingXP, SwerveConstants.kPathingXI, SwerveConstants.kPathingXD),\n\t\t\t\tnew PIDController(SwerveConstants.kPathingYP, SwerveConstants.kPathingYI, SwerveConstants.kPathingYD),\n\t\t\t\tnew PIDController(SwerveConstants.kPathingTP, SwerveConstants.kPathingTI, SwerveConstants.kPathingTD),\n\t\t\t\tdriveTrain::setModuleStates,\n\t\t\t\tdriveTrain);\n\t}\n}"
},
{
"identifier": "Limelight",
"path": "src/main/java/frc/robot/subsystems/Limelight.java",
"snippet": "public class Limelight extends SubsystemBase {\n private NetworkTable limelight;\n /** Creates a new LimelightTest1109. */\n public Limelight(String name) {\n limelight = NetworkTableInstance.getDefault().getTable(name);\n }\n\n @Override\n public void periodic() {\n }\n\n public void setPipeLine(int pipeLine) {\n limelight.getEntry(\"pipeline\").setNumber(pipeLine);\n }\n\n public double getPipeLine() {\n return limelight.getEntry(\"getpipe\").getDouble(0.0);\n }\n\n public double getX() {\n return limelight.getEntry(\"tx\").getDouble(0.0);\n }\n\n public double getY() {\n return limelight.getEntry(\"ty\").getDouble(0.0);\n }\n\n public double getArea() {\n return limelight.getEntry(\"ta\").getDouble(0.0);\n }\n\n public double [] getTargetposeInRobotspace() {\n return limelight.getEntry(\"targetpose_robotspace\").getDoubleArray(new double[6]);\n }\t\n}"
}
] | import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import frc.robot.commands.auto.AutoMap;
import frc.robot.subsystems.Limelight; | 900 | package frc.robot;
/**
* Put the needed in-game data here.
* Take care that don't put null object on table.
*/
public class DashBoard {
private SendableChooser<String> autoChooser;
public static String autoString = "nonAuto";
public static double testXP = 0;
public static double testXI = 0;
public static double testXD = 0;
public static double testZP = 0;
public DashBoard() {
autoChooserSetUp();
}
public void autoChooserSetUp() {
autoChooser = new SendableChooser<>();
autoChooser.setDefaultOption("nonAuto", "nonAuto"); | package frc.robot;
/**
* Put the needed in-game data here.
* Take care that don't put null object on table.
*/
public class DashBoard {
private SendableChooser<String> autoChooser;
public static String autoString = "nonAuto";
public static double testXP = 0;
public static double testXI = 0;
public static double testXD = 0;
public static double testZP = 0;
public DashBoard() {
autoChooserSetUp();
}
public void autoChooserSetUp() {
autoChooser = new SendableChooser<>();
autoChooser.setDefaultOption("nonAuto", "nonAuto"); | AutoMap.AutoTest1.setName("AutoTest1"); | 0 | 2023-12-13 11:38:11+00:00 | 2k |
applepi-2067/2023_Pure_Swerve | src/main/java/frc/robot/subsystems/DriveMotor.java | [
{
"identifier": "Conversions",
"path": "src/main/java/frc/robot/utils/Conversions.java",
"snippet": "public class Conversions {\n public static double RPMToTicksPer100ms(double RPM, double ticksPerRev) {\n return RPM * ticksPerRev / (60.0 * 10.0);\n }\n\n public static double ticksPer100msToRPM(double ticksPer100ms, double ticksPerRev) {\n return ticksPer100ms * (10.0 * 60.0) * (1.0 / ticksPerRev);\n }\n\n\n public static double ticksToMeters(double ticks, double ticksPerRev, double radiusMeters) {\n return ticks * (1.0 / ticksPerRev) * (Math.PI * 2.0 * radiusMeters);\n }\n\n public static double metersToTicks(double meters, double ticksPerRev, double radiusMeters) {\n return meters * (1.0 / (Math.PI * 2.0 * radiusMeters)) * ticksPerRev;\n }\n\n\n public static double metersPerSecondToRPM(double metersPerSecond, double radiusMeters) {\n return metersPerSecond * 60.0 / (radiusMeters * (2.0 * Math.PI));\n }\n\n public static double rpmToMetersPerSecond(double RPM, double radiusMeters) {\n return RPM * (1.0 / 60.0) * (2 * Math.PI) * radiusMeters;\n }\n\n \n public static double degreesToTicks(double degrees, double ticksPerRev) {\n return degrees * (1.0 / 360.0) * ticksPerRev;\n }\n\n public static double ticksToDegrees(double ticks, double ticksPerRev) {\n return ticks * (1.0 / ticksPerRev) * 360.0;\n }\n}"
},
{
"identifier": "Gains",
"path": "src/main/java/frc/robot/utils/Gains.java",
"snippet": "public class Gains {\n public final double kP;\n\tpublic final double kI;\n\tpublic final double kD;\n\tpublic final double kF;\n\tpublic final double kIzone;\n\tpublic final double kPeakOutput;\n\t\n\tpublic Gains(double _kP, double _kF, double _kPeakOutput) {\n\t\tthis(_kP, 0.0, 0.0, _kF, 0.0, _kPeakOutput);\n\t}\n\n\tpublic Gains(\n\t\tdouble _kP, double _kI, double _kD,\n\t\tdouble _kF, double _kIzone, double _kPeakOutput\n\t) {\n\t\tkP = _kP;\n\t\tkI = _kI;\n\t\tkD = _kD;\n\t\tkF = _kF;\n\t\tkIzone = _kIzone;\n\t\tkPeakOutput = _kPeakOutput;\n }\n\n\tpublic void setGains(SparkMaxPIDController pidController, int pidSlot) {\n\t\tpidController.setP(kP, pidSlot);\n pidController.setI(kI, pidSlot);\n pidController.setD(kD, pidSlot);\n pidController.setFF(kF, pidSlot); \n pidController.setIZone(kIzone, pidSlot);\n pidController.setOutputRange(-kPeakOutput, kPeakOutput, pidSlot);\n\t}\n\n\tpublic void setGains(WPI_TalonFX motor, int pidSlot, int pidLoop, int timeoutMS) {\n\t\tmotor.selectProfileSlot(pidSlot, pidLoop);\n\n motor.config_kF(pidSlot, kF, timeoutMS);\n motor.config_kP(pidSlot, kP, timeoutMS);\n motor.config_kI(pidSlot, kI, timeoutMS);\n motor.config_kD(pidSlot, kD, timeoutMS);\n motor.config_IntegralZone(pidSlot, kIzone, timeoutMS);\n\n // Set peak (max) and nominal (min) outputs.\n motor.configNominalOutputForward(0.0, timeoutMS);\n motor.configNominalOutputReverse(0.0, timeoutMS);\n motor.configPeakOutputForward(kPeakOutput, timeoutMS);\n motor.configPeakOutputReverse(-1.0 * kPeakOutput, timeoutMS);\n\t}\n\n\tpublic static void configSmartMotion(\n\t\tSparkMaxPIDController pidController,\n\t\tdouble maxVelocityRPM,\n\t\tdouble minVelocityRPM,\n\t\tdouble maxAccelRPMPerSec,\n\t\tdouble allowedErrorRotations,\n\t\tint pidSlot\n\t) {\n pidController.setSmartMotionMaxVelocity(maxVelocityRPM, pidSlot);\n pidController.setSmartMotionMinOutputVelocity(minVelocityRPM, pidSlot);\n pidController.setSmartMotionMaxAccel(maxAccelRPMPerSec, pidSlot);\n pidController.setSmartMotionAllowedClosedLoopError(allowedErrorRotations, pidSlot);\n }\n\n\tpublic static void configMotionMagic(\n\t\tWPI_TalonFX motor,\n\t\tint cruiseVelocityTicksPer100MS,\n\t\tint maxAccelTicksPer100MS_PerSec,\n\t\tint timeoutMS\n\t) {\n\t\tmotor.configMotionCruiseVelocity(cruiseVelocityTicksPer100MS, timeoutMS);\n\t\tmotor.configMotionAcceleration(maxAccelTicksPer100MS_PerSec, timeoutMS);\n\t}\n}"
}
] | import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.ctre.phoenix.motorcontrol.SupplyCurrentLimitConfiguration;
import com.ctre.phoenix.motorcontrol.TalonFXControlMode;
import com.ctre.phoenix.motorcontrol.TalonFXFeedbackDevice;
import com.ctre.phoenix.motorcontrol.can.WPI_TalonFX;
import edu.wpi.first.math.util.Units;
import frc.robot.utils.Conversions;
import frc.robot.utils.Gains; | 1,556 | package frc.robot.subsystems;
public class DriveMotor {
private final WPI_TalonFX m_motor;
// Motor settings.
private static final boolean ENABLE_CURRENT_LIMIT = true;
private static final double CONTINUOUS_CURRENT_LIMIT_AMPS = 55.0;
private static final double TRIGGER_THRESHOLD_LIMIT_AMPS = 60.0;
private static final double TRIGGER_THRESHOLD_TIME_SECONDS = 0.5;
private static final double PERCENT_DEADBAND = 0.001;
// Conversion constants.
private static final double TICKS_PER_REV = 2048.0;
private static final double WHEEL_RADIUS_METERS = Units.inchesToMeters(4.0 / 2.0);
private static final double GEAR_RATIO = 6.12;
// PID.
private static final int K_TIMEOUT_MS = 10;
private static final int K_PID_LOOP = 0;
private static final int K_PID_SLOT = 0; | package frc.robot.subsystems;
public class DriveMotor {
private final WPI_TalonFX m_motor;
// Motor settings.
private static final boolean ENABLE_CURRENT_LIMIT = true;
private static final double CONTINUOUS_CURRENT_LIMIT_AMPS = 55.0;
private static final double TRIGGER_THRESHOLD_LIMIT_AMPS = 60.0;
private static final double TRIGGER_THRESHOLD_TIME_SECONDS = 0.5;
private static final double PERCENT_DEADBAND = 0.001;
// Conversion constants.
private static final double TICKS_PER_REV = 2048.0;
private static final double WHEEL_RADIUS_METERS = Units.inchesToMeters(4.0 / 2.0);
private static final double GEAR_RATIO = 6.12;
// PID.
private static final int K_TIMEOUT_MS = 10;
private static final int K_PID_LOOP = 0;
private static final int K_PID_SLOT = 0; | private static final Gains PID_GAINS = new Gains(0.01, 0.045, 1.0); | 1 | 2023-12-13 02:33:42+00:00 | 2k |
ganeshbabugb/NASC-CMS | src/main/java/com/nasc/application/data/repository/SubjectRepository.java | [
{
"identifier": "DepartmentEntity",
"path": "src/main/java/com/nasc/application/data/core/DepartmentEntity.java",
"snippet": "@Entity\n@Table(name = \"t_departments\")\npublic class DepartmentEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n private String name;\n\n private String shortName;\n\n @OneToMany(mappedBy = \"department\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\n private Set<SubjectEntity> subjects = new HashSet<>();\n\n @Override\n public String toString() {\n return name;\n }\n\n\n @Override\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getShortName() {\n return shortName;\n }\n\n public void setShortName(String shortName) {\n this.shortName = shortName;\n }\n\n public Set<SubjectEntity> getSubjects() {\n return subjects;\n }\n\n public void setSubjects(Set<SubjectEntity> subjects) {\n this.subjects = subjects;\n }\n}"
},
{
"identifier": "SubjectEntity",
"path": "src/main/java/com/nasc/application/data/core/SubjectEntity.java",
"snippet": "@Entity\n@Table(name = \"t_subjects\")\npublic class SubjectEntity implements BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String subjectName;\n private String subjectShortForm;\n private String subjectCode;\n @Enumerated(EnumType.STRING)\n private PaperType paperType;\n\n @Enumerated(EnumType.STRING)\n private MajorOfPaper majorOfPaper;\n\n @ManyToOne\n @JoinColumn(name = \"department_id\")\n private DepartmentEntity department;\n\n @Enumerated(EnumType.STRING)\n private Semester semester;\n\n @Override\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public PaperType getPaperType() {\n return paperType;\n }\n\n public void setPaperType(PaperType paperType) {\n this.paperType = paperType;\n }\n\n public String getSubjectCode() {\n return subjectCode;\n }\n\n public void setSubjectCode(String subjectCode) {\n this.subjectCode = subjectCode;\n }\n\n public String getSubjectName() {\n return subjectName;\n }\n\n public void setSubjectName(String subjectName) {\n this.subjectName = subjectName;\n }\n\n public String getSubjectShortForm() {\n return subjectShortForm;\n }\n\n public void setSubjectShortForm(String subjectShortForm) {\n this.subjectShortForm = subjectShortForm;\n }\n\n public MajorOfPaper getMajorOfPaper() {\n return majorOfPaper;\n }\n\n public void setMajorOfPaper(MajorOfPaper majorOfPaper) {\n this.majorOfPaper = majorOfPaper;\n }\n\n public DepartmentEntity getDepartment() {\n return department;\n }\n\n public void setDepartment(DepartmentEntity department) {\n this.department = department;\n }\n\n public Semester getSemester() {\n return semester;\n }\n\n public void setSemester(Semester semester) {\n this.semester = semester;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof SubjectEntity subject)) return false;\n return Objects.equals(id, subject.id);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id);\n }\n}"
},
{
"identifier": "Semester",
"path": "src/main/java/com/nasc/application/data/core/enums/Semester.java",
"snippet": "public enum Semester {\n SEMESTER_1,\n SEMESTER_2,\n SEMESTER_3,\n SEMESTER_4,\n SEMESTER_5,\n SEMESTER_6;\n\n public String getDisplayName() {\n String capitalize = UIUtils.toCapitalize(name());\n return capitalize.replace(\"_\", \" \");\n }\n\n}"
}
] | import com.nasc.application.data.core.DepartmentEntity;
import com.nasc.application.data.core.SubjectEntity;
import com.nasc.application.data.core.enums.Semester;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List; | 1,145 | package com.nasc.application.data.repository;
@Repository
public interface SubjectRepository extends JpaRepository<SubjectEntity, Long> { | package com.nasc.application.data.repository;
@Repository
public interface SubjectRepository extends JpaRepository<SubjectEntity, Long> { | List<SubjectEntity> findByDepartmentAndSemester(DepartmentEntity department, Semester semester); | 2 | 2023-12-10 18:07:28+00:00 | 2k |
BroncBotz3481/FRC2024 | src/main/java/frc/robot/RobotContainer.java | [
{
"identifier": "OperatorConstants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public static class OperatorConstants {\n public static final int kDriverControllerPort = 0;\n}"
},
{
"identifier": "Autos",
"path": "src/main/java/frc/robot/commands/Autos.java",
"snippet": "public final class Autos {\n /** Example static factory for an autonomous command. */\n public static Command exampleAuto(ExampleSubsystem subsystem) {\n return Commands.sequence(subsystem.exampleMethodCommand(), new ExampleCommand(subsystem));\n }\n\n private Autos() {\n throw new UnsupportedOperationException(\"This is a utility class!\");\n }\n}"
},
{
"identifier": "ExampleCommand",
"path": "src/main/java/frc/robot/commands/ExampleCommand.java",
"snippet": "public class ExampleCommand extends Command {\n @SuppressWarnings({\"PMD.UnusedPrivateField\", \"PMD.SingularField\"})\n private final ExampleSubsystem m_subsystem;\n\n /**\n * Creates a new ExampleCommand.\n *\n * @param subsystem The subsystem used by this command.\n */\n public ExampleCommand(ExampleSubsystem subsystem) {\n m_subsystem = subsystem;\n // Use addRequirements() here to declare subsystem dependencies.\n addRequirements(subsystem);\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {}\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {}\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {}\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n return false;\n }\n}"
},
{
"identifier": "ExampleSubsystem",
"path": "src/main/java/frc/robot/subsystems/ExampleSubsystem.java",
"snippet": "public class ExampleSubsystem extends SubsystemBase {\n /** Creates a new ExampleSubsystem. */\n public ExampleSubsystem() {}\n\n /**\n * Example command factory method.\n *\n * @return a command\n */\n public Command exampleMethodCommand() {\n // Inline construction of command goes here.\n // Subsystem::RunOnce implicitly requires `this` subsystem.\n return runOnce(\n () -> {\n /* one-time action goes here */\n });\n }\n\n /**\n * An example method querying a boolean state of the subsystem (for example, a digital sensor).\n *\n * @return value of some boolean subsystem state, such as a digital sensor.\n */\n public boolean exampleCondition() {\n // Query some boolean state, such as a digital sensor.\n return false;\n }\n\n @Override\n public void periodic() {\n // This method will be called once per scheduler run\n }\n\n @Override\n public void simulationPeriodic() {\n // This method will be called once per scheduler run during simulation\n }\n}"
}
] | import frc.robot.Constants.OperatorConstants;
import frc.robot.commands.Autos;
import frc.robot.commands.ExampleCommand;
import frc.robot.subsystems.ExampleSubsystem;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.button.CommandXboxController;
import edu.wpi.first.wpilibj2.command.button.Trigger; | 1,152 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
// The robot's subsystems and commands are defined here...
private final ExampleSubsystem m_exampleSubsystem = new ExampleSubsystem();
// Replace with CommandPS4Controller or CommandJoystick if needed
private final CommandXboxController m_driverController =
new CommandXboxController(OperatorConstants.kDriverControllerPort);
/** The container for the robot. Contains subsystems, OI devices, and commands. */
public RobotContainer() {
// Configure the trigger bindings
configureBindings();
}
/**
* Use this method to define your trigger->command mappings. Triggers can be created via the
* {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
* predicate, or via the named factories in {@link
* edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link
* CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller
* PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight
* joysticks}.
*/
private void configureBindings() {
// Schedule `ExampleCommand` when `exampleCondition` changes to `true`
new Trigger(m_exampleSubsystem::exampleCondition) | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot;
/**
* This class is where the bulk of the robot should be declared. Since Command-based is a
* "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot}
* periodic methods (other than the scheduler calls). Instead, the structure of the robot (including
* subsystems, commands, and trigger mappings) should be declared here.
*/
public class RobotContainer {
// The robot's subsystems and commands are defined here...
private final ExampleSubsystem m_exampleSubsystem = new ExampleSubsystem();
// Replace with CommandPS4Controller or CommandJoystick if needed
private final CommandXboxController m_driverController =
new CommandXboxController(OperatorConstants.kDriverControllerPort);
/** The container for the robot. Contains subsystems, OI devices, and commands. */
public RobotContainer() {
// Configure the trigger bindings
configureBindings();
}
/**
* Use this method to define your trigger->command mappings. Triggers can be created via the
* {@link Trigger#Trigger(java.util.function.BooleanSupplier)} constructor with an arbitrary
* predicate, or via the named factories in {@link
* edu.wpi.first.wpilibj2.command.button.CommandGenericHID}'s subclasses for {@link
* CommandXboxController Xbox}/{@link edu.wpi.first.wpilibj2.command.button.CommandPS4Controller
* PS4} controllers or {@link edu.wpi.first.wpilibj2.command.button.CommandJoystick Flight
* joysticks}.
*/
private void configureBindings() {
// Schedule `ExampleCommand` when `exampleCondition` changes to `true`
new Trigger(m_exampleSubsystem::exampleCondition) | .onTrue(new ExampleCommand(m_exampleSubsystem)); | 2 | 2023-12-07 02:36:32+00:00 | 2k |
Viola-Siemens/StellarForge | src/main/java/com/hexagram2021/stellarforge/server/commands/SFCommands.java | [
{
"identifier": "SFCommonConfig",
"path": "src/main/java/com/hexagram2021/stellarforge/common/config/SFCommonConfig.java",
"snippet": "public class SFCommonConfig {\n\tprivate static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n\tprivate static final ForgeConfigSpec SPEC;\n\n\tpublic static final ForgeConfigSpec.BooleanValue ENABLE_REGISTRY_CHECK;\n\tpublic static final ForgeConfigSpec.IntValue COMMAND_PERMISSION;\n\n\tstatic {\n\t\tBUILDER.push(\"stellarforge-common-config\");\n\n\t\tCOMMAND_PERMISSION = BUILDER.comment(\"Permission level for command `/stellarforge`\").defineInRange(\"COMMAND_PERMISSION\", 2, 0, 4);\n\t\tENABLE_REGISTRY_CHECK = BUILDER.comment(\"Enable registry check. This function is good for debugging, especially for developers, server operators, and players who find the game not working. But it takes time to check everytime the game starts. It is recommended for you to run it in game test server.\").define(\"ENABLE_REGISTRY_CHECK\", false);\n\n\t\tBUILDER.pop();\n\n\t\tSPEC = BUILDER.build();\n\t}\n\n\tpublic static ForgeConfigSpec getConfig() {\n\t\treturn SPEC;\n\t}\n}"
},
{
"identifier": "BlockFunction",
"path": "src/main/java/com/hexagram2021/stellarforge/common/function/BlockFunction.java",
"snippet": "public interface BlockFunction {\n\t@Nullable\n\tBlockState transfer(ServerLevel level, BlockPos pos, BlockState state);\n}"
},
{
"identifier": "SFRegistries",
"path": "src/main/java/com/hexagram2021/stellarforge/common/register/SFRegistries.java",
"snippet": "public final class SFRegistries {\n\tpublic static final ResourceKey<Registry<BlockFunction>> BLOCK_FUNCTIONS = ResourceKey.createRegistryKey(new ResourceLocation(MODID, \"block_functions\"));\n\n\tprivate SFRegistries() {\n\t}\n}"
}
] | import com.google.common.collect.Lists;
import com.hexagram2021.stellarforge.common.config.SFCommonConfig;
import com.hexagram2021.stellarforge.common.function.BlockFunction;
import com.hexagram2021.stellarforge.common.register.SFRegistries;
import com.mojang.brigadier.arguments.FloatArgumentType;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import com.mojang.brigadier.exceptions.Dynamic2CommandExceptionType;
import com.mojang.brigadier.exceptions.SimpleCommandExceptionType;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.ResourceKeyArgument;
import net.minecraft.commands.arguments.coordinates.BlockPosArgument;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Holder;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.level.GameRules;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.levelgen.structure.BoundingBox;
import java.util.List;
import java.util.function.Consumer; | 816 | package com.hexagram2021.stellarforge.server.commands;
public final class SFCommands {
@SuppressWarnings("unchecked")
public static LiteralArgumentBuilder<CommandSourceStack> register() {
return Commands.literal("stellarforge").requires(stack -> stack.hasPermission(SFCommonConfig.COMMAND_PERMISSION.get())).then(
Commands.literal("function").then(
Commands.argument("func", ResourceKeyArgument.key(SFRegistries.BLOCK_FUNCTIONS)).then(
Commands.argument("from", BlockPosArgument.blockPos()).then(
Commands.argument("to", BlockPosArgument.blockPos())
.executes(context -> solve(
context.getSource().getLevel(),
BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(context, "from"), BlockPosArgument.getLoadedBlockPos(context, "to")), | package com.hexagram2021.stellarforge.server.commands;
public final class SFCommands {
@SuppressWarnings("unchecked")
public static LiteralArgumentBuilder<CommandSourceStack> register() {
return Commands.literal("stellarforge").requires(stack -> stack.hasPermission(SFCommonConfig.COMMAND_PERMISSION.get())).then(
Commands.literal("function").then(
Commands.argument("func", ResourceKeyArgument.key(SFRegistries.BLOCK_FUNCTIONS)).then(
Commands.argument("from", BlockPosArgument.blockPos()).then(
Commands.argument("to", BlockPosArgument.blockPos())
.executes(context -> solve(
context.getSource().getLevel(),
BoundingBox.fromCorners(BlockPosArgument.getLoadedBlockPos(context, "from"), BlockPosArgument.getLoadedBlockPos(context, "to")), | context.getSource().getServer().registryAccess().lookupOrThrow(SFRegistries.BLOCK_FUNCTIONS).getOrThrow((ResourceKey<BlockFunction>)context.getArgument("func", ResourceKey.class)), | 1 | 2023-12-10 07:20:43+00:00 | 2k |
Yana-Koroliuk/openapi-spring | src/main/java/com/example/openapispring/service/GrantService.java | [
{
"identifier": "Grant",
"path": "src/main/java/com/example/openapispring/entity/Grant.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\n@Table(name = \"grants\")\npublic class Grant {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @ManyToOne\n @JoinColumn(name = \"role_id\", nullable = false)\n private Role role;\n\n @ManyToOne\n @JoinColumn(name = \"permission_id\", nullable = false)\n private Permission permission;\n}"
},
{
"identifier": "Permission",
"path": "src/main/java/com/example/openapispring/entity/Permission.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\n@Table(name = \"permission\")\npublic class Permission {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\", nullable = false)\n private Long id;\n\n @Column(name = \"action\", unique = true)\n private String action;\n\n}"
},
{
"identifier": "Role",
"path": "src/main/java/com/example/openapispring/entity/Role.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@Entity\n@Table(name = \"role\")\npublic class Role {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id\", nullable = false)\n private Long id;\n\n @Column(name = \"name\")\n private String name;\n\n @Column(name = \"description\")\n private String description;\n\n}"
},
{
"identifier": "GrantRepository",
"path": "src/main/java/com/example/openapispring/repository/GrantRepository.java",
"snippet": "public interface GrantRepository extends CrudRepository<Grant, Long> {\n List<Grant> findByRoleId(Long roleId);\n List<Grant> findByPermissionId(Long permissionId);\n Optional<Grant> findByRoleIdAndPermissionId(Long roleId, Long permissionId);\n\n}"
},
{
"identifier": "PermissionRepository",
"path": "src/main/java/com/example/openapispring/repository/PermissionRepository.java",
"snippet": "public interface PermissionRepository extends CrudRepository<Permission, Long> {\n Optional<Permission> findByAction(String action);\n}"
},
{
"identifier": "RoleRepository",
"path": "src/main/java/com/example/openapispring/repository/RoleRepository.java",
"snippet": "@Repository\npublic interface RoleRepository extends CrudRepository<Role, Long> {\n}"
}
] | import com.example.openapispring.entity.Grant;
import com.example.openapispring.entity.Permission;
import com.example.openapispring.entity.Role;
import com.example.openapispring.repository.GrantRepository;
import com.example.openapispring.repository.PermissionRepository;
import com.example.openapispring.repository.RoleRepository;
import dto.GrantDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport; | 656 | package com.example.openapispring.service;
@Service
public class GrantService {
| package com.example.openapispring.service;
@Service
public class GrantService {
| private final GrantRepository grantRepository; | 3 | 2023-12-09 14:37:04+00:00 | 2k |
deepcloudlabs/dcl350-2023-dec-04 | reactive-crm-microservice/src/main/java/com/example/crm/controller/CrmReactiveRestController.java | [
{
"identifier": "CustomerDocument",
"path": "reactive-crm-microservice/src/main/java/com/example/crm/document/CustomerDocument.java",
"snippet": "@Document\n@Data\npublic class CustomerDocument {\n\t@Id\n\tprivate String identity; \n\tprivate String fullname; \n\t@Indexed(unique=true)\n\tprivate String email; \n\tprivate List<Phone> phones; \n\tprivate List<Address> addresses; \n}"
},
{
"identifier": "CrmReactiveService",
"path": "reactive-crm-microservice/src/main/java/com/example/crm/service/CrmReactiveService.java",
"snippet": "@Service\npublic class CrmReactiveService {\n\tprivate final CustomerDocumentRepository customerDocumentRepository;\n\tprivate final ReactiveKafkaProducerTemplate<String, String> reactiveKafkaProducerTemplate;\n\tprivate final ObjectMapper objectMapper;\n\t\n\tpublic CrmReactiveService(CustomerDocumentRepository customerDocumentRepository,\n\t\t\tReactiveKafkaProducerTemplate<String, String> reactiveKafkaProducerTemplate, ObjectMapper objectMapper) {\n\t\tthis.customerDocumentRepository = customerDocumentRepository;\n\t\tthis.reactiveKafkaProducerTemplate = reactiveKafkaProducerTemplate;\n\t\tthis.objectMapper = objectMapper;\n\t}\n\n\tpublic Mono<CustomerDocument> findCustByEmail(String email) {\n\t\treturn customerDocumentRepository.findOneByEmail(email);\n\t}\n\n\tpublic Flux<CustomerDocument> findCustsByPage(int pageNo, int pageSize) {\n\t\treturn customerDocumentRepository.findAll(PageRequest.of(pageNo, pageSize));\n\t}\n\n\tpublic Mono<CustomerDocument> acquireCustomer(CustomerDocument customer) {\n\t\treturn customerDocumentRepository.insert(customer)\n\t\t\t\t .doOnSuccess(\n\t\t\t\t \t\tinsertedCustomer->{\n\t\t\t\t \t\t\ttry {\n\t\t\t\t \t\t\t\tvar event = new CustomerAcquiredEvent(customer.getIdentity());\n\t\t\t\t \t\t\t\tString eventAsJson = objectMapper.writeValueAsString(event);\n\t\t\t\t\t\t\t\t\treactiveKafkaProducerTemplate.send(\"crm-events\", null,eventAsJson).subscribe();\n\t\t\t\t\t\t\t\t} catch (JsonProcessingException e) {\n\t\t\t\t\t\t\t\t\tSystem.err.println(e.getMessage());\n\t\t\t\t\t\t\t\t}\n\t\t\t\t }\n\t\t\t\t );\n\t}\n\n\tpublic Mono<CustomerDocument> releaseCustomer(String email) {\n\t\treturn customerDocumentRepository.findOneByEmail(email)\n\t\t\t .doOnSuccess(\n\t\t\t \t\tfoundCustomer->{\n\t\t\t \t\t\tcustomerDocumentRepository.delete(foundCustomer)\n\t\t\t \t\t\t .doOnSuccess(removedCustomer ->{\n\t\t\t \t\t\t \t try {\n\t\t\t \t\t\t \t\t var event = new CustomerReleasedEvent(foundCustomer.getIdentity());\n\t\t\t \t\t\t \t\t String eventAsJson = objectMapper.writeValueAsString(event);\n\t\t\t \t\t\t \t\t reactiveKafkaProducerTemplate.send(\"crm-events\", null,eventAsJson).subscribe();\n\t\t\t \t\t\t \t } catch (JsonProcessingException e) {\n\t\t\t \t\t\t \t\t System.err.println(e.getMessage());\n\t\t\t \t\t\t \t }\t\t\t \t\t\t \t \n\t\t\t \t\t\t }).subscribe();\n\t\t\t }\n\t\t\t );\n\t}\n\n}"
}
] | 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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.crm.document.CustomerDocument;
import com.example.crm.service.CrmReactiveService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; | 789 | package com.example.crm.controller;
@RestController
@RequestMapping("/customers")
@CrossOrigin
public class CrmReactiveRestController { | package com.example.crm.controller;
@RestController
@RequestMapping("/customers")
@CrossOrigin
public class CrmReactiveRestController { | private final CrmReactiveService crmService; | 1 | 2023-12-05 09:46:09+00:00 | 2k |
nilsgenge/finite-state-machine-visualizer | src/main/Renderer.java | [
{
"identifier": "Settings",
"path": "src/utilz/Settings.java",
"snippet": "public enum Settings {\n\t//SETTINGS\n\tPRINT_PERFORMANCE_UPDATES(false),\n\tENABLE_DOUBLE_BUFFERING(false);\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\tprivate final Boolean value;\n\t\n\tSettings(Boolean value) {\n this.value = value;\n }\n\t\n\tpublic Boolean getValue() {\n return value;\n }\n}"
},
{
"identifier": "colortable",
"path": "src/utilz/colortable.java",
"snippet": "public class colortable {\n\n\tprivate static final String HEX_BG_MAIN = \"#fffffe\";\n\tprivate static final String HEX_BG_MENU = \"#eff0f3\";\n\tprivate static final String HEX_STROKE = \"#1f1235\";\n\tprivate static final String HEX_HIGHLIGHT = \"#ff8e3c\";\n\tprivate static final String HEX_TEXT = \"#1f1135\";\n\tprivate static final String HEX_SUBTEXT = \"#1b1325\";\n\n\tpublic static final Color BG_MAIN = new Color(colortable.hexToRGB(HEX_BG_MAIN));\n\tpublic static final Color BG_MENU = new Color(colortable.hexToRGB(HEX_BG_MENU));\n\tpublic static final Color STROKE = new Color(colortable.hexToRGB(HEX_STROKE));\n\tpublic static final Color HIGHLIGHT = new Color(colortable.hexToRGB(HEX_HIGHLIGHT));\n\tpublic static final Color TEXT = new Color(colortable.hexToRGB(HEX_TEXT));\n\tpublic static final Color SUBTEXT = new Color(colortable.hexToRGB(HEX_SUBTEXT));\n\n\tprivate static int hexToRGB(String hex) {\n\t\tlong a = Long.decode(hex) + 4278190080L;\n\t\tint rgbColor = (int) a;\n\t\treturn rgbColor;\n\t}\n}"
}
] | import java.awt.*;
import java.awt.image.VolatileImage;
import javax.swing.JPanel;
import gui.*;
import utilz.Settings;
import utilz.colortable;
import workspace.*; | 731 | package main;
public class Renderer extends JPanel {
Main main;
ObjectHandler oh;
GuiHandler gui;
private final int FPS_SET = 60;
private int UPS_SET = 60;
VolatileImage offScreenBuffer;
public Renderer(Main main) {
this.main = main;
}
public void runCycle() {
this.oh = main.oh;
this.gui = main.g;
double timePerFrame = 1000000000 / FPS_SET;
double timePerUpdate = 1000000000 / UPS_SET;
long previousTime = System.nanoTime();
int updates = 0;
int frames = 0;
long lastCheck = System.currentTimeMillis();
double deltaU = 0;
double deltaF = 0;
while (true) {
long currentTime = System.nanoTime();
deltaU += (currentTime - previousTime) / timePerUpdate;
deltaF += (currentTime - previousTime) / timePerFrame;
previousTime = currentTime;
if (deltaU >= 1) {
update();
updates++;
deltaU--;
}
if (deltaF >= 1) {
repaint();
frames++;
deltaF--;
}
if (System.currentTimeMillis() - lastCheck >= 1000) {
lastCheck = System.currentTimeMillis(); | package main;
public class Renderer extends JPanel {
Main main;
ObjectHandler oh;
GuiHandler gui;
private final int FPS_SET = 60;
private int UPS_SET = 60;
VolatileImage offScreenBuffer;
public Renderer(Main main) {
this.main = main;
}
public void runCycle() {
this.oh = main.oh;
this.gui = main.g;
double timePerFrame = 1000000000 / FPS_SET;
double timePerUpdate = 1000000000 / UPS_SET;
long previousTime = System.nanoTime();
int updates = 0;
int frames = 0;
long lastCheck = System.currentTimeMillis();
double deltaU = 0;
double deltaF = 0;
while (true) {
long currentTime = System.nanoTime();
deltaU += (currentTime - previousTime) / timePerUpdate;
deltaF += (currentTime - previousTime) / timePerFrame;
previousTime = currentTime;
if (deltaU >= 1) {
update();
updates++;
deltaU--;
}
if (deltaF >= 1) {
repaint();
frames++;
deltaF--;
}
if (System.currentTimeMillis() - lastCheck >= 1000) {
lastCheck = System.currentTimeMillis(); | if (Settings.PRINT_PERFORMANCE_UPDATES.getValue()) { | 0 | 2023-12-12 20:43:41+00:00 | 2k |
CompeyDev/touch-grass-reminder | src/main/java/xyz/devcomp/touch_grass_reminder/client/TouchGrassReminderClient.java | [
{
"identifier": "ConfigModel",
"path": "src/main/java/xyz/devcomp/touch_grass_reminder/config/ConfigModel.java",
"snippet": "public class ConfigModel {\n @SerialEntry(comment = \"Whether the mod's functionality is enabled\")\n @AutoGen(category = \"touch_grass_reminder\")\n @TickBox\n public boolean isEnabled = true;\n\n @SerialEntry(comment = \"Number of hours the reminder should be displayed after\")\n @AutoGen(category = \"touch_grass_reminder\")\n @IntField(min = 1)\n public int reminderFrequency = 24;\n}"
},
{
"identifier": "PlayDurationHandler",
"path": "src/main/java/xyz/devcomp/touch_grass_reminder/utils/PlayDurationHandler.java",
"snippet": "public class PlayDurationHandler implements Runnable {\n Minecraft client;\n SystemToast toast;\n long startTime;\n int reminderFrequency; // In milliseconds, converted in onInitializeClient\n\n public PlayDurationHandler(Minecraft client, long startTime, int reminderFrequency) {\n this.client = client;\n this.startTime = startTime;\n this.reminderFrequency = reminderFrequency;\n\n this.toast = new SystemToast(SystemToastIds.TUTORIAL_HINT,\n Component.translatable(\"touch_grass_reminder.toast.name\", reminderFrequency),\n Component.translatable(\"touch_grass_reminder.toast.description\"));\n }\n\n @Override\n public void run() {\n TouchGrassReminderClient.LOGGER.info(\"Started playing Minecraft at: {}\", this.startTime);\n\n while (true) {\n if (System.currentTimeMillis() - this.startTime > this.reminderFrequency) {\n TouchGrassReminderClient.LOGGER\n .info(\"Player has spent more than 24 hours in Minecraft. Displaying reminder.\");\n\n this.client.getToasts().addToast(toast);\n return;\n }\n\n try {\n // Recheck every 10 minutes\n Thread.sleep(10 * 60 * 1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n }\n\n}"
}
] | import java.util.UUID;
import xyz.devcomp.touch_grass_reminder.config.ConfigModel;
import xyz.devcomp.touch_grass_reminder.utils.PlayDurationHandler;
import net.minecraft.client.multiplayer.ServerData;
import org.quiltmc.loader.api.ModContainer;
import org.quiltmc.qsl.base.api.entrypoint.client.ClientModInitializer;
import org.quiltmc.qsl.networking.api.client.ClientPlayConnectionEvents;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 788 | package xyz.devcomp.touch_grass_reminder.client;
public class TouchGrassReminderClient implements ClientModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("Touch Grass Reminder");
private ConfigModel config = new ConfigModel();
private Thread thread;
@Override
public void onInitializeClient(ModContainer mod) {
LOGGER.info("Touch Grass reminder init; isEnabled={}, reminderFrequency={}h", config.isEnabled,
config.reminderFrequency);
LOGGER.info("Registering JOIN & DISCONNECT events...");
if (config.isEnabled) {
ClientPlayConnectionEvents.JOIN.register((net, packet, client) -> {
UUID sessionId = net.getId();
ServerData serverInfo = net.getServerData() == null ? new ServerData("Unknown", "Unknown", false)
: net.getServerData();
LOGGER.info(
"Player initiated connection; sessionId={}, name={}, version={}, protocolVersion={}, isLocal={}",
sessionId, serverInfo.name, serverInfo.version, serverInfo.protocol, serverInfo.isLan());
| package xyz.devcomp.touch_grass_reminder.client;
public class TouchGrassReminderClient implements ClientModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("Touch Grass Reminder");
private ConfigModel config = new ConfigModel();
private Thread thread;
@Override
public void onInitializeClient(ModContainer mod) {
LOGGER.info("Touch Grass reminder init; isEnabled={}, reminderFrequency={}h", config.isEnabled,
config.reminderFrequency);
LOGGER.info("Registering JOIN & DISCONNECT events...");
if (config.isEnabled) {
ClientPlayConnectionEvents.JOIN.register((net, packet, client) -> {
UUID sessionId = net.getId();
ServerData serverInfo = net.getServerData() == null ? new ServerData("Unknown", "Unknown", false)
: net.getServerData();
LOGGER.info(
"Player initiated connection; sessionId={}, name={}, version={}, protocolVersion={}, isLocal={}",
sessionId, serverInfo.name, serverInfo.version, serverInfo.protocol, serverInfo.isLan());
| PlayDurationHandler worker = new PlayDurationHandler(client, System.currentTimeMillis(), | 1 | 2023-12-07 18:06:36+00:00 | 2k |
gaetanBloch/jhlite-gateway | src/test/java/com/mycompany/myapp/shared/pagination/domain/JhipsterSampleApplicationPageableTest.java | [
{
"identifier": "NumberValueTooHighException",
"path": "src/main/java/com/mycompany/myapp/shared/error/domain/NumberValueTooHighException.java",
"snippet": "public class NumberValueTooHighException extends AssertionException {\n\n private final String max;\n private final String value;\n\n private NumberValueTooHighException(NumberValueTooHighExceptionBuilder builder) {\n super(builder.field, builder.message());\n max = builder.maxValue;\n value = builder.value;\n }\n\n public static NumberValueTooHighExceptionBuilder builder() {\n return new NumberValueTooHighExceptionBuilder();\n }\n\n public static class NumberValueTooHighExceptionBuilder {\n\n private String field;\n private String maxValue;\n private String value;\n\n public NumberValueTooHighExceptionBuilder field(String field) {\n this.field = field;\n\n return this;\n }\n\n public NumberValueTooHighExceptionBuilder maxValue(String maxValue) {\n this.maxValue = maxValue;\n\n return this;\n }\n\n public NumberValueTooHighExceptionBuilder value(String value) {\n this.value = value;\n\n return this;\n }\n\n public String message() {\n return new StringBuilder()\n .append(\"Value of field \\\"\")\n .append(field)\n .append(\"\\\" must be at most \")\n .append(maxValue)\n .append(\" but was \")\n .append(value)\n .toString();\n }\n\n public NumberValueTooHighException build() {\n return new NumberValueTooHighException(this);\n }\n }\n\n @Override\n public AssertionErrorType type() {\n return AssertionErrorType.NUMBER_VALUE_TOO_HIGH;\n }\n\n @Override\n public Map<String, String> parameters() {\n return Map.of(\"max\", max, \"value\", value);\n }\n}"
},
{
"identifier": "NumberValueTooLowException",
"path": "src/main/java/com/mycompany/myapp/shared/error/domain/NumberValueTooLowException.java",
"snippet": "public class NumberValueTooLowException extends AssertionException {\n\n private final String min;\n private final String value;\n\n private NumberValueTooLowException(NumberValueTooLowExceptionBuilder builder) {\n super(builder.field, builder.message());\n min = builder.minValue;\n value = builder.value;\n }\n\n public static NumberValueTooLowExceptionBuilder builder() {\n return new NumberValueTooLowExceptionBuilder();\n }\n\n public static class NumberValueTooLowExceptionBuilder {\n\n private String field;\n private String minValue;\n private String value;\n\n public NumberValueTooLowExceptionBuilder field(String field) {\n this.field = field;\n\n return this;\n }\n\n public NumberValueTooLowExceptionBuilder minValue(String minValue) {\n this.minValue = minValue;\n\n return this;\n }\n\n public NumberValueTooLowExceptionBuilder value(String value) {\n this.value = value;\n\n return this;\n }\n\n public String message() {\n return new StringBuilder()\n .append(\"Value of field \\\"\")\n .append(field)\n .append(\"\\\" must be at least \")\n .append(minValue)\n .append(\" but was \")\n .append(value)\n .toString();\n }\n\n public NumberValueTooLowException build() {\n return new NumberValueTooLowException(this);\n }\n }\n\n @Override\n public AssertionErrorType type() {\n return AssertionErrorType.NUMBER_VALUE_TOO_LOW;\n }\n\n @Override\n public Map<String, String> parameters() {\n return Map.of(\"min\", min, \"value\", value);\n }\n}"
}
] | import static org.assertj.core.api.Assertions.*;
import org.junit.jupiter.api.Test;
import com.mycompany.myapp.UnitTest;
import com.mycompany.myapp.shared.error.domain.NumberValueTooHighException;
import com.mycompany.myapp.shared.error.domain.NumberValueTooLowException; | 1,098 | package com.mycompany.myapp.shared.pagination.domain;
@UnitTest
class JhipsterSampleApplicationPageableTest {
@Test
void shouldNotBuildWithNegativePage() {
assertThatThrownBy(() -> new JhipsterSampleApplicationPageable(-1, 10))
.isExactlyInstanceOf(NumberValueTooLowException.class)
.hasMessageContaining("page");
}
@Test
void shouldNotBuildWithPageSizeAtZero() {
assertThatThrownBy(() -> new JhipsterSampleApplicationPageable(0, 0))
.isExactlyInstanceOf(NumberValueTooLowException.class)
.hasMessageContaining("pageSize");
}
@Test
void shouldNotBuildWithPageSizeOverHundred() {
assertThatThrownBy(() -> new JhipsterSampleApplicationPageable(0, 101)) | package com.mycompany.myapp.shared.pagination.domain;
@UnitTest
class JhipsterSampleApplicationPageableTest {
@Test
void shouldNotBuildWithNegativePage() {
assertThatThrownBy(() -> new JhipsterSampleApplicationPageable(-1, 10))
.isExactlyInstanceOf(NumberValueTooLowException.class)
.hasMessageContaining("page");
}
@Test
void shouldNotBuildWithPageSizeAtZero() {
assertThatThrownBy(() -> new JhipsterSampleApplicationPageable(0, 0))
.isExactlyInstanceOf(NumberValueTooLowException.class)
.hasMessageContaining("pageSize");
}
@Test
void shouldNotBuildWithPageSizeOverHundred() {
assertThatThrownBy(() -> new JhipsterSampleApplicationPageable(0, 101)) | .isExactlyInstanceOf(NumberValueTooHighException.class) | 0 | 2023-12-10 06:39:18+00:00 | 2k |
maykon/myfood | core/src/main/java/com/myfood/services/CompanyService.java | [
{
"identifier": "Company",
"path": "core/src/main/java/com/myfood/domain/company/Company.java",
"snippet": "@Entity\n@Table(name = \"companies\")\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@EqualsAndHashCode(of = \"id\")\npublic class Company {\n @Id\n @GeneratedValue(strategy = GenerationType.UUID)\n private UUID id;\n private String name;\n private String address;\n private String phone;\n private String cnpj;\n @Enumerated(EnumType.STRING)\n private FoodCategory category;\n private Integer distance;\n private Integer rating;\n private String description;\n private Boolean opened;\n private Boolean active;\n @CreationTimestamp\n private Instant createdAt;\n @UpdateTimestamp\n private Instant updatedAt;\n\n public Company(String name, String address, String phone, String cnpj, FoodCategory category, String description) {\n this.name = name;\n this.address = address;\n this.phone = phone;\n this.cnpj = cnpj;\n this.category = category;\n this.description = description;\n this.active = true;\n this.opened = false;\n this.rating = 5;\n this.distance = (int) (Math.random() * 10_000) + 1_000;\n }\n\n public Company update(CompanyDTO dto) {\n this.name = dto.name();\n this.address = dto.address();\n this.phone = dto.phone();\n this.cnpj = dto.cnpj();\n this.category = dto.category();\n this.description = dto.description();\n return this;\n }\n\n public CompanyDTO toDTO() {\n return new CompanyDTO(getId(), getName(), getAddress(), getPhone(), getCnpj(), getCategory(), getDescription(),\n getDistance(), getRating(), getOpened(), getCreatedAt()\n );\n }\n}"
},
{
"identifier": "UserRole",
"path": "core/src/main/java/com/myfood/domain/user/UserRole.java",
"snippet": "public enum UserRole {\n ADMIN,\n USER,\n MERCHANT\n}"
},
{
"identifier": "CompanyRepository",
"path": "core/src/main/java/com/myfood/repositories/CompanyRepository.java",
"snippet": "@Repository\npublic interface CompanyRepository extends JpaRepository<Company, UUID> {\n @Query(\"\"\"\n SELECT new com.myfood.domain.company.CompanyListDTO(c.id, c.name, c.address, c.phone, c.category,\n c.description, c.opened) FROM Company c WHERE c.active = true\"\"\")\n List<CompanyListDTO> findAllCompanies();\n\n @Query(\"\"\"\n SELECT new com.myfood.domain.company.CompanyDTO(c.id, c.name, c.address, c.phone, c.cnpj, c.category,\n c.description, c.distance, c.rating, c.opened, c.createdAt) FROM Company c WHERE c.active = true and id =:id\"\"\")\n Optional<CompanyDTO> findCompanyById(@Param(\"id\") UUID id);\n\n Optional<Company> findByIdAndActiveTrue(UUID id);\n\n @Modifying\n @Query(\"UPDATE Company c SET c.opened = ?2 WHERE c.id IN ?1\")\n void openCompany(UUID id, Boolean opened);\n\n @Modifying\n @Query(\"UPDATE Company c SET c.active = ?2 WHERE c.id IN ?1\")\n void activeCompany(UUID id, Boolean active);\n}"
}
] | import com.myfood.domain.company.Company;
import com.myfood.domain.company.CompanyDTO;
import com.myfood.domain.company.CompanyListDTO;
import com.myfood.domain.company.CompanyRegisterDTO;
import com.myfood.domain.user.UserRegisterDTO;
import com.myfood.domain.user.UserRole;
import com.myfood.repositories.CompanyRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.UUID; | 940 | package com.myfood.services;
@Service
public class CompanyService {
@Autowired
private UserService userService;
@Autowired
private CompanyRepository repository;
@Transactional
public CompanyDTO register(CompanyRegisterDTO data) {
var newCompany = new Company(data.name(), data.address(), data.phone(), data.cnpj(), data.category(), data.description());
var createdCompany = repository.save(newCompany);
repository.flush(); | package com.myfood.services;
@Service
public class CompanyService {
@Autowired
private UserService userService;
@Autowired
private CompanyRepository repository;
@Transactional
public CompanyDTO register(CompanyRegisterDTO data) {
var newCompany = new Company(data.name(), data.address(), data.phone(), data.cnpj(), data.category(), data.description());
var createdCompany = repository.save(newCompany);
repository.flush(); | userService.register(new UserRegisterDTO(data.name(), data.email(), data.password(), UserRole.MERCHANT), createdCompany.getId()); | 1 | 2023-12-11 21:55:26+00:00 | 2k |
zerodevstuff/ExploitFixerv2 | src/main/java/dev/_2lstudios/exploitfixer/modules/PacketsModule.java | [
{
"identifier": "IConfiguration",
"path": "src/main/java/dev/_2lstudios/exploitfixer/configuration/IConfiguration.java",
"snippet": "public interface IConfiguration {\n public IConfiguration getSection(String string);\n\n public Collection<String> getKeys();\n\n public Collection<String> getStringList(String string);\n\n public String getString(String path);\n\n public String getString(String path, String def);\n\n public double getDouble(String path);\n\n public double getDouble(String path, double def);\n\n public long getLong(String path);\n\n public int getInt(String path);\n\n public boolean getBoolean(String path);\n\n public boolean getBoolean(String path, boolean def);\n\n public Object getObject();\n\n public boolean contains(String string);\n}"
},
{
"identifier": "Violations",
"path": "src/main/java/dev/_2lstudios/exploitfixer/exploit/Violations.java",
"snippet": "public class Violations {\n\tprivate Map<Integer, Collection<String>> violations = new HashMap<>();\n\n\tpublic Violations(IConfiguration configuration) {\n\t\tif (configuration != null) {\n\t\t\tfor (String key : configuration.getKeys()) {\n\t\t\t\ttry {\n\t\t\t\t\tthis.violations.put(Integer.parseInt(key), configuration.getStringList(key));\n\t\t\t\t} catch (NumberFormatException ignored) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic Collection<String> getCommands(int violations) {\n\t\treturn this.violations.getOrDefault(violations, null);\n\t}\n\n\tpublic Collection<Integer> getViolations() {\n\t\treturn violations.keySet();\n\t}\n}"
},
{
"identifier": "ViolationModule",
"path": "src/main/java/dev/_2lstudios/exploitfixer/modules/interfaces/ViolationModule.java",
"snippet": "public abstract class ViolationModule extends Module {\n private double cancelVls; // The amount of vls to start cancelling\n private double reduceVls; // The amount of vls to reduce each second\n private Violations violations;\n\n\tpublic Violations getViolations() {\n\t\treturn violations;\n\t}\n\n public double getCancelVls() {\n return cancelVls;\n }\n\n public void setCancelVls(double cancelVls) {\n this.cancelVls = cancelVls;\n }\n\n public double getReduceVls() {\n return reduceVls;\n }\n\n public void setReduceVls(double reduceVls) {\n this.reduceVls = reduceVls;\n }\n\n public void setViolations(Violations violations) {\n this.violations = violations;\n }\n}"
}
] | import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import dev._2lstudios.exploitfixer.configuration.IConfiguration;
import dev._2lstudios.exploitfixer.exploit.Violations;
import dev._2lstudios.exploitfixer.modules.interfaces.ViolationModule; | 866 | package dev._2lstudios.exploitfixer.modules;
public class PacketsModule extends ViolationModule {
private Map<String, Double> rateMultipliers = new HashMap<>();
private Collection<String> blacklist = new HashSet<>();
private double dataVls, bookVls, tagVls, blockDigVls, blockPlaceVls, setCreativeSlot, windowClick, byteMultiplier;
private int dataMaxSizeBook, dataMaxSizeSign, dataMaxSize, dataMaxFlags, dataMaxFireworkFlags;
private String bypassPermission;
public void reload(IConfiguration configYml) {
setName("Packets");
String name = getName().toLowerCase();
IConfiguration rateMultipliersSection = configYml.getSection(name + ".rate_multipliers");
setEnabled(configYml.getBoolean(name + ".enabled"));
setCancelVls(configYml.getDouble(name + ".cancel_vls"));
setReduceVls(configYml.getDouble(name + ".reduce_vls")); | package dev._2lstudios.exploitfixer.modules;
public class PacketsModule extends ViolationModule {
private Map<String, Double> rateMultipliers = new HashMap<>();
private Collection<String> blacklist = new HashSet<>();
private double dataVls, bookVls, tagVls, blockDigVls, blockPlaceVls, setCreativeSlot, windowClick, byteMultiplier;
private int dataMaxSizeBook, dataMaxSizeSign, dataMaxSize, dataMaxFlags, dataMaxFireworkFlags;
private String bypassPermission;
public void reload(IConfiguration configYml) {
setName("Packets");
String name = getName().toLowerCase();
IConfiguration rateMultipliersSection = configYml.getSection(name + ".rate_multipliers");
setEnabled(configYml.getBoolean(name + ".enabled"));
setCancelVls(configYml.getDouble(name + ".cancel_vls"));
setReduceVls(configYml.getDouble(name + ".reduce_vls")); | setViolations(new Violations(configYml.getSection(name + ".violations"))); | 1 | 2023-12-13 21:49:27+00:00 | 2k |
12manel123/mcc-tsys-ex2-c4-051223 | Ex02/src/main/java/com/ex02/controller/MensajeController.java | [
{
"identifier": "Mensaje",
"path": "Ex02/src/main/java/com/ex02/dto/Mensaje.java",
"snippet": "@Entity\r\npublic class Mensaje {\r\n\t@Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n private Long id;\r\n private String contenido;\r\n private String nombreUsuarioCreador;\r\n \r\n @ManyToOne\r\n\t@JoinColumn(name = \"partida_id\")\r\n\tprivate Partida partida;\r\n \r\n\tpublic Long getId() {\r\n\t\treturn id;\r\n\t}\r\n\tpublic void setId(Long id) {\r\n\t\tthis.id = id;\r\n\t}\r\n\tpublic String getContenido() {\r\n\t\treturn contenido;\r\n\t}\r\n\tpublic void setContenido(String contenido) {\r\n\t\tthis.contenido = contenido;\r\n\t}\r\n\tpublic String getNombreUsuarioCreador() {\r\n\t\treturn nombreUsuarioCreador;\r\n\t}\r\n\tpublic void setNombreUsuarioCreador(String nombreUsuarioCreador) {\r\n\t\tthis.nombreUsuarioCreador = nombreUsuarioCreador;\r\n\t}\r\n\tpublic Mensaje(Long id, String contenido, String nombreUsuarioCreador) {\r\n\t\tsuper();\r\n\t\tthis.id = id;\r\n\t\tthis.contenido = contenido;\r\n\t\tthis.nombreUsuarioCreador = nombreUsuarioCreador;\r\n\t}\r\n\tpublic Mensaje() {\r\n\t\tsuper();\r\n\t}\r\n\tpublic Partida getPartida() {\r\n\t\treturn partida;\r\n\t}\r\n\tpublic void setPartida(Partida partida) {\r\n\t\tthis.partida = partida;\r\n\t}\r\n\t\r\n \r\n \r\n}\r"
},
{
"identifier": "Partida",
"path": "Ex02/src/main/java/com/ex02/dto/Partida.java",
"snippet": "@Entity\r\npublic class Partida {\r\n @Id\r\n private String nombre;\r\n private String descripcion;\r\n private int jugadores;\r\n private String plataforma;\r\n private Date fechaInicio;\r\n private String videojuego;\r\n \r\n @OneToMany(mappedBy = \"partida\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)\r\n @JsonIgnore\r\n private List<Mensaje> mensajes;\r\n \r\n public Partida() {\r\n }\r\n \r\n \r\n\r\n public List<Mensaje> getMensajes() {\r\n\t\treturn mensajes;\r\n\t}\r\n\r\n\r\n\r\n\tpublic void setMensajes(List<Mensaje> mensajes) {\r\n\t\tthis.mensajes = mensajes;\r\n\t}\r\n\r\n\r\n\r\n\tpublic Partida(String nombre, String descripcion, int jugadores, String plataforma, Date fechaInicio, String videojuego) {\r\n this.nombre = nombre;\r\n this.descripcion = descripcion;\r\n this.jugadores = jugadores;\r\n this.plataforma = plataforma;\r\n this.fechaInicio = fechaInicio;\r\n this.videojuego = videojuego;\r\n }\r\n public String getVideojuego() {\r\n return videojuego;\r\n }\r\n\r\n public void setVideojuego(String videojuego) {\r\n this.videojuego = videojuego;\r\n }\r\n public String getNombre() {\r\n return nombre;\r\n }\r\n\r\n public void setNombre(String nombre) {\r\n this.nombre = nombre;\r\n }\r\n\r\n public String getDescripcion() {\r\n return descripcion;\r\n }\r\n\r\n public void setDescripcion(String descripcion) {\r\n this.descripcion = descripcion;\r\n }\r\n\r\n public int getJugadores() {\r\n return jugadores;\r\n }\r\n\r\n public void setJugadores(int jugadores) {\r\n this.jugadores = jugadores;\r\n }\r\n\r\n public String getPlataforma() {\r\n return plataforma;\r\n }\r\n\r\n public void setPlataforma(String plataforma) {\r\n this.plataforma = plataforma;\r\n }\r\n\r\n public Date getFechaInicio() {\r\n return fechaInicio;\r\n }\r\n\r\n public void setFechaInicio(Date fechaInicio) {\r\n this.fechaInicio = fechaInicio;\r\n }\r\n}\r"
},
{
"identifier": "MensajeService",
"path": "Ex02/src/main/java/com/ex02/service/MensajeService.java",
"snippet": "@Service\r\npublic class MensajeService implements IMensajeService {\r\n private final IMensajeDAO mensajeDAO;\r\n\r\n public MensajeService(IMensajeDAO mensajeDAO) {\r\n this.mensajeDAO = mensajeDAO;\r\n }\r\n\r\n public void crearMensaje(Mensaje mensaje) {\r\n mensajeDAO.save(mensaje);\r\n }\r\n\r\n public void eliminarMensaje(Long idMensaje) {\r\n mensajeDAO.deleteById(idMensaje);\r\n }\r\n\r\n public List<Mensaje> verTodosLosMensajes(String nombreSala) {\r\n return mensajeDAO.findAll();\r\n }\r\n public void editarMensaje(Long idMensaje, Mensaje mensajeActualizado) {\r\n Mensaje mensajeExistente = mensajeDAO.findById(idMensaje).orElse(null);\r\n if (mensajeExistente != null) {\r\n mensajeExistente.setContenido(mensajeActualizado.getContenido());\r\n mensajeExistente.setNombreUsuarioCreador(mensajeActualizado.getNombreUsuarioCreador());\r\n mensajeDAO.save(mensajeExistente);\r\n }\r\n }\r\n\r\n}"
},
{
"identifier": "PartidaService",
"path": "Ex02/src/main/java/com/ex02/service/PartidaService.java",
"snippet": "@Service\r\npublic class PartidaService implements IPartidaService {\r\n\r\n private final IPartidaDAO partidaDAO;\r\n\r\n public PartidaService(IPartidaDAO partidaDAO) {\r\n this.partidaDAO = partidaDAO;\r\n }\r\n\r\n @Override\r\n public void crearPartida(Partida partida) {\r\n partidaDAO.save(partida);\r\n }\r\n \r\n public List<Partida> buscarPartidasPorVideojuego(String videojuego) {\r\n return partidaDAO.findByVideojuego(videojuego);\r\n }\r\n\r\n @Override\r\n public void unirseAPartida(String nombrePartida) {\r\n Partida partida = partidaDAO.findById(nombrePartida).orElse(null);\r\n if (partida != null) {\r\n partida.setJugadores(partida.getJugadores()+1);\r\n partidaDAO.save(partida);\r\n }\r\n }\r\n\r\n @Override\r\n public void salirDePartida(String nombrePartida) {\r\n Partida partida = partidaDAO.findById(nombrePartida).orElse(null);\r\n partida.setJugadores(partida.getJugadores()-1);\r\n partidaDAO.save(partida);\r\n \r\n }\r\n \r\n}"
}
] | import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ex02.dto.Mensaje;
import com.ex02.dto.Partida;
import com.ex02.service.MensajeService;
import com.ex02.service.PartidaService;
import jakarta.transaction.Transactional;
| 1,600 | package com.ex02.controller;
@RestController
@RequestMapping("ex2/mensaje")
public class MensajeController {
private final MensajeService mensajeService;
public MensajeController(MensajeService mensajeService) {
this.mensajeService = mensajeService;
}
@PostMapping("/crear")
| package com.ex02.controller;
@RestController
@RequestMapping("ex2/mensaje")
public class MensajeController {
private final MensajeService mensajeService;
public MensajeController(MensajeService mensajeService) {
this.mensajeService = mensajeService;
}
@PostMapping("/crear")
| public ResponseEntity<String> crearMensaje(@RequestBody Mensaje mensaje) {
| 0 | 2023-12-05 15:39:34+00:00 | 2k |
xIdentified/TavernBard | src/main/java/me/xidentified/tavernbard/managers/QueueManager.java | [
{
"identifier": "Song",
"path": "src/main/java/me/xidentified/tavernbard/Song.java",
"snippet": "public class Song {\n protected final String namespace;\n protected final String name;\n protected final String displayName;\n protected final String artist;\n protected final int duration;\n protected final UUID addedByUUID;\n\n public Song(String namespace, String name, String displayName, String artist, int duration, UUID addedByUUID) {\n this.namespace = namespace;\n this.name = name;\n this.displayName = displayName;\n this.artist = artist;\n this.duration = duration;\n this.addedByUUID = addedByUUID;\n }\n\n public Song(String namespace, String name, String displayName, String artist, int duration) {\n this(namespace, name, displayName, artist, duration, null);\n }\n\n public String getAddedByName() {\n if (addedByUUID == null) return \"Unknown Player\";\n return Bukkit.getOfflinePlayer(addedByUUID).getName();\n }\n\n public UUID getAddedByUUID() {\n return addedByUUID;\n }\n\n public String getSoundReference() {\n return namespace + \":\" + name;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public String getArtist() {\n return artist;\n }\n\n public int getDuration() {\n return duration;\n }\n\n public String getName() {\n return name;\n }\n\n public String getNamespace() {\n return namespace;\n }\n}"
},
{
"identifier": "TavernBard",
"path": "src/main/java/me/xidentified/tavernbard/TavernBard.java",
"snippet": "public final class TavernBard extends JavaPlugin {\n\n private SongManager songManager;\n private MessageUtil messageUtil;\n private CooldownManager cooldownManager;\n\n @Override\n public void onEnable() {\n boolean citizensFound = getServer().getPluginManager().isPluginEnabled(\"Citizens\");\n boolean mythicMobsFound = Bukkit.getPluginManager().isPluginEnabled(\"MythicMobs\");\n\n // Check if neither Citizens nor MythicMobs is enabled\n if (!citizensFound && !mythicMobsFound) {\n getLogger().log(Level.SEVERE, \"Neither Citizens nor MythicMobs found. At least one is required for the plugin to work!\");\n getServer().getPluginManager().disablePlugin(this);\n return;\n }\n\n // Check if Citizens is enabled and register bard trait\n if (citizensFound) {\n // Check if trait is already registered\n if (CitizensAPI.getTraitFactory().getTrait(\"bard\") == null) {\n CitizensAPI.getTraitFactory().registerTrait(net.citizensnpcs.api.trait.TraitInfo.create(BardTrait.class).withName(\"bard\"));\n getLogger().info(\"Bard trait registered with Citizens.\");\n }\n }\n\n if (mythicMobsFound) {\n getServer().getPluginManager().registerEvents(new MythicMobInteractListener(this), this);\n getLogger().info(\"MythicMobs detected. Support enabled!\");\n }\n\n // Load default config if missing and saved plugin configuration\n saveDefaultConfig();\n reloadConfig();\n\n // Initialize SongManager, QueueManager, and MessageUtil classes\n this.messageUtil = new MessageUtil(getConfig());\n cooldownManager = new CooldownManager();\n songManager = new SongManager(this);\n QueueManager queueManager = new QueueManager(this, songManager, cooldownManager);\n\n // Initialize and register listeners\n GUIListener GUIListener = new GUIListener(this, songManager);\n getServer().getPluginManager().registerEvents(GUIListener, this);\n\n ResourcePackListener resourcePackListener = new ResourcePackListener(this);\n getServer().getPluginManager().registerEvents(resourcePackListener, this);\n\n CitizensInteractListener citizensInteractListener = new CitizensInteractListener(this);\n getServer().getPluginManager().registerEvents(citizensInteractListener, this);\n\n // Register commands\n Objects.requireNonNull(this.getCommand(\"bard\")).setExecutor(new CommandHandler(songManager, queueManager));\n\n }\n\n public void handleInteraction(UUID bardEntityId, Player player) {\n debugLog(\"handleInteraction method fired\");\n\n SongSelectionGUI gui = new SongSelectionGUI(this, getSongManager(), bardEntityId);\n player.openInventory(gui.getInventory());\n\n if (!getSongManager().bardNpcs.containsKey(bardEntityId)) {\n debugLog(\"Adding entity with ID: \" + bardEntityId);\n if (bardEntityId != null) {\n getSongManager().bardNpcs.put(bardEntityId, player.getUniqueId());\n }\n } else {\n debugLog(\"Entity with ID: \" + bardEntityId + \" already added.\");\n }\n }\n\n // Get entity from UUID to check if it's a bard or not\n public Entity getEntityFromUUID(World world, UUID uuid) {\n for (Entity entity : world.getEntities()) {\n if (entity.getUniqueId().equals(uuid)) {\n return entity;\n }\n }\n return null;\n }\n\n\n // Plugin shutdown logic\n @Override\n public void onDisable() {\n // Unregister the bard trait\n if (CitizensAPI.hasImplementation()) {\n CitizensAPI.getTraitFactory().deregisterTrait(net.citizensnpcs.api.trait.TraitInfo.create(BardTrait.class));\n }\n\n // Unregister listeners\n HandlerList.unregisterAll();\n\n // Cancel all tasks\n Bukkit.getScheduler().cancelTasks(this);\n\n }\n\n // Getter methods\n public SongManager getSongManager() {\n return songManager;\n }\n\n public MessageUtil getMessageUtil() {\n return messageUtil;\n }\n\n public CooldownManager getCooldownManager() {\n return cooldownManager;\n }\n\n public void debugLog(String message) {\n if (getConfig().getBoolean(\"debug_mode\", false)) {\n getLogger().info(\"[DEBUG] \" + message);\n }\n }\n\n}"
}
] | import me.xidentified.tavernbard.Song;
import me.xidentified.tavernbard.TavernBard;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import java.util.concurrent.TimeUnit; | 1,522 | package me.xidentified.tavernbard.managers;
public class QueueManager {
private final SongManager songManager;
private final CooldownManager cooldownManager; | package me.xidentified.tavernbard.managers;
public class QueueManager {
private final SongManager songManager;
private final CooldownManager cooldownManager; | private final Map<UUID, Queue<Song>> npcSongQueues = new HashMap<>(); | 0 | 2023-12-06 06:00:57+00:00 | 2k |
connect-ankit/contact-directory | contact-service/src/main/java/com/inn/assignment/task2/controller/Impl/ContactControllerImpl.java | [
{
"identifier": "IContactController",
"path": "contact-api/src/main/java/com/inn/assignment/task2/controller/IContactController.java",
"snippet": "@Tag(name = \"IContactController\", description = \"Endpoint for managing person data\")\n@Validated\npublic interface IContactController {\n\n\t@Operation(summary = \"Check if the service is alive\", description = \"Returns a simple string to confirm that the service is running.\")\n\t@GetMapping(\"/isAlive\")\n\tpublic String isAlive();\n\t\n\t@Operation(summary = \"Add a new Contact details in directory \", description = \"Add a new Contact details in directory and return created Object in response\")\n\t@PostMapping(\"/addContact\")\n\tContact addContact(@Valid @org.springframework.web.bind.annotation.RequestBody Contact model);\n\t\n\t@Operation(summary = \"update a existing Contact details in directory\", description = \"update a existing details in directory and return updated data in response\")\n\t@PostMapping(\"/editContact\")\n\tContact editContact(@Valid @org.springframework.web.bind.annotation.RequestBody Contact model);\n\n\t@Operation(summary = \"Find all contact records\", description = \"Retrieve all the contact records.\")\n\t@GetMapping(\"/findAll\")\n\tpublic List<Contact> findAll();\n\n\t@Operation(summary = \"Delete a existing Contact details from directory\", description = \"Delete a existing details in directory and return success\")\n\t@DeleteMapping(\"/deleteContact/{id}\")\n\tString deleteContact(@PathVariable Integer id);\n\t\n\t@Operation(summary = \"Search contact record from contact directory\", description = \"Perform an advanced version of the search for contact records based on the provided query and limits.\")\n\t@PostMapping(path = \"/search\")\n\tList<Contact> search(\n\t\t\t@RequestBody(content = @Content(schema = @Schema(implementation = String.class)), required = false) @Parameter(description = \"Search query\") String query,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Upper limit for search\") Integer ulimit,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Lower limit for search\") Integer llimit,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Field to order results by\") String orderBy,\n\t\t\t@RequestParam(required = false) @Parameter(description = \"Type of ordering (ascending/descending\") String orderType);\n\n\t@Hidden\n\t@Operation(summary = \"Get count of searched contact records\", description = \"Retrieve the count of contact records based on the advanced search query.\")\n\t@PostMapping(path = \"getCount\")\n\tLong getCount(\n\t\t\t@RequestBody(content = @Content(schema = @Schema(implementation = String.class)), required = false) @Parameter(description = \"Search query\") String query);\n}"
},
{
"identifier": "BusinessException",
"path": "contact-api/src/main/java/com/inn/assignment/task2/core/BusinessException.java",
"snippet": "public class BusinessException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic BusinessException(String message) {\n\t\tsuper(message);\n\n\t}\n\n}"
},
{
"identifier": "Contact",
"path": "contact-api/src/main/java/com/inn/assignment/task2/model/Contact.java",
"snippet": "@Entity\n@Data\n@Valid\n@AllArgsConstructor\n@NoArgsConstructor\n@Table(name = \"CONTACT\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n@JsonIgnoreProperties({ \"hibernateLazyInitializer\", \"handler\" })\npublic class Contact {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Integer id;\n\t\n\t@NotEmpty(message = \"Email Address is required\")\n\t@Email(message = \"Invalid email format\")\n\tprivate String emailAddress;\n\n\t@NotEmpty(message = \"Phone Number is required\")\n\t@Size(min = 10, max = 10, message = \"Phone Number should be of 10 digits only\")\n\t@Pattern(regexp = \"^[0-9]+$\", message = \"Phone Number should contain only digits\")\n\tprivate String phoneNumber;\n\n}"
},
{
"identifier": "IContactService",
"path": "contact-api/src/main/java/com/inn/assignment/task2/service/IContactService.java",
"snippet": "public interface IContactService {\n\n\tContact addContact(Contact model);\n\n\tContact editContact(Contact model);\n\n\tList<Contact> findAll();\n\n\tString deleteContact(Integer id);\n\n\tList<Contact> search(String query, Integer ulimit, Integer llimit, String orderBy, String orderType);\n\n\tLong getCount(String query);\n}"
}
] | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.inn.assignment.task2.controller.IContactController;
import com.inn.assignment.task2.core.BusinessException;
import com.inn.assignment.task2.model.Contact;
import com.inn.assignment.task2.service.IContactService;
import io.swagger.v3.oas.annotations.media.Content;
import jakarta.persistence.EntityNotFoundException;
import jakarta.validation.Valid; | 1,120 | package com.inn.assignment.task2.controller.Impl;
@RestController
@RequestMapping(path = "/Contact") | package com.inn.assignment.task2.controller.Impl;
@RestController
@RequestMapping(path = "/Contact") | public class ContactControllerImpl implements IContactController { | 0 | 2023-12-14 20:15:48+00:00 | 2k |
Crydsch/the-one | src/routing/maxprop/MeetingProbabilitySet.java | [
{
"identifier": "SimClock",
"path": "src/core/SimClock.java",
"snippet": "public class SimClock {\n\tprivate static double clockTime = 0.0;\n\tprivate static SimClock clock = null;\n\n\tprivate SimClock() {}\n\n\tstatic {\n\t\tDTNSim.registerForReset(SimClock.class.getCanonicalName());\n\t\treset();\n\t}\n\n\t/**\n\t * Get the instance of the class that can also change the time.\n\t * @return The instance of this clock\n\t */\n\tpublic static SimClock getInstance() {\n\t\tif (clock == null) {\n\t\t\tclock = new SimClock();\n\t\t}\n\t\treturn clock;\n\t}\n\n\t/**\n\t * Returns the current time (seconds since start)\n\t * @return Time as a double\n\t */\n\tpublic static double getTime() {\n\t\treturn clockTime;\n\t}\n\n\t/**\n\t * Returns the current time rounded to the nearest integer\n\t * @return Time as integer\n\t */\n\tpublic static int getIntTime() {\n\t\treturn (int)Math.round(clockTime);\n\t}\n\n\t/**\n\t * Returns a string presentation of the sim time shown with the given amount\n\t * of decimals\n\t * @param decimals The number of decimals to show\n\t * @return The sim time\n\t */\n\tpublic static String getFormattedTime(int decimals) {\n\t\treturn String.format(\"%.\" + decimals + \"f\", clockTime);\n\t}\n\n\t/**\n\t * Advances the time by n seconds\n\t * @param time Nrof seconds to increase the time\n\t */\n\tpublic void advance(double time) {\n\t\tclockTime += time;\n\t}\n\n\t/**\n\t * Sets the time of the clock.\n\t * @param time the time to set\n\t */\n\tpublic void setTime(double time) {\n\t\tclockTime = time;\n\t}\n\n\t/**\n\t * Returns the current simulation time in a string\n\t * @return the current simulation time in a string\n\t */\n\tpublic String toString() {\n\t\treturn \"SimTime: \" + clockTime;\n\t}\n\n\t/**\n\t * Resets the static fields of the class\n\t */\n\tpublic static void reset() {\n\t\tclockTime = 0;\n\t}\n}"
},
{
"identifier": "DEBUG",
"path": "src/core/Constants.java",
"snippet": "public static final boolean DEBUG = false;"
}
] | import java.util.HashMap;
import java.util.List;
import java.util.Map;
import core.SimClock;
import static core.Constants.DEBUG; | 1,152 | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package routing.maxprop;
/**
* Class for storing and manipulating the meeting probabilities for the MaxProp
* router module.
*/
public class MeetingProbabilitySet {
public static final int INFINITE_SET_SIZE = Integer.MAX_VALUE;
/** meeting probabilities (probability that the next node one meets is X) */
private Map<Integer, Double> probs;
/** the time when this MPS was last updated */
private double lastUpdateTime;
/** the alpha parameter */
private double alpha;
private int maxSetSize;
/**
* Constructor. Creates a probability set with empty node-probability
* mapping.
* @param maxSetSize Maximum size of the probability set; when the set is
* full, smallest values are dropped when new are added
*/
public MeetingProbabilitySet(int maxSetSize, double alpha) {
this.alpha = alpha;
this.probs = new HashMap<Integer, Double>();
if (maxSetSize == INFINITE_SET_SIZE || maxSetSize < 1) {
this.probs = new HashMap<Integer, Double>();
this.maxSetSize = INFINITE_SET_SIZE;
} else {
this.probs = new HashMap<Integer, Double>(maxSetSize);
this.maxSetSize = maxSetSize;
}
this.lastUpdateTime = 0;
}
/**
* Constructor. Creates a probability set with empty node-probability
* mapping and infinite set size
*/
public MeetingProbabilitySet() {
this(INFINITE_SET_SIZE, 1);
}
/**
* Constructor. Creates a probability set with equal probability for
* all the given node indexes.
*/
public MeetingProbabilitySet(double alpha,
List<Integer> initiallyKnownNodes) {
this(INFINITE_SET_SIZE, alpha);
double prob = 1.0/initiallyKnownNodes.size();
for (Integer i : initiallyKnownNodes) {
this.probs.put(i, prob);
}
}
/**
* Updates meeting probability for the given node index.
* <PRE> P(b) = P(b)_old + alpha
* Normalize{P}</PRE>
* I.e., The probability of the given node index is increased by one and
* then all the probabilities are normalized so that their sum equals to 1.
* @param index The node index to update the probability for
*/
public void updateMeetingProbFor(Integer index) {
Map.Entry<Integer, Double> smallestEntry = null;
double smallestValue = Double.MAX_VALUE;
| /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package routing.maxprop;
/**
* Class for storing and manipulating the meeting probabilities for the MaxProp
* router module.
*/
public class MeetingProbabilitySet {
public static final int INFINITE_SET_SIZE = Integer.MAX_VALUE;
/** meeting probabilities (probability that the next node one meets is X) */
private Map<Integer, Double> probs;
/** the time when this MPS was last updated */
private double lastUpdateTime;
/** the alpha parameter */
private double alpha;
private int maxSetSize;
/**
* Constructor. Creates a probability set with empty node-probability
* mapping.
* @param maxSetSize Maximum size of the probability set; when the set is
* full, smallest values are dropped when new are added
*/
public MeetingProbabilitySet(int maxSetSize, double alpha) {
this.alpha = alpha;
this.probs = new HashMap<Integer, Double>();
if (maxSetSize == INFINITE_SET_SIZE || maxSetSize < 1) {
this.probs = new HashMap<Integer, Double>();
this.maxSetSize = INFINITE_SET_SIZE;
} else {
this.probs = new HashMap<Integer, Double>(maxSetSize);
this.maxSetSize = maxSetSize;
}
this.lastUpdateTime = 0;
}
/**
* Constructor. Creates a probability set with empty node-probability
* mapping and infinite set size
*/
public MeetingProbabilitySet() {
this(INFINITE_SET_SIZE, 1);
}
/**
* Constructor. Creates a probability set with equal probability for
* all the given node indexes.
*/
public MeetingProbabilitySet(double alpha,
List<Integer> initiallyKnownNodes) {
this(INFINITE_SET_SIZE, alpha);
double prob = 1.0/initiallyKnownNodes.size();
for (Integer i : initiallyKnownNodes) {
this.probs.put(i, prob);
}
}
/**
* Updates meeting probability for the given node index.
* <PRE> P(b) = P(b)_old + alpha
* Normalize{P}</PRE>
* I.e., The probability of the given node index is increased by one and
* then all the probabilities are normalized so that their sum equals to 1.
* @param index The node index to update the probability for
*/
public void updateMeetingProbFor(Integer index) {
Map.Entry<Integer, Double> smallestEntry = null;
double smallestValue = Double.MAX_VALUE;
| this.lastUpdateTime = SimClock.getTime(); | 0 | 2023-12-10 15:51:41+00:00 | 2k |
jackyor/matsim_HongKong | src/main/java/org/matsim/run/RunDrt.java | [
{
"identifier": "MultiModeOptDrtConfigGroup",
"path": "src/main/java/org/matsim/optDRT/MultiModeOptDrtConfigGroup.java",
"snippet": "public final class MultiModeOptDrtConfigGroup extends ReflectiveConfigGroup implements MultiModal<OptDrtConfigGroup>{\n\tpublic static final String GROUP_NAME = \"multiModeOptDrt\";\n\t\n\tprivate static final String UPDATE_INTERVAL = \"optDrtUpdateInterval\";\n\tprivate static final String DISABLE_INNOVATION_IN_OPTDRT_UPDATE_INTERVAL = \"disableInnovationInOptDrtUpdateInterval\";\n\tprivate int updateInterval = 1;\n\tprivate DisableInnovationInOptDrtUpdateInterval disableInnovationInOptDrtUpdateInterval =\n\t\t\tDisableInnovationInOptDrtUpdateInterval.StrategyConfigFractionOfIterationsToDisableInnovation;\n\n\tenum DisableInnovationInOptDrtUpdateInterval {Off, StrategyConfigFractionOfIterationsToDisableInnovation, UpdateIterationOnly};\n\n\tpublic MultiModeOptDrtConfigGroup() {\n\t\tsuper(GROUP_NAME);\n\t}\n\n\t@Override\n\t@SuppressWarnings(\"unchecked\")\n\tpublic Collection<OptDrtConfigGroup> getModalElements() {\n\t\treturn (Collection<OptDrtConfigGroup>)getParameterSets(OptDrtConfigGroup.GROUP_NAME);\n\t}\n\t\n\t@Override\n\tpublic ConfigGroup createParameterSet(String type) {\n\t\tif (type.equals(OptDrtConfigGroup.GROUP_NAME)) {\n\t\t\treturn new OptDrtConfigGroup();\n\t\t}\n\t\tthrow new IllegalArgumentException(type);\n\t}\n\n\t@StringGetter( UPDATE_INTERVAL )\n\tpublic int getUpdateInterval() {\n\t\treturn updateInterval;\n\t}\n\t\n\t@StringSetter( UPDATE_INTERVAL )\n\tpublic void setUpdateInterval(int updateInterval) {\n\t\tthis.updateInterval = updateInterval;\n\t}\n\n\t@StringGetter( DISABLE_INNOVATION_IN_OPTDRT_UPDATE_INTERVAL )\n\tpublic DisableInnovationInOptDrtUpdateInterval getDisableInnovationInOptDrtUpdateInterval() {\n\t\treturn disableInnovationInOptDrtUpdateInterval;\n\t}\n\n\t@StringSetter( DISABLE_INNOVATION_IN_OPTDRT_UPDATE_INTERVAL )\n\tpublic void setDisableInnovationInOptDrtUpdateInterval(DisableInnovationInOptDrtUpdateInterval disableInnovationInOptDrtUpdateInterval) {\n\t\tthis.disableInnovationInOptDrtUpdateInterval = disableInnovationInOptDrtUpdateInterval;\n\t}\n\n}"
},
{
"identifier": "OptDrt",
"path": "src/main/java/org/matsim/optDRT/OptDrt.java",
"snippet": "public class OptDrt {\n\n\tpublic static void addAsOverridingModule(AllowsConfiguration controler,\n\t\t\tMultiModeOptDrtConfigGroup multiModeOptDrtConfigGroup) {\n\t\tcontroler.addOverridingModule(new MultiModeOptDrtModule());\n\t\tcontroler.addOverridingQSimModule(new MultiModeOptDrtQSimModule(multiModeOptDrtConfigGroup));\n\t}\n}"
}
] | import org.matsim.vis.otfvis.OTFVisConfigGroup;
import java.util.List;
import java.util.stream.Collectors;
import org.matsim.core.mobsim.qsim.components.QSimComponentsConfigurator;
import org.matsim.optDRT.MultiModeOptDrtConfigGroup;
import org.matsim.optDRT.OptDrt;
import org.matsim.contrib.drt.extension.fiss.FISSConfigGroup;
import org.matsim.contrib.drt.extension.fiss.FISSConfigurator;
import org.matsim.contrib.drt.run.DrtControlerCreator;
import org.matsim.contrib.drt.run.MultiModeDrtConfigGroup;
import org.matsim.contrib.dvrp.run.DvrpConfigGroup;
import org.matsim.core.config.Config;
import org.matsim.core.config.ConfigUtils;
import org.matsim.core.controler.Controler;
import org.matsim.simwrapper.SimWrapperModule; | 1,109 | /* *********************************************************************** *
* project: org.matsim.* *
* *
* *********************************************************************** *
* *
* copyright : (C) 2008 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package org.matsim.run;
/**
* @author nagel
*
*/
public class RunDrt {
public static void main(String[] args) {
String configFile = "scenarios/final_drt/car.config.xml";
Config config = ConfigUtils.loadConfig(configFile, new MultiModeDrtConfigGroup(), | /* *********************************************************************** *
* project: org.matsim.* *
* *
* *********************************************************************** *
* *
* copyright : (C) 2008 by the members listed in the COPYING, *
* LICENSE and WARRANTY file. *
* email : info at matsim dot org *
* *
* *********************************************************************** *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* See also COPYING, LICENSE and WARRANTY file *
* *
* *********************************************************************** */
package org.matsim.run;
/**
* @author nagel
*
*/
public class RunDrt {
public static void main(String[] args) {
String configFile = "scenarios/final_drt/car.config.xml";
Config config = ConfigUtils.loadConfig(configFile, new MultiModeDrtConfigGroup(), | new DvrpConfigGroup(), new OTFVisConfigGroup(),new MultiModeOptDrtConfigGroup()); | 0 | 2023-12-05 08:52:39+00:00 | 2k |
rcaneppele/simple-openai-client | src/main/java/br/com/rcaneppele/openai/endpoints/run/request/builder/CreateThreadAndRunRequestBuilder.java | [
{
"identifier": "OpenAIModel",
"path": "src/main/java/br/com/rcaneppele/openai/common/OpenAIModel.java",
"snippet": "public enum OpenAIModel {\n\n GPT_3_5_TURBO_1106(\"gpt-3.5-turbo-1106\"),\n GPT_3_5_TURBO(\"gpt-3.5-turbo\"),\n GPT_3_5_TURBO_16k(\"gpt-3.5-turbo-16k\"),\n GPT_3_5_TURBO_INSTRUCT(\"gpt-3.5-turbo-instruct\"),\n GPT_4_1106_PREVIEW(\"gpt-4-1106-preview\"),\n GPT_4(\"gpt-4\"),\n GPT_4_32K(\"gpt-4-32k\"),\n GPT_4_0613(\"gpt-4-0613\"),\n GPT_4_32k_0613(\"gpt-4-32k-0613\");\n\n private final String name;\n\n OpenAIModel(String name) {\n this.name = name;\n }\n\n @JsonValue\n public String getName() {\n return name;\n }\n\n @JsonCreator\n public static OpenAIModel fromString(String value) {\n return Arrays.stream(OpenAIModel.values())\n .filter(model -> model.getName().equalsIgnoreCase(value))\n .findFirst()\n .orElseThrow(() -> new IllegalArgumentException(\"Unknown OpenAIModel enum constant: \" + value));\n }\n\n}"
},
{
"identifier": "IdValidator",
"path": "src/main/java/br/com/rcaneppele/openai/common/validation/IdValidator.java",
"snippet": "public class IdValidator {\n\n public void validateAssistantId(String assistantId) {\n if (!isIdValid(assistantId)) {\n throw new IllegalArgumentException(\"Assistant id is required!\");\n }\n }\n\n public void validateThreadId(String threadId) {\n if (!isIdValid(threadId)) {\n throw new IllegalArgumentException(\"Thread id is required!\");\n }\n }\n\n public void validateFileId(String fileId) {\n if (!isIdValid(fileId)) {\n throw new IllegalArgumentException(\"File id is required!\");\n }\n }\n\n public void validateMessageId(String messageId) {\n if (!isIdValid(messageId)) {\n throw new IllegalArgumentException(\"Message id is required!\");\n }\n }\n\n public void validateRunId(String runId) {\n if (!isIdValid(runId)) {\n throw new IllegalArgumentException(\"Run id is required!\");\n }\n }\n\n public void validateRunStepId(String runStepId) {\n if (!isIdValid(runStepId)) {\n throw new IllegalArgumentException(\"Run Step id is required!\");\n }\n }\n\n private boolean isIdValid(String id) {\n return id != null && !id.isBlank();\n }\n\n}"
},
{
"identifier": "MetadataValidator",
"path": "src/main/java/br/com/rcaneppele/openai/common/validation/MetadataValidator.java",
"snippet": "public class MetadataValidator {\n\n public void validate(Map<String, String> metadata) {\n if (metadata.size() > 16) {\n throw new IllegalArgumentException(\"There can be a maximum of 16 key-value pairs that can be attached to the assistant!\");\n }\n\n var keysValid = metadata.keySet().stream().allMatch(key -> key.length() <= 64);\n if (!keysValid) {\n throw new IllegalArgumentException(\"Metadata Keys can be a maximum of 64 characters long!\");\n }\n\n var valuesValid = metadata.values().stream().allMatch(key -> key.length() <= 512);\n if (!valuesValid) {\n throw new IllegalArgumentException(\"Metadata Values can be a maximum of 512 characters long!\");\n }\n }\n\n}"
},
{
"identifier": "ToolType",
"path": "src/main/java/br/com/rcaneppele/openai/endpoints/assistant/tools/ToolType.java",
"snippet": "public enum ToolType {\n\n RETRIEVAL(\"retrieval\"),\n CODE_INTERPRETER(\"code_interpreter\"),\n FUNCTION_CALL(\"function\");\n\n private final String name;\n\n ToolType(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n}"
},
{
"identifier": "CreateThreadRequestBuilder",
"path": "src/main/java/br/com/rcaneppele/openai/endpoints/thread/request/builder/CreateThreadRequestBuilder.java",
"snippet": "public class CreateThreadRequestBuilder {\n\n private List<CreateMessageRequest> messages = new ArrayList<>();\n private Map<String, String> metadata;\n\n private MetadataValidator metadataValidator = new MetadataValidator();\n\n public CreateThreadRequestBuilder addUserMessage(String content, Set<String> fileIds, Map<String, String> metadata) {\n if (content == null || content.isBlank()) {\n throw new IllegalArgumentException(\"The content of the message is required!\");\n }\n\n if (fileIds != null && fileIds.size() > 10) {\n throw new IllegalArgumentException(\"There can be a maximum of 10 files attached to a message!\");\n }\n\n if (metadata != null) {\n this.metadataValidator.validate(metadata);\n }\n\n var message = new CreateMessageRequest(\n null,\n \"user\",\n content,\n fileIds,\n metadata\n );\n this.messages.add(message);\n return this;\n }\n\n public CreateThreadRequestBuilder metadata(Map<String, String> metadata) {\n this.metadataValidator.validate(metadata);\n this.metadata = metadata;\n return this;\n }\n\n public CreateThreadRequest build() {\n return new CreateThreadRequest(\n this.messages,\n this.metadata\n );\n }\n\n}"
}
] | import br.com.rcaneppele.openai.common.OpenAIModel;
import br.com.rcaneppele.openai.common.validation.IdValidator;
import br.com.rcaneppele.openai.common.validation.MetadataValidator;
import br.com.rcaneppele.openai.endpoints.assistant.tools.Function;
import br.com.rcaneppele.openai.endpoints.assistant.tools.Tool;
import br.com.rcaneppele.openai.endpoints.assistant.tools.ToolType;
import br.com.rcaneppele.openai.endpoints.run.request.CreateThreadAndRunRequest;
import br.com.rcaneppele.openai.endpoints.thread.request.builder.CreateThreadRequestBuilder;
import java.util.HashSet;
import java.util.Map;
import java.util.Set; | 1,523 | package br.com.rcaneppele.openai.endpoints.run.request.builder;
public class CreateThreadAndRunRequestBuilder {
private String assistantId; | package br.com.rcaneppele.openai.endpoints.run.request.builder;
public class CreateThreadAndRunRequestBuilder {
private String assistantId; | private OpenAIModel model; | 0 | 2023-12-21 19:17:56+00:00 | 2k |
373675032/smart-medicine | src/main/java/world/xuewei/controller/MessageController.java | [
{
"identifier": "RespResult",
"path": "src/main/java/world/xuewei/dto/RespResult.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class RespResult {\n\n /**\n * 响应编码\n */\n protected String code;\n\n /**\n * 响应信息\n */\n protected String message;\n\n /**\n * 响应数据\n */\n protected Object data;\n\n /**\n * 请求成功\n */\n public static RespResult success() {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(\"请求成功\")\n .build();\n }\n\n /**\n * 请求成功\n */\n public static RespResult success(String message) {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(message)\n .build();\n }\n\n /**\n * 请求成功\n */\n public static RespResult success(String message, Object data) {\n return RespResult.builder()\n .code(\"SUCCESS\")\n .message(message)\n .data(data)\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail() {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(\"请求失败\")\n .build();\n }\n\n\n /**\n * 请求失败\n */\n public static RespResult fail(String message) {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(message)\n .build();\n }\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound(String message, Object data) {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(message)\n .data(data)\n .build();\n }\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound() {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(\"请求失败\")\n .build();\n }\n\n\n /**\n * 未查询到数据\n */\n public static RespResult notFound(String message) {\n return RespResult.builder()\n .code(\"NOT_FOUND\")\n .message(message)\n .build();\n }\n\n /**\n * 请求失败\n */\n public static RespResult fail(String message, Object data) {\n return RespResult.builder()\n .code(\"FAIL\")\n .message(message)\n .data(data)\n .build();\n }\n\n /**\n * 请求是否成功\n */\n public boolean isSuccess() {\n return \"SUCCESS\".equals(code);\n }\n\n /**\n * 请求是否成功并有数据返回\n */\n public boolean isSuccessWithDateResp() {\n return \"SUCCESS\".equals(code) && Assert.notEmpty(data);\n }\n\n /**\n * 请求是否成功\n */\n public boolean notSuccess() {\n return !isSuccess();\n }\n\n /**\n * 获取响应的数据集合\n */\n public <T> List<T> getDataList(Class<T> clazz) {\n String jsonString = JSONObject.toJSONString(data);\n return JSONObject.parseArray(jsonString, clazz);\n }\n\n /**\n * 获取响应的数据\n */\n public <T> T getDataObj(Class<T> clazz) {\n String jsonString = JSONObject.toJSONString(data);\n return JSONObject.parseObject(jsonString, clazz);\n }\n\n}"
},
{
"identifier": "User",
"path": "src/main/java/world/xuewei/entity/User.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@TableName(\"user\")\npublic class User {\n\n /**\n * 主键ID\n */\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n /**\n * 用户账号\n */\n private String userAccount;\n\n /**\n * 用户真实名字\n */\n private String userName;\n\n /**\n * 用户密码\n */\n private String userPwd;\n\n /**\n * 用户年龄\n */\n private Integer userAge;\n\n /**\n * 用户性别\n */\n private String userSex;\n\n /**\n * 用户邮箱\n */\n private String userEmail;\n\n /**\n * 用户电话\n */\n private String userTel;\n\n /**\n * 角色状态,1代表管理员,0普通用户\n */\n private Integer roleStatus;\n\n /**\n * 图片的地址\n */\n private String imgPath;\n\n /**\n * 创建时间\n */\n private Date createTime;\n\n /**\n * 更新时间\n */\n private Date updateTime;\n\n}"
}
] | import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import world.xuewei.dto.RespResult;
import world.xuewei.entity.User; | 1,304 | package world.xuewei.controller;
/**
* 消息控制器
*
* @author XUEW
*/
@RestController
@RequestMapping("/message")
public class MessageController extends BaseController<User> {
/**
* 发送消息
*/
@PostMapping("/query") | package world.xuewei.controller;
/**
* 消息控制器
*
* @author XUEW
*/
@RestController
@RequestMapping("/message")
public class MessageController extends BaseController<User> {
/**
* 发送消息
*/
@PostMapping("/query") | public RespResult query(String content) { | 0 | 2023-12-16 11:16:11+00:00 | 2k |
simasch/vaadin-jooq-template | src/main/java/ch/martinelli/vj/ui/views/helloworld/HelloWorldView.java | [
{
"identifier": "Notifier",
"path": "src/main/java/ch/martinelli/vj/ui/components/Notifier.java",
"snippet": "public class Notifier extends Notification {\n\n public static final int DURATION = 3000;\n\n public static void info(String message) {\n showNotification(message);\n }\n\n public static void success(String message) {\n var notification = showNotification(message);\n notification.addThemeVariants(NotificationVariant.LUMO_SUCCESS);\n }\n\n public static void warn(String message) {\n var notification = showNotification(message);\n notification.addThemeVariants(NotificationVariant.LUMO_WARNING);\n }\n\n public static void error(String message) {\n var text = new NativeLabel(message);\n var close = new Button(\"OK\");\n\n var content = new HorizontalLayout(text, close);\n content.addClassName(LumoUtility.AlignItems.CENTER);\n\n var notification = new Notification(content);\n notification.addThemeVariants(NotificationVariant.LUMO_ERROR);\n notification.setPosition(Position.TOP_END);\n\n close.addClickListener(buttonClickEvent -> notification.close());\n notification.open();\n close.focus();\n }\n\n private static Notification showNotification(String message) {\n return show(message, DURATION, Position.TOP_END);\n }\n\n}"
},
{
"identifier": "MainLayout",
"path": "src/main/java/ch/martinelli/vj/ui/layout/MainLayout.java",
"snippet": "public class MainLayout extends AppLayout {\n\n private final transient AuthenticatedUser authenticatedUser;\n private final AccessAnnotationChecker accessChecker;\n\n private H2 viewTitle;\n\n public MainLayout(AuthenticatedUser authenticatedUser, AccessAnnotationChecker accessChecker) {\n this.authenticatedUser = authenticatedUser;\n this.accessChecker = accessChecker;\n\n setPrimarySection(Section.DRAWER);\n addDrawerContent();\n addHeaderContent();\n }\n\n private void addHeaderContent() {\n var toggle = new DrawerToggle();\n toggle.setAriaLabel(\"Menu toggle\");\n\n viewTitle = new H2();\n viewTitle.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);\n\n addToNavbar(true, toggle, viewTitle);\n }\n\n private void addDrawerContent() {\n var appName = new H1(\"Vaadin jOOQ Template\");\n appName.addClassNames(LumoUtility.FontSize.LARGE, LumoUtility.Margin.NONE);\n\n var header = new Header(appName);\n\n var scroller = new Scroller(createNavigation());\n\n addToDrawer(header, scroller, createFooter());\n }\n\n private SideNav createNavigation() {\n var nav = new SideNav();\n\n if (accessChecker.hasAccess(HelloWorldView.class)) {\n nav.addItem(new SideNavItem(getTranslation(\"Hello World\"), HelloWorldView.class, VaadinIcon.GLOBE.create()));\n\n }\n if (accessChecker.hasAccess(PersonView.class)) {\n nav.addItem(new SideNavItem(getTranslation(\"Persons\"), PersonView.class, VaadinIcon.ARCHIVES.create()));\n }\n if (accessChecker.hasAccess(UserView.class)) {\n nav.addItem(new SideNavItem(getTranslation(\"Users\"), UserView.class, VaadinIcon.USER.create()));\n }\n\n return nav;\n }\n\n private Footer createFooter() {\n var layout = new Footer();\n\n var optionalUserRecord = authenticatedUser.get();\n if (optionalUserRecord.isPresent()) {\n var user = optionalUserRecord.get();\n\n var avatar = new Avatar(\"%s %s\".formatted(user.getFirstName(), user.getLastName()));\n var resource = new StreamResource(\"profile-pic\", () -> new ByteArrayInputStream(user.getPicture()));\n avatar.setImageResource(resource);\n avatar.setThemeName(\"xsmall\");\n avatar.getElement().setAttribute(\"tabindex\", \"-1\");\n\n var userMenu = new MenuBar();\n userMenu.setThemeName(\"tertiary-inline contrast\");\n\n var userName = userMenu.addItem(\"\");\n\n var div = new Div();\n div.add(avatar);\n div.add(\"%s %s\".formatted(user.getFirstName(), user.getLastName()));\n div.add(LumoIcon.DROPDOWN.create());\n div.addClassNames(LumoUtility.Display.FLEX, LumoUtility.AlignItems.CENTER, LumoUtility.Gap.SMALL);\n userName.add(div);\n userName.getSubMenu().addItem(getTranslation(\"Sign out\"), e -> authenticatedUser.logout());\n\n layout.add(userMenu);\n } else {\n var loginLink = new Anchor(\"login\", getTranslation(\"Sign in\"));\n layout.add(loginLink);\n }\n\n return layout;\n }\n\n @Override\n protected void afterNavigation() {\n super.afterNavigation();\n viewTitle.setText(getCurrentPageTitle());\n }\n\n private String getCurrentPageTitle() {\n var title = getContent().getClass().getAnnotation(PageTitle.class);\n return title == null ? \"\" : title.value();\n }\n}"
}
] | import ch.martinelli.vj.ui.components.Notifier;
import ch.martinelli.vj.ui.layout.MainLayout;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import com.vaadin.flow.server.auth.AnonymousAllowed; | 1,347 | package ch.martinelli.vj.ui.views.helloworld;
@PageTitle("Hello World")
@Route(value = "hello", layout = MainLayout.class)
@RouteAlias(value = "", layout = MainLayout.class)
@AnonymousAllowed
public class HelloWorldView extends HorizontalLayout {
public HelloWorldView() {
setMargin(true);
var name = new TextField(getTranslation("Your name"));
name.setId("name");
var sayHello = new Button(getTranslation("Say hello"));
sayHello.setId("say-hello"); | package ch.martinelli.vj.ui.views.helloworld;
@PageTitle("Hello World")
@Route(value = "hello", layout = MainLayout.class)
@RouteAlias(value = "", layout = MainLayout.class)
@AnonymousAllowed
public class HelloWorldView extends HorizontalLayout {
public HelloWorldView() {
setMargin(true);
var name = new TextField(getTranslation("Your name"));
name.setId("name");
var sayHello = new Button(getTranslation("Say hello"));
sayHello.setId("say-hello"); | sayHello.addClickListener(e -> Notifier.info(getTranslation("Hello {0}", name.getValue()))); | 0 | 2023-12-20 13:08:17+00:00 | 2k |
373675032/academic-report | src/main/java/world/xuewei/vo/AppointmentVo.java | [
{
"identifier": "Appointment",
"path": "src/main/java/world/xuewei/entity/Appointment.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Appointment implements Serializable {\n\n private static final long serialVersionUID = 827721937429118051L;\n\n /**\n * 预约ID\n */\n private Integer id;\n\n /**\n * 会议ID\n */\n private Integer meetingId;\n\n /**\n * 学生ID\n */\n private Integer studentId;\n\n /**\n * 预约时间\n */\n private Date appointmentTime;\n\n /**\n * 是否到场【1:是】【0:否】\n */\n private Integer present;\n\n}"
},
{
"identifier": "Student",
"path": "src/main/java/world/xuewei/entity/Student.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\n@ExcelTarget(\"Student\")\npublic class Student implements Serializable {\n\n private static final long serialVersionUID = 972593633686891663L;\n\n /**\n * 主键ID\n */\n private Integer id;\n\n /**\n * 学号【201724114111】\n */\n @Excel(name = \"学号\", width = 20)\n private String no;\n\n /**\n * 姓名\n */\n @Excel(name = \"姓名\")\n private String name;\n\n /**\n * 登录密码\n */\n private String password;\n\n /**\n * 邮箱\n */\n @Excel(name = \"邮箱\", width = 20)\n private String email;\n\n /**\n * 手机号码\n */\n @Excel(name = \"手机号码\", width = 20)\n private String phone;\n\n /**\n * 性别\n */\n @Excel(name = \"性别\")\n private String sex;\n\n /**\n * 出生日期【1999-09-09】\n */\n @Excel(name = \"出生日期\", format = \"yyyy年MM月dd日\", width = 20)\n private Date birthday;\n\n /**\n * 出生日期字符串\n */\n private String birthdayStr;\n\n /**\n * 年级【2017】\n */\n @Excel(name = \"年级\")\n private Integer grade;\n\n /**\n * 专业\n */\n @Excel(name = \"专业\", width = 30)\n private String major;\n\n /**\n * 班级信息【1班】\n */\n @Excel(name = \"班级\")\n private String classInfo;\n\n /**\n * 学院ID\n */\n private Integer collegeId;\n\n /**\n * 院系\n */\n @Excel(name = \"院系\", width = 30)\n private String collegeName;\n\n /**\n * 院系\n */\n private College college;\n\n /**\n * 头像\n */\n private String img = Photo.student;\n\n}"
}
] | import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import world.xuewei.entity.Appointment;
import world.xuewei.entity.Student; | 1,104 | package world.xuewei.vo;
/**
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AppointmentVo {
private Student student;
private MeetingVo meetingVo; | package world.xuewei.vo;
/**
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AppointmentVo {
private Student student;
private MeetingVo meetingVo; | private Appointment appointment; | 0 | 2023-12-21 06:59:12+00:00 | 2k |
misode/packtest | src/main/java/io/github/misode/packtest/mixin/GameTestInfoMixin.java | [
{
"identifier": "ChatListener",
"path": "src/main/java/io/github/misode/packtest/ChatListener.java",
"snippet": "public class ChatListener {\n\n private static final List<ChatListener> listeners = new ArrayList<>();\n\n public static void broadcast(ServerPlayer player, Component chatMessage) {\n Message message = new Message(player.getName().getString(), chatMessage.getString());\n ChatListener.listeners.forEach(l -> l.messages.add(message));\n }\n\n public ChatListener() {\n ChatListener.listeners.add(this);\n }\n\n public final List<Message> messages = new ArrayList<>();\n\n public void stop() {\n ChatListener.listeners.remove(this);\n }\n\n public List<String> filter(Predicate<Message> predicate) {\n return this.messages.stream()\n .filter(predicate)\n .map(m -> m.content)\n .toList();\n }\n\n public void reset() {\n this.messages.clear();\n }\n\n public record Message(String player, String content) {}\n}"
},
{
"identifier": "PackTestInfo",
"path": "src/main/java/io/github/misode/packtest/PackTestInfo.java",
"snippet": "public interface PackTestInfo {\n long packtest$getTick();\n void packtest$setChatListener(ChatListener listener);\n ChatListener packtest$getChatListener();\n}"
},
{
"identifier": "Dummy",
"path": "src/main/java/io/github/misode/packtest/dummy/Dummy.java",
"snippet": "public class Dummy extends ServerPlayer {\n public Vec3 originalSpawn;\n\n public static Dummy createRandom(MinecraftServer server, ResourceKey<Level> dimensionId, Vec3 pos) {\n RandomSource random = server.overworld().getRandom();\n int tries = 0;\n while (tries++ < 10) {\n String playerName = \"Dummy\" + random.nextInt(100, 1000);\n if (server.getPlayerList().getPlayerByName(playerName) == null) {\n return create(playerName, server, dimensionId, pos);\n }\n }\n throw new IllegalStateException(\"Failed to spawn dummy with a random name\");\n }\n\n public static Dummy create(String username, MinecraftServer server, ResourceKey<Level> dimensionId, Vec3 pos) {\n ServerLevel level = server.getLevel(dimensionId);\n GameProfileCache.setUsesAuthentication(false);\n GameProfile profile;\n try {\n var profileCache = server.getProfileCache();\n profile = profileCache == null ? null : profileCache.get(username).orElse(null);\n }\n finally {\n GameProfileCache.setUsesAuthentication(server.isDedicatedServer() && server.usesAuthentication());\n }\n if (profile == null) {\n profile = new GameProfile(UUIDUtil.createOfflinePlayerUUID(username), username);\n }\n Vec3 originalSpawn = Vec3.atBottomCenterOf(BlockPos.containing(pos));\n Dummy dummy = new Dummy(server, level, profile, ClientInformation.createDefault(), originalSpawn);\n server.getPlayerList().placeNewPlayer(\n new DummyClientConnection(PacketFlow.SERVERBOUND),\n dummy,\n new CommonListenerCookie(profile, 0, dummy.clientInformation()));\n dummy.teleportTo(level, originalSpawn.x, originalSpawn.y, originalSpawn.z, 0, 0);\n dummy.setHealth(20);\n dummy.unsetRemoved();\n dummy.gameMode.changeGameModeForPlayer(GameType.SURVIVAL);\n server.getPlayerList().broadcastAll(new ClientboundRotateHeadPacket(dummy, (byte) (dummy.yHeadRot * 256 / 360)), dimensionId);\n server.getPlayerList().broadcastAll(new ClientboundTeleportEntityPacket(dummy), dimensionId);\n dummy.entityData.set(DATA_PLAYER_MODE_CUSTOMISATION, (byte) 0x7f);\n return dummy;\n }\n\n public Dummy(MinecraftServer server, ServerLevel level, GameProfile profile, ClientInformation cli, Vec3 originalSpawn) {\n super(server, level, profile, cli);\n this.originalSpawn = originalSpawn;\n }\n\n public String getUsername() {\n return this.getGameProfile().getName();\n }\n\n public void leave(Component reason) {\n server.getPlayerList().remove(this);\n this.connection.onDisconnect(reason);\n }\n\n public void respawn() {\n server.getPlayerList().respawn(this, false);\n }\n\n @Override\n public void tick() {\n if (Objects.requireNonNull(this.getServer()).getTickCount() % 10 == 0) {\n this.connection.resetPosition();\n this.serverLevel().getChunkSource().move(this);\n }\n try {\n super.tick();\n this.doTick();\n } catch (NullPointerException ignored) {}\n }\n\n @Override\n public void die(DamageSource cause) {\n super.die(cause);\n if (this.serverLevel().getGameRules().getBoolean(GameRules.RULE_DO_IMMEDIATE_RESPAWN)) {\n this.server.tell(new TickTask(this.server.getTickCount(),\n () -> this.connection.handleClientCommand(new ServerboundClientCommandPacket(ServerboundClientCommandPacket.Action.PERFORM_RESPAWN))\n ));\n }\n }\n\n @Override\n public void onEquipItem(final EquipmentSlot slot, final ItemStack previous, final ItemStack stack) {\n if (!isUsingItem()) super.onEquipItem(slot, previous, stack);\n }\n\n @Override\n public @NotNull String getIpAddress() {\n return \"127.0.0.1\";\n }\n}"
}
] | import com.llamalad7.mixinextras.sugar.Local;
import io.github.misode.packtest.ChatListener;
import io.github.misode.packtest.PackTestInfo;
import io.github.misode.packtest.dummy.Dummy;
import net.minecraft.gametest.framework.GameTestInfo;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.phys.AABB;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; | 1,464 | package io.github.misode.packtest.mixin;
/**
* Adds chat listener field and accessors. Removes the listener when finishing.
* Prevents crash when test has already started.
* Clears dummies after succeeding.
*/
@Mixin(GameTestInfo.class)
public abstract class GameTestInfoMixin implements PackTestInfo {
@Shadow
public abstract ServerLevel getLevel();
@Shadow private long tickCount;
@Unique | package io.github.misode.packtest.mixin;
/**
* Adds chat listener field and accessors. Removes the listener when finishing.
* Prevents crash when test has already started.
* Clears dummies after succeeding.
*/
@Mixin(GameTestInfo.class)
public abstract class GameTestInfoMixin implements PackTestInfo {
@Shadow
public abstract ServerLevel getLevel();
@Shadow private long tickCount;
@Unique | private ChatListener chatListener; | 0 | 2023-12-15 10:08:54+00:00 | 2k |
Swofty-Developments/HypixelSkyBlock | generic/src/main/java/net/swofty/types/generic/item/items/mining/vanilla/StonePickaxe.java | [
{
"identifier": "ItemStatistic",
"path": "generic/src/main/java/net/swofty/types/generic/user/statistics/ItemStatistic.java",
"snippet": "@Getter\npublic enum ItemStatistic {\n // Non-Player Statistics\n DAMAGE(\"Damage\", true, null, \"+\", \"\", \"❁\"),\n\n // Player Statistics\n HEALTH(\"Health\", true, \"§c\", \"+\", \"\", \"❤\"),\n DEFENSE(\"Defense\", false, \"§a\", \"+\", \"\", \"❈\"),\n SPEED(\"Speed\", false, \"§f\", \"+\", \"\", \"✦\"),\n STRENGTH(\"Strength\", true, \"§c\", \"+\", \"\", \"❁\"),\n INTELLIGENCE(\"Intelligence\", false, \"§b\", \"+\", \"\", \"✎\"),\n MINING_SPEED(\"Mining Speed\", false, \"§6\", \"+\", \"\", \"⸕\"),\n ;\n\n private final String displayName;\n private final boolean isRed;\n private final String colour;\n private final String prefix;\n private final String suffix;\n private final String symbol;\n\n ItemStatistic(String displayName, boolean isRed, String colour, String prefix, String suffix, String symbol) {\n this.displayName = displayName;\n this.isRed = isRed;\n this.colour = colour;\n this.prefix = prefix;\n this.suffix = suffix;\n this.symbol = symbol;\n }\n}"
},
{
"identifier": "ItemStatistics",
"path": "generic/src/main/java/net/swofty/types/generic/user/statistics/ItemStatistics.java",
"snippet": "@Getter\npublic class ItemStatistics {\n\n public static final ItemStatistics EMPTY = new ItemStatistics(new EnumMap<>(ItemStatistic.class));\n\n private final Map<ItemStatistic, Integer> statistics;\n\n // Private constructor used by the builder\n private ItemStatistics(Map<ItemStatistic, Integer> statistics) {\n this.statistics = new EnumMap<>(statistics);\n }\n\n // Static method to create the builder\n public static ItemStatisticsBuilder builder() {\n return new ItemStatisticsBuilder();\n }\n\n // Builder class\n public static class ItemStatisticsBuilder {\n private final Map<ItemStatistic, Integer> statistics = new EnumMap<>(ItemStatistic.class);\n\n public ItemStatisticsBuilder with(ItemStatistic stat, Integer value) {\n this.statistics.put(stat, value);\n return this;\n }\n\n public ItemStatistics build() {\n return new ItemStatistics(this.statistics);\n }\n }\n\n public Integer get(ItemStatistic stat) {\n return this.statistics.getOrDefault(stat, 0);\n }\n\n public ItemStatistics add(ItemStatistics other) {\n for (ItemStatistic stat : ItemStatistic.values()) {\n this.statistics.merge(stat, other.get(stat), Integer::sum);\n }\n return this;\n }\n}"
},
{
"identifier": "ItemGroups",
"path": "generic/src/main/java/net/swofty/types/generic/utility/ItemGroups.java",
"snippet": "@Getter\npublic enum ItemGroups {\n TOOLS(\"Tools\"),\n PICKAXE(\"Mining Tools\"),\n SWORD(\"Melee Weapon\"),\n FISHING_WEAPON(\"Melee Weapon\"),\n LONG_SWORD(\"Melee Weapon\"),\n ARMOR(\"Armor\"),\n FISHING_ROD(\"Tools\"),\n GAUNTLET(\"Melee Weapon\"),\n DRILL(\"Tools\"),\n ;\n\n private final String displayName;\n\n ItemGroups(String displayName) {\n this.displayName = displayName;\n }\n\n @Override\n public String toString() {\n return StringUtility.toNormalCase(super.toString().toLowerCase());\n }\n}"
},
{
"identifier": "ReforgeType",
"path": "generic/src/main/java/net/swofty/types/generic/item/ReforgeType.java",
"snippet": "@Getter\npublic enum ReforgeType {\n SWORDS(List.of(\n new Reforge(\"Epic\", List.of(\n new Reforge.ReforgeSet(ItemStatistic.STRENGTH, level -> (double) (10 + (level * 5)))\n ))\n )),\n BOWS(List.of()),\n ARMOR(List.of()),\n EQUIPMENT(List.of()),\n FISHING_RODS(List.of()),\n PICKAXES(List.of(\n new Reforge(\"Unyielding\", List.of(\n new Reforge.ReforgeSet(ItemStatistic.SPEED, level -> level * 1.15),\n new Reforge.ReforgeSet(ItemStatistic.MINING_SPEED, Double::valueOf)\n )),\n new Reforge(\"Excellent\", List.of(\n new Reforge.ReforgeSet(ItemStatistic.SPEED, level -> level * 1.1),\n new Reforge.ReforgeSet(ItemStatistic.MINING_SPEED, level -> level * 4d)\n ))\n )),\n AXES(List.of()),\n HOES(List.of()),\n VACUUMS(List.of()),\n ;\n\n private final List<Reforge> reforges;\n\n ReforgeType(List<Reforge> reforges) {\n this.reforges = reforges;\n }\n\n public record Reforge(String prefix, List<ReforgeSet> set) {\n public Set<ItemStatistic> getStatistics() {\n return Set.copyOf(set.stream().map(ReforgeSet::statistic).toList());\n }\n\n public Integer getBonusCalculation(ItemStatistic statistic, Integer level) {\n try {\n return Math.toIntExact(Math.round(set\n .stream()\n .filter(reforgeSet -> reforgeSet.statistic() == statistic)\n .findFirst()\n .orElseThrow()\n .bonusCalculation()\n .apply(level)));\n } catch (NoSuchElementException ex) {\n return 0;\n }\n }\n\n public record ReforgeSet(ItemStatistic statistic, Function<Integer, Double> bonusCalculation) {\n }\n }\n}"
}
] | import net.swofty.types.generic.item.impl.*;
import net.swofty.types.generic.user.statistics.ItemStatistic;
import net.swofty.types.generic.user.statistics.ItemStatistics;
import net.swofty.types.generic.utility.ItemGroups;
import net.swofty.types.generic.item.ReforgeType;
import net.swofty.types.generic.item.impl.*;
import java.util.List; | 1,555 | package net.swofty.types.generic.item.items.mining.vanilla;
public class StonePickaxe implements CustomSkyBlockItem, MiningTool, ExtraRarityDisplay, Enchantable, Reforgable {
@Override
public ItemStatistics getStatistics() {
return ItemStatistics.builder()
.with(ItemStatistic.MINING_SPEED, 110)
.with(ItemStatistic.DAMAGE, 20)
.build();
}
@Override
public int getBreakingPower() {
return 2;
}
@Override
public String getExtraRarityDisplay() {
return " PICKAXE";
}
@Override
public boolean showEnchantLores() {
return true;
}
@Override | package net.swofty.types.generic.item.items.mining.vanilla;
public class StonePickaxe implements CustomSkyBlockItem, MiningTool, ExtraRarityDisplay, Enchantable, Reforgable {
@Override
public ItemStatistics getStatistics() {
return ItemStatistics.builder()
.with(ItemStatistic.MINING_SPEED, 110)
.with(ItemStatistic.DAMAGE, 20)
.build();
}
@Override
public int getBreakingPower() {
return 2;
}
@Override
public String getExtraRarityDisplay() {
return " PICKAXE";
}
@Override
public boolean showEnchantLores() {
return true;
}
@Override | public List<ItemGroups> getItemGroups() { | 2 | 2023-12-14 09:51:15+00:00 | 2k |
refutix/refutix | refutix-server/src/main/java/org/refutix/refutix/server/service/impl/LdapServiceImpl.java | [
{
"identifier": "UserType",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/enums/UserType.java",
"snippet": "public enum UserType {\n /** ldap user. */\n LDAP(1, \"LDAP\"),\n /** local user. */\n LOCAL(0, \"LOCAL\");\n\n private final int code;\n private final String type;\n\n public int getCode() {\n return this.code;\n }\n\n public String getType() {\n return this.type;\n }\n\n UserType(int code, String type) {\n this.code = code;\n this.type = type;\n }\n}"
},
{
"identifier": "User",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/data/model/User.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Table(name = \"refutix_user\")\npublic class User extends BaseModel {\n\n private static final long serialVersionUID = 1L;\n\n /** username. */\n private String username;\n\n /** password. */\n private String password;\n\n /** nickname. */\n private String nickname;\n\n /** login type (0:LOCAL,1:LDAP). */\n private Integer userType;\n\n /** mobile phone. */\n private String mobile;\n\n /** email. */\n private String email;\n\n /** is enable. */\n private Boolean enabled;\n\n /** is delete. */\n @TableLogic private Boolean isDelete;\n\n /** avatar url. */\n private String url;\n\n public boolean isAdmin() {\n return isAdmin(this.getId());\n }\n\n public static boolean isAdmin(Integer userId) {\n return userId != null && Constants.ADMIN_ID == userId;\n }\n}"
},
{
"identifier": "LdapService",
"path": "refutix-server/src/main/java/org/refutix/refutix/server/service/LdapService.java",
"snippet": "public interface LdapService {\n /**\n * get user info by ldap user identification.\n *\n * @param uid login name of ldap user\n * @return {@link Optional} of {@link User} when user not exist then return {@link\n * Optional#empty()}\n */\n Optional<User> getUser(String uid);\n\n /**\n * authenticate by ldap.\n *\n * @param name login name of ldap user\n * @param password login password of ldap user\n * @return {@link Optional} of {@link User} when user authenticate failed then return {@link\n * Optional#empty()}\n */\n Optional<User> authenticate(String name, String password);\n}"
}
] | import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.refutix.refutix.server.data.enums.UserType;
import org.refutix.refutix.server.data.model.User;
import org.refutix.refutix.server.service.LdapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.EqualsFilter;
import org.springframework.ldap.query.LdapQuery;
import org.springframework.ldap.query.LdapQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import java.util.List;
import java.util.Optional; | 1,514 | /*
* 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.refutix.server.service.impl;
/** ldap service impl. */
@Slf4j
@Service
public class LdapServiceImpl implements LdapService {
private static final UserAttributesMapperMapper MAPPER = new UserAttributesMapperMapper();
private static final String FILTER = "cn";
@Autowired private LdapTemplate ldapTemplate;
/**
* get user info by ldap user identification.
*
* @param uid login name of ldap user
* @return {@link Optional} of {@link User} when user not exist then return {@link
* Optional#empty()}
*/
@Override
public Optional<User> getUser(String uid) {
LdapQuery query = LdapQueryBuilder.query().where(FILTER).is(uid);
try {
List<User> users = ldapTemplate.search(query, MAPPER);
return CollectionUtils.isEmpty(users)
? Optional.empty()
: Optional.ofNullable(users.get(0));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
/**
* authenticate by ldap.
*
* @param name login name of ldap user
* @param password login password of ldap user
* @return {@link Optional} of {@link User} when user authenticate failed then return {@link
* Optional#empty()}
*/
@Override
public Optional<User> authenticate(String name, String password) {
EqualsFilter filter = new EqualsFilter(FILTER, name);
if (ldapTemplate.authenticate(StringUtils.EMPTY, filter.toString(), password)) {
return this.getUser(name);
}
return Optional.empty();
}
/** Attributes mapper from LDAP user to Local user. */
private static class UserAttributesMapperMapper implements AttributesMapper<User> {
/**
* Map the LDAP attributes to User object.
*
* @param attributes LDAP attributes
* @return User object
* @throws NamingException if there is an error during mapping
*/
@Override
public User mapFromAttributes(Attributes attributes) throws NamingException {
Attribute usernameAttr = attributes.get(FILTER);
Attribute nicknameAttr = attributes.get("sn");
Attribute email = attributes.get("email");
if (usernameAttr != null && nicknameAttr != null) {
User user = new User();
user.setUsername(usernameAttr.get().toString());
user.setNickname(nicknameAttr.get().toString());
user.setEmail(
Optional.ofNullable(email)
.map(
e -> {
try {
return e.get().toString();
} catch (NamingException ignore) {
}
return StringUtils.EMPTY;
})
.orElse(StringUtils.EMPTY)); | /*
* 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.refutix.server.service.impl;
/** ldap service impl. */
@Slf4j
@Service
public class LdapServiceImpl implements LdapService {
private static final UserAttributesMapperMapper MAPPER = new UserAttributesMapperMapper();
private static final String FILTER = "cn";
@Autowired private LdapTemplate ldapTemplate;
/**
* get user info by ldap user identification.
*
* @param uid login name of ldap user
* @return {@link Optional} of {@link User} when user not exist then return {@link
* Optional#empty()}
*/
@Override
public Optional<User> getUser(String uid) {
LdapQuery query = LdapQueryBuilder.query().where(FILTER).is(uid);
try {
List<User> users = ldapTemplate.search(query, MAPPER);
return CollectionUtils.isEmpty(users)
? Optional.empty()
: Optional.ofNullable(users.get(0));
} catch (EmptyResultDataAccessException e) {
return Optional.empty();
}
}
/**
* authenticate by ldap.
*
* @param name login name of ldap user
* @param password login password of ldap user
* @return {@link Optional} of {@link User} when user authenticate failed then return {@link
* Optional#empty()}
*/
@Override
public Optional<User> authenticate(String name, String password) {
EqualsFilter filter = new EqualsFilter(FILTER, name);
if (ldapTemplate.authenticate(StringUtils.EMPTY, filter.toString(), password)) {
return this.getUser(name);
}
return Optional.empty();
}
/** Attributes mapper from LDAP user to Local user. */
private static class UserAttributesMapperMapper implements AttributesMapper<User> {
/**
* Map the LDAP attributes to User object.
*
* @param attributes LDAP attributes
* @return User object
* @throws NamingException if there is an error during mapping
*/
@Override
public User mapFromAttributes(Attributes attributes) throws NamingException {
Attribute usernameAttr = attributes.get(FILTER);
Attribute nicknameAttr = attributes.get("sn");
Attribute email = attributes.get("email");
if (usernameAttr != null && nicknameAttr != null) {
User user = new User();
user.setUsername(usernameAttr.get().toString());
user.setNickname(nicknameAttr.get().toString());
user.setEmail(
Optional.ofNullable(email)
.map(
e -> {
try {
return e.get().toString();
} catch (NamingException ignore) {
}
return StringUtils.EMPTY;
})
.orElse(StringUtils.EMPTY)); | user.setUserType(UserType.LDAP.getCode()); | 0 | 2023-12-21 03:39:07+00:00 | 2k |
Tianscar/uxgl | desktop/src/main/java/unrefined/internal/X11/X11FontSupport.java | [
{
"identifier": "OperatingSystem",
"path": "desktop/src/main/java/unrefined/internal/OperatingSystem.java",
"snippet": "public final class OperatingSystem {\n\n private OperatingSystem() {\n throw new NotInstantiableError(OperatingSystem.class);\n }\n\n private static final String OS_NAME = System.getProperty(\"os.name\");\n private static final String OS_VERSION = System.getProperty(\"os.version\");\n private static final long OS_VERSION_LONG;\n static {\n int major = 1;\n int minor = 0;\n int micro = 0;\n int patch = 0;\n try {\n StringTokenizer st = new StringTokenizer(OperatingSystem.OS_VERSION, \"._-+\");\n major = Integer.parseInt(st.nextToken());\n minor = Integer.parseInt(st.nextToken());\n micro = Integer.parseInt(st.nextToken());\n patch = Integer.parseInt(st.nextToken());\n }\n catch (NumberFormatException | NoSuchElementException ignored) {\n }\n OS_VERSION_LONG = toVersionLong(major, minor, micro, patch);\n }\n\n public static final boolean IS_WINDOWS = OS_NAME.startsWith(\"Windows\");\n public static final boolean IS_WINDOWS_PE = IS_WINDOWS && \"X:\\\\Windows\\\\System32\".equalsIgnoreCase(System.getProperty(\"user.dir\"));\n public static final boolean IS_MAC = OS_NAME.startsWith(\"Mac\") || OS_NAME.startsWith(\"Darwin\");\n public static final boolean IS_X11 = !IS_WINDOWS && !IS_MAC; // Currently Wayland isn't supported\n\n public static final Charset NATIVE_CHARSET = Charset.forName(System.getProperty(\"sun.jnu.encoding\", System.getProperty(\"native.encoding\")));\n private static final byte[] NATIVE_STRING_TERMINATOR = \"\\0\".getBytes(NATIVE_CHARSET);\n public static final int NATIVE_CHAR_SIZE = NATIVE_STRING_TERMINATOR.length;\n public static final Charset WIDE_CHARSET = IS_WINDOWS ? StandardCharsets.UTF_16LE : Charset.forName(ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN) ? \"UTF-32BE\" : \"UTF-32LE\");\n private static final byte[] WIDE_CHAR_STRING_TERMINATOR = \"\\0\".getBytes(WIDE_CHARSET);\n public static final int WIDE_CHAR_SIZE = WIDE_CHAR_STRING_TERMINATOR.length;\n\n public static boolean isNativeStringCompatible(byte[] terminator) {\n return Arrays.equals(terminator, NATIVE_STRING_TERMINATOR);\n }\n\n public static boolean isWideCharStringCompatible(byte[] terminator) {\n return Arrays.equals(terminator, WIDE_CHAR_STRING_TERMINATOR);\n }\n\n public static String normalize(String pathname) {\n return (OperatingSystem.IS_WINDOWS || OperatingSystem.IS_MAC) ? pathname : normalizeToUNIXStyle(pathname);\n }\n\n private static String normalizeToUNIXStyle(String pathname) {\n if (pathname == null) return null;\n return pathname.toLowerCase(Locale.ENGLISH).replaceAll(\" \", \"-\");\n }\n\n public static boolean checkOSVersion(int major, int minor, int micro, int patch) {\n return OS_VERSION_LONG >= toVersionLong(major, minor, micro, patch);\n }\n\n private static long toVersionLong(int major, int minor, int micro, int patch) {\n return ((long) major << 48) | ((long) minor << 32) | ((long) micro << 16) | patch;\n }\n\n}"
},
{
"identifier": "NotInstantiableError",
"path": "base/src/main/java/unrefined/util/NotInstantiableError.java",
"snippet": "public class NotInstantiableError extends AssertionError {\n\n private static final long serialVersionUID = -4931611382965558909L;\n\n public NotInstantiableError() {\n this((String) null);\n }\n\n public NotInstantiableError(String message) {\n super((message == null || message.isEmpty()) ? \"This class is not instantiable\" : \"No \" + message + \" instances for you\");\n }\n\n public NotInstantiableError(Class<?> clazz) {\n this(clazz == null ? null : clazz.getName());\n }\n\n}"
}
] | import unrefined.internal.OperatingSystem;
import unrefined.util.NotInstantiableError;
import java.awt.Font;
import java.util.Locale;
import java.util.StringTokenizer; | 1,014 | package unrefined.internal.X11;
public final class X11FontSupport {
private X11FontSupport() {
throw new NotInstantiableError(X11FontSupport.class);
}
private static volatile Font defaultFont;
private static volatile float fontScale;
private static volatile int dpi;
private static volatile float density;
private static volatile float scaledDensity;
static { | package unrefined.internal.X11;
public final class X11FontSupport {
private X11FontSupport() {
throw new NotInstantiableError(X11FontSupport.class);
}
private static volatile Font defaultFont;
private static volatile float fontScale;
private static volatile int dpi;
private static volatile float density;
private static volatile float scaledDensity;
static { | if (OperatingSystem.IS_X11) { | 0 | 2023-12-15 19:03:31+00:00 | 2k |
jlokitha/layered-architecture-jlokitha | src/main/java/lk/jl/layeredarchitecture/bo/custom/impl/MainBOImpl.java | [
{
"identifier": "MainBO",
"path": "src/main/java/lk/jl/layeredarchitecture/bo/custom/MainBO.java",
"snippet": "public interface MainBO extends SuperBO {\n ArrayList<CustomerOrderDetailsDTO> customerOrderDetails() throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "DAOFactory",
"path": "src/main/java/lk/jl/layeredarchitecture/dao/DAOFactory.java",
"snippet": "public class DAOFactory {\n private static DAOFactory daoFactory;\n\n private DAOFactory() {\n\n }\n\n public static DAOFactory getDaoFactory() {\n return (daoFactory == null) ? daoFactory = new DAOFactory() : daoFactory;\n }\n\n public enum DAOType {\n CUSTOMER,ITEM,ORDER,ORDER_DETAIL,QUERY\n }\n\n public SuperDAO getDAO(DAOType daoType) {\n switch (daoType) {\n case CUSTOMER:\n return new CustomerDAOImpl();\n case ITEM:\n return new ItemDAOImpl();\n case ORDER:\n return new OrdersDAOImpl();\n case ORDER_DETAIL:\n return new OrderDetailDAOImpl();\n case QUERY:\n return new QueryDAOImpl();\n default:\n return null;\n }\n }\n}"
},
{
"identifier": "QueryDAO",
"path": "src/main/java/lk/jl/layeredarchitecture/dao/custom/QueryDAO.java",
"snippet": "public interface QueryDAO extends SuperDAO {\n ArrayList<CustomerOrderDetailsDTO> customerOrderDetails() throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "CustomerOrderDetailsDTO",
"path": "src/main/java/lk/jl/layeredarchitecture/dto/CustomerOrderDetailsDTO.java",
"snippet": "public class CustomerOrderDetailsDTO {\n private String orderId;\n private String total;\n private String date;\n private String id;\n private String name;\n private String address;\n\n public CustomerOrderDetailsDTO() {\n }\n\n public CustomerOrderDetailsDTO(String orderId, String total, String date, String id, String name, String address) {\n this.orderId = orderId;\n this.total = total;\n this.date = date;\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getOrderId() {\n return orderId;\n }\n\n public void setOrderId(String orderId) {\n this.orderId = orderId;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getTotal() {\n return total;\n }\n\n public void setTotal(String total) {\n this.total = total;\n }\n\n @Override\n public String toString() {\n return \"CustomerOrderDetailsDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n \", orderId='\" + orderId + '\\'' +\n \", date='\" + date + '\\'' +\n '}';\n }\n}"
}
] | import lk.jl.layeredarchitecture.bo.custom.MainBO;
import lk.jl.layeredarchitecture.dao.DAOFactory;
import lk.jl.layeredarchitecture.dao.custom.QueryDAO;
import lk.jl.layeredarchitecture.dto.CustomerOrderDetailsDTO;
import java.sql.SQLException;
import java.util.ArrayList; | 921 | package lk.jl.layeredarchitecture.bo.custom.impl;
public class MainBOImpl implements MainBO {
QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO( DAOFactory.DAOType.QUERY );
@Override | package lk.jl.layeredarchitecture.bo.custom.impl;
public class MainBOImpl implements MainBO {
QueryDAO queryDAO = (QueryDAO) DAOFactory.getDaoFactory().getDAO( DAOFactory.DAOType.QUERY );
@Override | public ArrayList<CustomerOrderDetailsDTO> customerOrderDetails() throws SQLException, ClassNotFoundException { | 3 | 2023-12-16 04:21:58+00:00 | 2k |
DreamingLri/EasyAreaCodes | src/main/java/com/project/eac/service/impl/DetailsServiceImpl.java | [
{
"identifier": "Change",
"path": "src/main/java/com/project/eac/entity/Change.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Accessors(chain = true)\n@TableName(\"changes\")\npublic class Change {\n @TableId\n private Integer id;\n\n private Integer code;\n private String name;\n private Integer start;\n private Integer newCode;\n private String newName;\n private Integer newStart;\n private Integer time;\n private Integer detailsId;\n}"
},
{
"identifier": "Details",
"path": "src/main/java/com/project/eac/entity/Details.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Accessors(chain = true)\n@TableName(\"details\")\npublic class Details {\n @TableId\n private Integer id;\n\n private String text;\n}"
},
{
"identifier": "DetailVO",
"path": "src/main/java/com/project/eac/entity/vo/DetailVO.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class DetailVO {\n private Integer id;\n private Integer code;\n private String name;\n private Integer start;\n private Integer newCode;\n private String newName;\n private Integer newStart;\n private Integer time;\n private String text;\n}"
},
{
"identifier": "UpdateDetailException",
"path": "src/main/java/com/project/eac/handler/exceptions/UpdateDetailException.java",
"snippet": "public class UpdateDetailException extends GlobalException {\n public UpdateDetailException(String message) {\n super(UPDATE_DETAIL_ERROR.getCode(), message);\n }\n}"
},
{
"identifier": "ChangesMapper",
"path": "src/main/java/com/project/eac/mapper/ChangesMapper.java",
"snippet": "@Mapper\npublic interface ChangesMapper extends BaseMapper<Change> {\n\n}"
},
{
"identifier": "DetailsMapper",
"path": "src/main/java/com/project/eac/mapper/DetailsMapper.java",
"snippet": "@Mapper\npublic interface DetailsMapper extends BaseMapper<Details> {\n\n}"
},
{
"identifier": "BeanCopyUtils",
"path": "src/main/java/com/project/eac/mapper/struct/BeanCopyUtils.java",
"snippet": "@Mapper\npublic interface BeanCopyUtils {\n BeanCopyUtils INSTANCE = Mappers.getMapper(BeanCopyUtils.class);\n\n ChangeVO toChangeVO(Change change);\n DetailVO toDetailVO(Change change);\n Change toChange(DetailVO detailVO);\n}"
},
{
"identifier": "DetailsService",
"path": "src/main/java/com/project/eac/service/DetailsService.java",
"snippet": "public interface DetailsService extends IService<Details> {\n\n Details getDetailByCodeAndNewCodeAndTime(Integer code, Integer newCode, Integer time);\n\n List<DetailVO> getDetailByChangesList(List<Change> changes);\n\n DetailVO getDetailByChange(Change change);\n\n boolean updateDetail(DetailVO detailVO);\n\n boolean updateDetails(List<DetailVO> detailVOList);\n\n// DetailVO getDetailUpdate(Change change);\n//\n// List<DetailVO> getDetailUpdates(List<Change> changes);\n}"
}
] | import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.eac.entity.Change;
import com.project.eac.entity.Details;
import com.project.eac.entity.vo.DetailVO;
import com.project.eac.handler.exceptions.UpdateDetailException;
import com.project.eac.mapper.ChangesMapper;
import com.project.eac.mapper.DetailsMapper;
import com.project.eac.mapper.struct.BeanCopyUtils;
import com.project.eac.service.DetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List; | 1,057 | package com.project.eac.service.impl;
@Service("detailsService")
@RequiredArgsConstructor
public class DetailsServiceImpl extends ServiceImpl<DetailsMapper, Details> implements DetailsService {
private final ChangesMapper changesMapper;
@Override
public Details getDetailByCodeAndNewCodeAndTime(Integer code, Integer newCode, Integer time) {
Details details = new Details();
Integer detailsId = changesMapper.selectOne(new LambdaQueryWrapper<Change>()
.eq(Change::getCode, code)
.eq(Change::getNewCode, newCode)
.eq(Change::getTime, time)).getDetailsId();
details = baseMapper.selectOne(new LambdaQueryWrapper<Details>()
.eq(Details::getId, detailsId));
return details;
}
@Override
public List<DetailVO> getDetailByChangesList(List<Change> changes) {
List<DetailVO> list = new ArrayList<>();
for (Change change : changes) {
Integer detailsId = changesMapper.selectOne(new LambdaQueryWrapper<Change>()
.eq(Change::getCode, change.getCode())
.eq(Change::getNewCode, change.getNewCode())
.eq(Change::getTime, change.getTime())).getDetailsId();
Details detail = baseMapper.selectById(detailsId); | package com.project.eac.service.impl;
@Service("detailsService")
@RequiredArgsConstructor
public class DetailsServiceImpl extends ServiceImpl<DetailsMapper, Details> implements DetailsService {
private final ChangesMapper changesMapper;
@Override
public Details getDetailByCodeAndNewCodeAndTime(Integer code, Integer newCode, Integer time) {
Details details = new Details();
Integer detailsId = changesMapper.selectOne(new LambdaQueryWrapper<Change>()
.eq(Change::getCode, code)
.eq(Change::getNewCode, newCode)
.eq(Change::getTime, time)).getDetailsId();
details = baseMapper.selectOne(new LambdaQueryWrapper<Details>()
.eq(Details::getId, detailsId));
return details;
}
@Override
public List<DetailVO> getDetailByChangesList(List<Change> changes) {
List<DetailVO> list = new ArrayList<>();
for (Change change : changes) {
Integer detailsId = changesMapper.selectOne(new LambdaQueryWrapper<Change>()
.eq(Change::getCode, change.getCode())
.eq(Change::getNewCode, change.getNewCode())
.eq(Change::getTime, change.getTime())).getDetailsId();
Details detail = baseMapper.selectById(detailsId); | DetailVO detailVO = BeanCopyUtils.INSTANCE.toDetailVO(change); | 6 | 2023-12-19 02:06:26+00:00 | 2k |
lemonguge/autogen4j | src/test/java/cn/homj/autogen4j/support/ClientTest2.java | [
{
"identifier": "EmbeddingRequest",
"path": "src/main/java/cn/homj/autogen4j/support/dashscope/embed/EmbeddingRequest.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class EmbeddingRequest {\n /**\n * 模型\n * <p>\n * eg: text-embedding-v1\n */\n private String model;\n /**\n * 文本\n */\n private List<String> texts;\n /**\n * 文本类型\n * <ul>\n * <li>query</li>\n * <li>document</li>\n * </ul>\n */\n private String textType;\n\n public EmbeddingRequest addText(String text) {\n if (texts == null) {\n texts = new ArrayList<>();\n }\n texts.add(text);\n return this;\n }\n}"
},
{
"identifier": "EmbeddingResponse",
"path": "src/main/java/cn/homj/autogen4j/support/dashscope/embed/EmbeddingResponse.java",
"snippet": "@Data\npublic class EmbeddingResponse implements ErrorResponse {\n /**\n * 请求 ID\n */\n @JSONField(name = \"request_id\")\n private String requestId;\n /**\n * 错误码\n */\n @JSONField(name = \"code\")\n private String errorCode;\n /**\n * 错误信息\n */\n @JSONField(name = \"message\")\n private String errorMessage;\n /**\n * 结果信息\n */\n private Output output;\n /**\n * 计量信息\n */\n private Usage usage;\n\n /**\n * 是否成功\n *\n * @return\n */\n public boolean isSuccess() {\n return errorCode == null;\n }\n\n @Data\n public static class Output {\n private List<Embedding> embeddings;\n }\n\n @Data\n public static class Embedding {\n @JSONField(name = \"text_index\")\n private Integer index;\n /**\n * 向量维度 1536\n */\n @JSONField(name = \"embedding\")\n private float[] vector;\n }\n\n @Data\n public static class Usage {\n /**\n * 请求文本转换成 Token 后的长度\n */\n @JSONField(name = \"total_tokens\")\n private Integer totalTokens;\n }\n}"
},
{
"identifier": "Embedding",
"path": "src/main/java/cn/homj/autogen4j/support/dashscope/embed/EmbeddingResponse.java",
"snippet": "@Data\npublic static class Embedding {\n @JSONField(name = \"text_index\")\n private Integer index;\n /**\n * 向量维度 1536\n */\n @JSONField(name = \"embedding\")\n private float[] vector;\n}"
},
{
"identifier": "embeddingApiKey",
"path": "src/test/java/cn/homj/autogen4j/Definition.java",
"snippet": "public static String embeddingApiKey;"
}
] | import java.util.List;
import com.alibaba.fastjson2.JSON;
import cn.homj.autogen4j.support.dashscope.embed.EmbeddingRequest;
import cn.homj.autogen4j.support.dashscope.embed.EmbeddingResponse;
import cn.homj.autogen4j.support.dashscope.embed.EmbeddingResponse.Embedding;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static cn.homj.autogen4j.Definition.embeddingApiKey; | 903 | package cn.homj.autogen4j.support;
public class ClientTest2 {
private final Client client = new Client();
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void embed() {
EmbeddingRequest request = new EmbeddingRequest();
request.setModel("text-embedding-v1");
request.addText("hello world"); | package cn.homj.autogen4j.support;
public class ClientTest2 {
private final Client client = new Client();
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void embed() {
EmbeddingRequest request = new EmbeddingRequest();
request.setModel("text-embedding-v1");
request.addText("hello world"); | EmbeddingResponse response = client.embed(embeddingApiKey, request); | 1 | 2023-12-15 01:43:11+00:00 | 2k |
wenbochang888/min-read-book | house/src/main/java/com/tianya/test/LoanCreditExpireDate.java | [
{
"identifier": "RulerEnum",
"path": "house/src/main/java/com/tianya/test/common/RulerEnum.java",
"snippet": "public enum RulerEnum {\n\n\tEXAMPLE_RULER(\"0\", \"exampleRuler\", \"所有活动的一些规则\"),\n\n\tLOAN_CREDIT_EXPIRE_DATE(\"1\", \"loanCreditExpireDate\", \"授信有效期内\"),\n\n\tCREDIT_PASS_NOT_LOAN_DATE(\"2\", \"creditPassNotLoanDate\", \"授信通过但未用信\"),\n\n\t;\n\n\tprivate String code;\n\n\tprivate String name;\n\n\tprivate String desc;\n\n\tRulerEnum(String code, String name, String desc) {\n\t\tthis.code = code;\n\t\tthis.name = name;\n\t\tthis.desc = desc;\n\t}\n\n\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\n\tpublic void setCode(String code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDesc() {\n\t\treturn desc;\n\t}\n\n\tpublic void setDesc(String desc) {\n\t\tthis.desc = desc;\n\t}\n}"
},
{
"identifier": "TxnHandler",
"path": "house/src/main/java/com/tianya/test/common/TxnHandler.java",
"snippet": "@Slf4j\npublic abstract class TxnHandler<T> implements Handler<T, Boolean> {\n\tprotected static final Boolean CONTINUE = Boolean.TRUE;\n\tprotected static final Boolean FINISH = Boolean.FALSE;\n\n\n\t@Override\n\tpublic Boolean handle(T context) {\n\t\tBoolean result = Boolean.TRUE;\n\t\tBoolean preHandle = preHandle(context);\n\t\tString handlerName = getClass().getSimpleName();\n\t\tlog.info(\"[活动执行规则]{} preHandle: {}\", handlerName, preHandle);\n\n\t\tif (preHandle) {\n\t\t\ttry {\n\t\t\t\tlog.info(\"[活动执行规则] {} executing.\", handlerName);\n\t\t\t\tresult = onHandle(context);\n\t\t\t} catch (Throwable e) {\n\t\t\t\tlog.warn(\"error = {}\", e.getMessage(), e);\n\t\t\t\tthrow e;\n\t\t\t} finally {\n\t\t\t\tpostHandle(context);\n\t\t\t}\n\t\t}\n\n\t\tlog.info(\"[活动执行规则] {} result: {}\", handlerName, result);\n\t\treturn result;\n\t}\n\n\n\t/**\n\t * 处理器前置处理,在处理业务逻辑前执行\n\t *\n\t * @param context\n\t *\n\t * @return 如果返回{@code true},进入处理器处理业务逻辑,否则跳过该处理器\n\t */\n\tprotected Boolean preHandle(T context) {\n\t\treturn true;\n\t}\n\n\t/**\n\t * 处理器业务处理单元\n\t *\n\t * @param context\n\t *\n\t * @return 如果返回{@code CONTINUE}继续执行下一个处理器,返回{@code FINISH}结束执行处理器链\n\t */\n\tprotected abstract Boolean onHandle(T context);\n\n\t/**\n\t * 处理器后置处理,在处理业务逻辑后执行\n\t *\n\t * @param context\n\t */\n\tprotected void postHandle(T context) {\n\t}\n\n\tpublic abstract String getRulerHandlerName();\n}"
}
] | import com.tianya.test.common.RulerEnum;
import com.tianya.test.common.TxnHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component; | 897 | package com.tianya.test;
/**
* @author changwenbo
* @date 2023/7/28 10:19
*/
@Slf4j
@Component | package com.tianya.test;
/**
* @author changwenbo
* @date 2023/7/28 10:19
*/
@Slf4j
@Component | public class LoanCreditExpireDate extends TxnHandler<ActivityContext> { | 1 | 2023-12-18 13:31:20+00:00 | 2k |
Valerde/vadb | va-collection/src/main/java/com/sovava/vacollection/api/VaMap.java | [
{
"identifier": "VaBiConsumer",
"path": "va-collection/src/main/java/com/sovava/vacollection/api/function/VaBiConsumer.java",
"snippet": "@FunctionalInterface\npublic interface VaBiConsumer<F, S> {\n void apply(F f, S s);\n}"
},
{
"identifier": "VaBiFunction",
"path": "va-collection/src/main/java/com/sovava/vacollection/api/function/VaBiFunction.java",
"snippet": "@FunctionalInterface\npublic interface VaBiFunction<F,S,R> {\n R apply(F f,S s);\n}"
},
{
"identifier": "VaFunction",
"path": "va-collection/src/main/java/com/sovava/vacollection/api/function/VaFunction.java",
"snippet": "@FunctionalInterface\npublic interface VaFunction <T,R>{\n R apply(T t);\n}"
}
] | import com.sovava.vacollection.api.function.VaBiConsumer;
import com.sovava.vacollection.api.function.VaBiFunction;
import com.sovava.vacollection.api.function.VaFunction;
import java.util.Objects; | 1,040 | package com.sovava.vacollection.api;
/**
* description: map类接口
* <p>
* TODO:some default methods is unsolved
*
* @Author sovava
* @Date 12/21/23 11:44 PM
*/
public interface VaMap<K, V> {
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containValue(Object value);
V get(Object key);
V put(K key, V value);
V remove(Object key);
void putAll(VaMap<? extends K, ? extends V> m);
void clear();
VaSet<K> keySet();
VaCollection<V> values();
VaSet<VaEntry<K, V>> entrySet();
boolean equals(Object o);
int hashCode();
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue;
}
default void forEach(VaBiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (VaEntry<K, V> e : entrySet()) {
K k = e.getKey();
V v = e.getValue();
action.apply(k, v);
}
}
default void replaceAll(VaBiFunction<? super K, ? super V, ? extends V> action) {
Objects.requireNonNull(action);
for (VaEntry<K, V> e : entrySet()) {
K k = e.getKey();
V v = e.getValue();
V res = action.apply(k, v);
e.setValue(res);
}
}
default V putIfAbsent(K key, V value) {
V v = get(key);
if (null == v) {
v = put(key, value);
}
return v;
}
default boolean remove(Object key, Object value) {
V oldV = get(key);
if (!Objects.equals(oldV, value) || (value == null && containsKey(key))) {
return false;
}
remove(key);
return true;
}
/**
* description: 当Map中key对应的value与oldValue对应时才将其替换为newValue
*
* @return boolean
* @Author sovava
* @Date 12/18/23 9:50 PM
* @param: key - [K]
* @param: oldValue - [V]
* @param: newValue - [V]
*/
default boolean replace(K key, V oldValue, V newValue) {
V oldV = get(key);
if (!Objects.equals(oldV, oldValue) || (oldValue == null && containsKey(key))) {
return false;
}
put(key, newValue);
return true;
}
/**
* description: 当key存在时,才替换
*
* @return V
* @Author sovava
* @Date 12/18/23 9:52 PM
* @param: key - [K]
* @param: value - [V]
*/
default V replace(K key, V value) {
V v = get(key);
if (v != null && containsKey(key)) {
v = put(key, value);
}
return v;
}
/**
* description: 如果map中不存在给定的key,那么就用给定的方法计算value并插入map中
*
* @return V
* @Author sovava
* @Date 12/18/23 9:56 PM
* @param: key - [K]
* @param: mappingFunction - [com.sovava.vacollection.api.function.VaFunction<?superK]
*/ | package com.sovava.vacollection.api;
/**
* description: map类接口
* <p>
* TODO:some default methods is unsolved
*
* @Author sovava
* @Date 12/21/23 11:44 PM
*/
public interface VaMap<K, V> {
int size();
boolean isEmpty();
boolean containsKey(Object key);
boolean containValue(Object value);
V get(Object key);
V put(K key, V value);
V remove(Object key);
void putAll(VaMap<? extends K, ? extends V> m);
void clear();
VaSet<K> keySet();
VaCollection<V> values();
VaSet<VaEntry<K, V>> entrySet();
boolean equals(Object o);
int hashCode();
default V getOrDefault(Object key, V defaultValue) {
V v;
return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue;
}
default void forEach(VaBiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (VaEntry<K, V> e : entrySet()) {
K k = e.getKey();
V v = e.getValue();
action.apply(k, v);
}
}
default void replaceAll(VaBiFunction<? super K, ? super V, ? extends V> action) {
Objects.requireNonNull(action);
for (VaEntry<K, V> e : entrySet()) {
K k = e.getKey();
V v = e.getValue();
V res = action.apply(k, v);
e.setValue(res);
}
}
default V putIfAbsent(K key, V value) {
V v = get(key);
if (null == v) {
v = put(key, value);
}
return v;
}
default boolean remove(Object key, Object value) {
V oldV = get(key);
if (!Objects.equals(oldV, value) || (value == null && containsKey(key))) {
return false;
}
remove(key);
return true;
}
/**
* description: 当Map中key对应的value与oldValue对应时才将其替换为newValue
*
* @return boolean
* @Author sovava
* @Date 12/18/23 9:50 PM
* @param: key - [K]
* @param: oldValue - [V]
* @param: newValue - [V]
*/
default boolean replace(K key, V oldValue, V newValue) {
V oldV = get(key);
if (!Objects.equals(oldV, oldValue) || (oldValue == null && containsKey(key))) {
return false;
}
put(key, newValue);
return true;
}
/**
* description: 当key存在时,才替换
*
* @return V
* @Author sovava
* @Date 12/18/23 9:52 PM
* @param: key - [K]
* @param: value - [V]
*/
default V replace(K key, V value) {
V v = get(key);
if (v != null && containsKey(key)) {
v = put(key, value);
}
return v;
}
/**
* description: 如果map中不存在给定的key,那么就用给定的方法计算value并插入map中
*
* @return V
* @Author sovava
* @Date 12/18/23 9:56 PM
* @param: key - [K]
* @param: mappingFunction - [com.sovava.vacollection.api.function.VaFunction<?superK]
*/ | default V computeIfAbsent(K key, VaFunction<? super K, ? extends V> mappingFunction) { | 2 | 2023-12-17 13:29:10+00:00 | 2k |
chamithKavinda/layered-architecture-ChamithKavinda | src/main/java/com/example/layeredarchitecture/bo/custom/PlaceOrderBO.java | [
{
"identifier": "SuperBO",
"path": "src/main/java/com/example/layeredarchitecture/bo/SuperBO.java",
"snippet": "public interface SuperBO {\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/com/example/layeredarchitecture/dto/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO(String id) {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "ItemDTO",
"path": "src/main/java/com/example/layeredarchitecture/dto/ItemDTO.java",
"snippet": "public class ItemDTO implements Serializable {\n private String code;\n private String description;\n private BigDecimal unitPrice;\n private int qtyOnHand;\n\n public ItemDTO() {\n }\n\n public ItemDTO(String code, String description, BigDecimal unitPrice, int qtyOnHand) {\n this.code = code;\n this.description = description;\n this.unitPrice = unitPrice;\n this.qtyOnHand = qtyOnHand;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n public int getQtyOnHand() {\n return qtyOnHand;\n }\n\n public void setQtyOnHand(int qtyOnHand) {\n this.qtyOnHand = qtyOnHand;\n }\n\n @Override\n public String toString() {\n return \"ItemTM{\" +\n \"code='\" + code + '\\'' +\n \", description='\" + description + '\\'' +\n \", unitPrice=\" + unitPrice +\n \", qtyOnHand=\" + qtyOnHand +\n '}';\n }\n}"
},
{
"identifier": "OrderDetailDTO",
"path": "src/main/java/com/example/layeredarchitecture/dto/OrderDetailDTO.java",
"snippet": "public class OrderDetailDTO implements Serializable {\n\n private String oid;\n private String itemCode;\n private int qty;\n private BigDecimal unitPrice;\n\n public OrderDetailDTO() {\n }\n\n public OrderDetailDTO(String itemCode, int qty, BigDecimal unitPrice) {\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public OrderDetailDTO(String oid, String itemCode, int qty, BigDecimal unitPrice) {\n this.oid = oid;\n this.itemCode = itemCode;\n this.qty = qty;\n this.unitPrice = unitPrice;\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getItemCode() {\n return itemCode;\n }\n\n public void setItemCode(String itemCode) {\n this.itemCode = itemCode;\n }\n\n public int getQty() {\n return qty;\n }\n\n public void setQty(int qty) {\n this.qty = qty;\n }\n\n public BigDecimal getUnitPrice() {\n return unitPrice;\n }\n\n public void setUnitPrice(BigDecimal unitPrice) {\n this.unitPrice = unitPrice;\n }\n\n @Override\n public String toString() {\n return \"OrderDetailDTO{\" +\n \"itemCode='\" + itemCode + '\\'' +\n \", qty=\" + qty +\n \", unitPrice=\" + unitPrice +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.bo.SuperBO;
import com.example.layeredarchitecture.dto.CustomerDTO;
import com.example.layeredarchitecture.dto.ItemDTO;
import com.example.layeredarchitecture.dto.OrderDetailDTO;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List; | 1,227 | package com.example.layeredarchitecture.bo.custom;
public interface PlaceOrderBO extends SuperBO {
boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException ;
CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException;
| package com.example.layeredarchitecture.bo.custom;
public interface PlaceOrderBO extends SuperBO {
boolean placeOrder(String orderId, LocalDate orderDate, String customerId, List<OrderDetailDTO> orderDetails) throws SQLException, ClassNotFoundException ;
CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException;
| ItemDTO searchItem(String code) throws SQLException, ClassNotFoundException; | 2 | 2023-12-16 04:21:25+00:00 | 2k |
ZakariaAitAli/MesDepensesTelecom | app/src/main/java/com/gi3/mesdepensestelecom/database/SupplementRepository.java | [
{
"identifier": "Recharge",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/Models/Recharge.java",
"snippet": "public class Recharge {\n\n public int Id;\n public int idUser;\n public float prix;\n public String date;\n public int operateur;\n\n\n public Recharge(float v, int operator, int userId, String date) {\n this.prix= v;\n this.operateur= operator;\n this.idUser= userId;\n this.date = date;\n }\n public Recharge() {\n\n }\n}"
},
{
"identifier": "Supplement",
"path": "app/src/main/java/com/gi3/mesdepensestelecom/Models/Supplement.java",
"snippet": "public class Supplement {\n public int id ;\n public int idAbonnement ;\n public float prix ;\n\n public String date ;\n\n public Supplement( int idAbonnement, float prix, String date ){\n this.idAbonnement =idAbonnement;\n this.prix=prix;\n this.date=date;\n }\n public Supplement() {\n\n }\n}"
}
] | import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.gi3.mesdepensestelecom.Models.Recharge;
import com.gi3.mesdepensestelecom.Models.Supplement;
import java.util.HashMap; | 744 | package com.gi3.mesdepensestelecom.database;
public class SupplementRepository {
private final DatabaseHelper databaseHelper;
public SupplementRepository(Context context) {
this.databaseHelper = new DatabaseHelper(context);
}
public HashMap<Integer, String> getAbonnementsMapByUserId(int userId){
SQLiteDatabase db = databaseHelper.getReadableDatabase();
String[] projection = {"id", "typeAbonnement" /* Add other columns as needed */};
String selection = "userId = ?";
String[] selectionArgs = {String.valueOf(userId)};
Cursor cursor = db.query("abonnements", projection, selection, selectionArgs, null, null, null);
HashMap<Integer, String> abonnementsMap = new HashMap<>();
if (cursor != null && cursor.moveToFirst()) {
do {
int id_abonnement = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
int typeAbonnement = cursor.getInt(cursor.getColumnIndexOrThrow("typeAbonnement"));
String transformedType = transformTypeAbonnement(typeAbonnement);
// Concatenate transformedType with id
String value = transformedType + "-" + id_abonnement;
// Add to the HashMap
abonnementsMap.put(id_abonnement, value);
} while (cursor.moveToNext());
// Close the cursor after use
cursor.close();
}
Log.d("abonnementsMapSize", String.valueOf(abonnementsMap.size()));
return abonnementsMap;
}
static String transformTypeAbonnement(int typeAbonnement) {
// You can implement your transformation logic here
switch (typeAbonnement) {
case 0:
return "fibreOptique";
case 1:
return "WIFI";
case 2:
return "MobileAppel";
case 3:
return "Fixe";
case 4:
return "MobileInternet";
default:
return "Unknown";
}
}
| package com.gi3.mesdepensestelecom.database;
public class SupplementRepository {
private final DatabaseHelper databaseHelper;
public SupplementRepository(Context context) {
this.databaseHelper = new DatabaseHelper(context);
}
public HashMap<Integer, String> getAbonnementsMapByUserId(int userId){
SQLiteDatabase db = databaseHelper.getReadableDatabase();
String[] projection = {"id", "typeAbonnement" /* Add other columns as needed */};
String selection = "userId = ?";
String[] selectionArgs = {String.valueOf(userId)};
Cursor cursor = db.query("abonnements", projection, selection, selectionArgs, null, null, null);
HashMap<Integer, String> abonnementsMap = new HashMap<>();
if (cursor != null && cursor.moveToFirst()) {
do {
int id_abonnement = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
int typeAbonnement = cursor.getInt(cursor.getColumnIndexOrThrow("typeAbonnement"));
String transformedType = transformTypeAbonnement(typeAbonnement);
// Concatenate transformedType with id
String value = transformedType + "-" + id_abonnement;
// Add to the HashMap
abonnementsMap.put(id_abonnement, value);
} while (cursor.moveToNext());
// Close the cursor after use
cursor.close();
}
Log.d("abonnementsMapSize", String.valueOf(abonnementsMap.size()));
return abonnementsMap;
}
static String transformTypeAbonnement(int typeAbonnement) {
// You can implement your transformation logic here
switch (typeAbonnement) {
case 0:
return "fibreOptique";
case 1:
return "WIFI";
case 2:
return "MobileAppel";
case 3:
return "Fixe";
case 4:
return "MobileInternet";
default:
return "Unknown";
}
}
| public long insertRechargeSupplement(Supplement supplement) { | 1 | 2023-12-20 13:43:21+00:00 | 2k |
litongjava/next-jfinal | src/main/java/com/jfinal/servlet/http/HttpServletRequestWrapper.java | [
{
"identifier": "AsyncContext",
"path": "src/main/java/com/jfinal/servlet/AsyncContext.java",
"snippet": "public class AsyncContext {\n\n}"
},
{
"identifier": "DispatcherType",
"path": "src/main/java/com/jfinal/servlet/DispatcherType.java",
"snippet": "public class DispatcherType {\n\n}"
},
{
"identifier": "RequestDispatcher",
"path": "src/main/java/com/jfinal/servlet/RequestDispatcher.java",
"snippet": "public class RequestDispatcher {\n\n public void forward(HttpServletRequest request, HttpServletResponse response) {\n // TODO Auto-generated method stub\n \n }\n\n}"
},
{
"identifier": "ServletContext",
"path": "src/main/java/com/jfinal/servlet/ServletContext.java",
"snippet": "public class ServletContext {\n private String contextPath = null;\n\n public String getContextPath() {\n return contextPath;\n }\n\n public String getRealPath(String string) {\n // TODO Auto-generated method stub\n return null;\n }\n\n public String getMimeType(String name) {\n // TODO Auto-generated method stub\n return null;\n }\n\n public void setContextPath(String contextPath) {\n this.contextPath=contextPath;\n }\n\n}"
},
{
"identifier": "ServletException",
"path": "src/main/java/com/jfinal/servlet/ServletException.java",
"snippet": "public class ServletException extends RuntimeException{\n\n}"
},
{
"identifier": "ServletInputStream",
"path": "src/main/java/com/jfinal/servlet/ServletInputStream.java",
"snippet": "public class ServletInputStream extends InputStream {\n\n @Override\n public int read() throws IOException {\n // TODO Auto-generated method stub\n return 0;\n }\n\n}"
},
{
"identifier": "ServletRequest",
"path": "src/main/java/com/jfinal/servlet/ServletRequest.java",
"snippet": "public class ServletRequest {\n\n}"
},
{
"identifier": "ServletResponse",
"path": "src/main/java/com/jfinal/servlet/ServletResponse.java",
"snippet": "public class ServletResponse {\n\n}"
},
{
"identifier": "Part",
"path": "src/main/java/com/jfinal/servlet/multipart/Part.java",
"snippet": "public class Part {\n\n}"
}
] | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import com.jfinal.servlet.AsyncContext;
import com.jfinal.servlet.DispatcherType;
import com.jfinal.servlet.RequestDispatcher;
import com.jfinal.servlet.ServletContext;
import com.jfinal.servlet.ServletException;
import com.jfinal.servlet.ServletInputStream;
import com.jfinal.servlet.ServletRequest;
import com.jfinal.servlet.ServletResponse;
import com.jfinal.servlet.multipart.Part; | 1,433 | public String getContentType() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getProtocol() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getScheme() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerName() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getServerPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getRemoteAddr() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRemoteHost() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAttribute(String name, Object o) {
// TODO Auto-generated method stub
}
@Override
public void removeAttribute(String name) {
// TODO Auto-generated method stub
}
@Override
public Locale getLocale() {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration<Locale> getLocales() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isSecure() {
// TODO Auto-generated method stub
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRealPath(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getRemotePort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getLocalName() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getLocalAddr() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getLocalPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public ServletContext getServletContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
// TODO Auto-generated method stub
return null;
}
@Override | package com.jfinal.servlet.http;
public class HttpServletRequestWrapper implements HttpServletRequest{
public HttpServletRequestWrapper(HttpServletRequest request) {
// TODO Auto-generated constructor stub
}
@Override
public Map<String, String[]> getParameterMap() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getParameter(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public String[] getParameterValues(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration<String> getParameterNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public BufferedReader getReader() throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration<String> getAttributeNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getCharacterEncoding() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
}
@Override
public int getContentLength() {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getContentLengthLong() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getContentType() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getProtocol() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getScheme() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerName() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getServerPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getRemoteAddr() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRemoteHost() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAttribute(String name, Object o) {
// TODO Auto-generated method stub
}
@Override
public void removeAttribute(String name) {
// TODO Auto-generated method stub
}
@Override
public Locale getLocale() {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration<Locale> getLocales() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isSecure() {
// TODO Auto-generated method stub
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getRealPath(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getRemotePort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getLocalName() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getLocalAddr() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getLocalPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public ServletContext getServletContext() {
// TODO Auto-generated method stub
return null;
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
// TODO Auto-generated method stub
return null;
}
@Override | public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) | 6 | 2023-12-19 10:58:33+00:00 | 2k |
ViniciusJPSilva/TSI-PizzeriaExpress | PizzeriaExpress/src/main/java/br/vjps/tsi/pe/managedbeans/EmployeeMB.java | [
{
"identifier": "EmployeeDAO",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/dao/EmployeeDAO.java",
"snippet": "public class EmployeeDAO implements Closeable {\n\tprivate EntityManager manager;\n\n\t/**\n\t * Construtor padrão que inicializa o EntityManager usando a classe utilitária\n\t * JPAUtil.\n\t */\n\tpublic EmployeeDAO() {\n\t\tmanager = new JPAUtil().getEntityManager();\n\t}\n\n\t/**\n\t * Valida as credenciais de um usuário para fins de autenticação.\n\t *\n\t * @param employee O funcionário cujas credenciais estão sendo validadas.\n\t * \n\t * @return O funcionário autenticado ou null se as credenciais forem inválidas.\n\t * \n\t * @throws IllegalArgumentException Se o cliente fornecido for nulo.\n\t */\n\tpublic Employee validate(Employee employee) {\n\t\tif (employee == null)\n\t\t\tthrow new IllegalArgumentException(\"Funcionário não pode ser nulo!\");\n\t\t\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Employee u WHERE u.login = :login AND u.password = :password\", Employee.class);\n\t\tquery.setParameter(\"login\", employee.getLogin());\n\t\tquery.setParameter(\"password\", employee.getPassword());\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Employee> users = query.getResultList();\n\n\t\treturn users.isEmpty() ? null : users.get(0);\n\t}\n\t\n\t/**\n\t * Obtém um funcionário com base no login.\n\t * @param login O login do funcionário a ser buscado.\n\t * @return O funcionário encontrado ou null se não encontrado.\n\t * @throws IllegalArgumentException Se o login fornecido for nulo.\n\t */\n\tpublic Employee getByLogin(String login) {\n\t\tif (login == null)\n\t\t\tthrow new IllegalArgumentException(\"Login não pode ser nulo!\");\n\t\t\n\t\tQuery query = manager.createQuery(\"SELECT u FROM Employee u WHERE u.login = :login\", Employee.class);\n\t\tquery.setParameter(\"login\", login);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tList<Employee> users = query.getResultList();\n\n\t\treturn users.isEmpty() ? null : users.get(0);\n\t}\n\t\n\t\n\t/**\n * Fecha o EntityManager quando este objeto ClientDAO é fechado.\n *\n * @throws IOException Se ocorrer um erro ao fechar o EntityManager.\n */\n\t@Override\n\tpublic void close() throws IOException {\n\t\tmanager.close();\n\t}\n}"
},
{
"identifier": "EmployeeType",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/enumeration/EmployeeType.java",
"snippet": "public enum EmployeeType {\n\tADMIN(\"Administrador\"),\n\tCHEF(\"Cozinheiro\");\n\t\n\tprivate String description;\n\t\n\tprivate EmployeeType(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\t\n\t/**\n\t * Obtém um objeto do tipo EmployeeType com base na descrição especificada.\n\t *\n\t * @param description A descrição do tipo a ser buscado.\n\t * @return O EmployeeType correspondente à descrição fornecida ou null se não encontrado.\n\t */\n\tpublic static EmployeeType getByDescription(String description) {\n\t\tfor(EmployeeType employeeType : EmployeeType.values())\n\t\t\tif(employeeType.description.equalsIgnoreCase(description))\n\t\t\t\treturn employeeType;\n\t\treturn null;\n\t}\n}"
},
{
"identifier": "Employee",
"path": "PizzeriaExpress/src/main/java/br/vjps/tsi/pe/model/Employee.java",
"snippet": "@Entity\npublic class Employee {\n\t\n\t@Id\n\t@SequenceGenerator(name = \"employee_id\", sequenceName = \"employee_seq\", allocationSize = 1)\n\t@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"employee_id\")\n\tprivate Long id;\n\t\n\tprivate String name;\n\t\n\tprivate String login;\n\t\n\tprivate String password;\n\t\n\t@Enumerated(EnumType.STRING)\n\tprivate EmployeeType type;\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getLogin() {\n\t\treturn login;\n\t}\n\n\tpublic void setLogin(String login) {\n\t\tthis.login = login;\n\t}\n\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic EmployeeType getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(EmployeeType type) {\n\t\tthis.type = type;\n\t}\n\t\n}"
}
] | import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import br.vjps.tsi.pe.dao.EmployeeDAO;
import br.vjps.tsi.pe.enumeration.EmployeeType;
import br.vjps.tsi.pe.model.Employee; | 1,297 | package br.vjps.tsi.pe.managedbeans;
@SessionScoped
@ManagedBean
public class EmployeeMB {
private Employee employee = new Employee();
/**
* Método para realizar o login do funcionário.
*
* @return A string de navegação para a próxima página.
*/
public String login() {
| package br.vjps.tsi.pe.managedbeans;
@SessionScoped
@ManagedBean
public class EmployeeMB {
private Employee employee = new Employee();
/**
* Método para realizar o login do funcionário.
*
* @return A string de navegação para a próxima página.
*/
public String login() {
| try(EmployeeDAO dao = new EmployeeDAO()) { | 0 | 2023-12-16 01:25:27+00:00 | 2k |
devOS-Sanity-Edition/terra-fishing | src/main/java/one/devos/nautical/terra_fishing/TerraFishing.java | [
{
"identifier": "Registrar",
"path": "src/main/java/one/devos/nautical/terra_fishing/util/Registrar.java",
"snippet": "public class Registrar {\n // Items\n public static final Item SEXTANT = registerItem(\"sextant\", new SextantItem(new FabricItemSettings().stacksTo(1)));\n public static final Item RADIO = registerItem(\"radio\", new RadioItem(new FabricItemSettings().stacksTo(1)));\n public static final Item POCKET_GUIDE = registerItem(\"pocket_guide\", new PocketGuideItem(new FabricItemSettings().stacksTo(1)));\n public static final Item FISH_FINDER = registerItem(\"fish_finder\", new FishFinderItem(new FabricItemSettings().stacksTo(1).rarity(Rarity.UNCOMMON)));\n public static final Item EARRING = registerItem(\"earring\", new EarringTrinketItem(new FabricItemSettings().stacksTo(1)));\n public static final Item TACKLE_BOX = registerItem(\"tackle_box\", new TackleBoxTrinketItem(new FabricItemSettings().stacksTo(1)));\n public static final Item HOOK = registerItem(\"hook\", new FishingHookTrinketItem(new FabricItemSettings().maxCount(1).fireproof()));\n public static final Item BOBBER = registerItem(\"bobber\", new FishingBobberTrinketItem(new FabricItemSettings().stacksTo(1)));\n public static final Item GLOW_BOBBER = registerItem(\"glow_bobber\", new GlowingFishingBobberTrinketItem(new FabricItemSettings().stacksTo(1).rarity(Rarity.UNCOMMON)));\n\n public static final Item ANGLER_HAT = registerItem(\"angler_hat\", new AnglerArmorItem(AnglerArmorMaterial.ANGLER, ArmorItem.Type.HELMET, new FabricItemSettings().maxCount(1)));\n public static final Item ANGLER_VEST = registerItem(\"angler_vest\", new AnglerArmorItem(AnglerArmorMaterial.ANGLER, ArmorItem.Type.CHESTPLATE, new FabricItemSettings().maxCount(1)));\n public static final Item ANGLER_PANTS = registerItem(\"angler_pants\", new AnglerArmorItem(AnglerArmorMaterial.ANGLER, ArmorItem.Type.LEGGINGS, new FabricItemSettings().maxCount(1)));\n public static final Item ANGLER_WADERS = registerItem(\"angler_waders\", new AnglerArmorItem(AnglerArmorMaterial.ANGLER, ArmorItem.Type.BOOTS, new FabricItemSettings().maxCount(1)));\n\n// public static final Item IRON_FISHING_ROD;\n// public static final Item GOLDEN_FISHING_ROD;\n// public static final Item NETHERITE_FISHING_ROD;\n//\n// public static final Item GRASSHOPPERS;\n// public static final Item WORM;\n// public static final Item GOLDEN_WORM;\n// public static final Item TRUFFLE_WORM;\n// public static final Item JELLYFISH;\n// public static final Item APPRENTICE;\n// public static final Item JOURNEYMAN;\n// public static final Item MASTER;\n//\n// public static final Item BOTTOMLESS_BUCKET;\n// public static final Block EMPTY_BOTTOMLESS_BUCKET;\n \n// // Blocks\n// public static final Block WOODEN_CRATE;\n// public static final Block IRON_CRATE;\n// public static final Block GOLDEN_CRATE;\n\n public static Item registerItem(String name, Item item) {\n ItemGroupEvents.modifyEntriesEvent(ITEM_GROUP).register(content -> content.accept(item));\n return Registry.register(BuiltInRegistries.ITEM, new ResourceLocation(MODID, name), item);\n }\n\n public static void init() {}\n\n}"
},
{
"identifier": "SEXTANT",
"path": "src/main/java/one/devos/nautical/terra_fishing/util/Registrar.java",
"snippet": "public static final Item SEXTANT = registerItem(\"sextant\", new SextantItem(new FabricItemSettings().stacksTo(1)));"
}
] | import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.core.registries.Registries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.ItemStack;
import one.devos.nautical.terra_fishing.util.Registrar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static one.devos.nautical.terra_fishing.util.Registrar.SEXTANT; | 1,166 | package one.devos.nautical.terra_fishing;
public class TerraFishing implements ModInitializer {
public static String MODID = "terra_fishing";
public static final Logger LOGGER = LoggerFactory.getLogger("Terra Fishing");
public static final ResourceKey<CreativeModeTab> ITEM_GROUP = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MODID, "discovery.tab"));
public static final CreativeModeTab TERRA_FISHING_GROUP = FabricItemGroup.builder() | package one.devos.nautical.terra_fishing;
public class TerraFishing implements ModInitializer {
public static String MODID = "terra_fishing";
public static final Logger LOGGER = LoggerFactory.getLogger("Terra Fishing");
public static final ResourceKey<CreativeModeTab> ITEM_GROUP = ResourceKey.create(Registries.CREATIVE_MODE_TAB, new ResourceLocation(MODID, "discovery.tab"));
public static final CreativeModeTab TERRA_FISHING_GROUP = FabricItemGroup.builder() | .icon(() -> new ItemStack(SEXTANT)) | 1 | 2023-12-18 22:55:14+00:00 | 2k |
NeckitWin/ArcaneMystic | src/main/java/net/arcanemagic/common/handler/ModItems.java | [
{
"identifier": "Book",
"path": "src/main/java/net/arcanemagic/common/item/Book.java",
"snippet": "public class Book extends Item{\n public Book () {\n setUnlocalizedName(\"book\");\n setTextureName(ArcaneMystic.MOD_ID + \":book\");\n setMaxStackSize(1);\n }\n}"
},
{
"identifier": "UltraPickaxe",
"path": "src/main/java/net/arcanemagic/common/item/tool/UltraPickaxe.java",
"snippet": "public class UltraPickaxe extends ItemTool {\n public UltraPickaxe() {\n super(2F, ModItems.ULTRA_MATERIAL, null);\n setUnlocalizedName(\"admin_pickaxe\");\n setTextureName(ArcaneMystic.MOD_ID + \":admin_pickaxe\");\n setCreativeTab(ModTab.INSTANCE);\n setHarvestLevel(\"pickaxe\", ModItems.ULTRA_MATERIAL.getHarvestLevel());\n }\n // кирка ломает быстро все блоки, что только можно\n @Override\n public float func_150893_a(ItemStack itemStack, Block block) {\n return 999;\n }\n // при правой кнопки мыши получает зелье прыжок 2 уровня на 1 минуту\n @Override\n public ItemStack onItemRightClick(ItemStack itemStack, net.minecraft.world.World world, net.minecraft.entity.player.EntityPlayer player) {\n player.addPotionEffect(new net.minecraft.potion.PotionEffect(8, 3600, 1));\n // и скорость\n player.addPotionEffect(new net.minecraft.potion.PotionEffect(1, 3600, 1));\n return itemStack;\n }\n}"
},
{
"identifier": "NecromancerStaff",
"path": "src/main/java/net/arcanemagic/common/item/tool/NecromancerStaff.java",
"snippet": "public class NecromancerStaff extends ItemSword {\n public NecromancerStaff() {\n super(ModItems.ULTRA_MATERIAL);\n setUnlocalizedName(\"Necromancers_Staff\");\n setTextureName(ArcaneMystic.MOD_ID + \":nekrostaff\");\n setCreativeTab(ModTab.INSTANCE);\n }\n\n @Override\n public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) {\n if (!world.isRemote) {\n EntitySkeleton skeleton = new EntitySkeleton(world);\n skeleton.setPosition(player.posX + 1, player.posY, player.posZ);\n skeleton.setCurrentItemOrArmor(0, new ItemStack(Items.diamond_axe));\n world.spawnEntityInWorld(skeleton);\n EntitySkeleton skeleton1 = new EntitySkeleton(world);\n skeleton1.setPosition(player.posX - 1, player.posY, player.posZ);\n skeleton1.setCurrentItemOrArmor(0, new ItemStack(Items.diamond_axe));\n world.spawnEntityInWorld(skeleton1);\n EntitySkeleton skeleton2 = new EntitySkeleton(world);\n skeleton2.setPosition(player.posX, player.posY, player.posZ + 1);\n skeleton2.setCurrentItemOrArmor(0, new ItemStack(Items.diamond_sword));\n world.spawnEntityInWorld(skeleton2);\n }\n return itemStack;\n }\n\n @Override\n public boolean hitEntity(ItemStack itemStack, EntityLivingBase entityLivingBase, EntityLivingBase entityLivingBase1) {\n if (!entityLivingBase.worldObj.isRemote) {\n EntityLightningBolt lightningBolt = new EntityLightningBolt(entityLivingBase.worldObj, entityLivingBase.posX, entityLivingBase.posY, entityLivingBase.posZ);\n for (int i = 0; i < 10; i++) {\n entityLivingBase.worldObj.addWeatherEffect(lightningBolt);\n }\n }\n return true;\n }\n}"
},
{
"identifier": "GoldenBread",
"path": "src/main/java/net/arcanemagic/common/item/GoldenBread.java",
"snippet": "public class GoldenBread extends ItemFood{\n public GoldenBread(){\n super(20, 5F, false);\n setPotionEffect(Potion.regeneration.id, 9999999, 5, 1F);\n setUnlocalizedName(\"GoldenBread\");\n setTextureName(ArcaneMystic.MOD_ID +\":goldenbread\");\n setMaxStackSize(16);\n setCreativeTab(ModTab.INSTANCE);\n }\n}"
},
{
"identifier": "MegaArmor",
"path": "src/main/java/net/arcanemagic/common/item/armor/MegaArmor.java",
"snippet": "public class MegaArmor extends ItemArmor {\n public MegaArmor(String elementName, int armorType) {\n super(ModItems.ULTRA_ARMOR_MATERIAL, 0, armorType);\n setUnlocalizedName(\"ruby_\" + elementName);\n setTextureName(ArcaneMystic.MOD_ID + \":ruby_\" + elementName);\n setCreativeTab(ModTab.INSTANCE);\n }\n}"
}
] | import net.arcanemagic.common.item.Book;
import net.arcanemagic.common.item.tool.UltraPickaxe;
import net.arcanemagic.common.item.tool.NecromancerStaff;
import net.minecraft.item.Item;
import cpw.mods.fml.common.registry.GameRegistry;
import net.arcanemagic.common.item.GoldenBread;
import net.minecraft.item.ItemArmor;
import net.minecraftforge.common.util.EnumHelper;
import net.arcanemagic.common.item.armor.MegaArmor; | 1,351 | package net.arcanemagic.common.handler;
public class ModItems {
public static final Item.ToolMaterial ULTRA_MATERIAL = EnumHelper.addToolMaterial("arcanemagic:ultra_ingot", 99999, 10000, 99999F, 20F, 30);
public static final ItemArmor.ArmorMaterial ULTRA_ARMOR_MATERIAL = EnumHelper.addArmorMaterial("arcanemagic:ultra_ingot", 99999, new int[]{99999, 99999, 99999, 99999}, 30);
public static final GoldenBread GOLDEN_BREAD = new GoldenBread();
public static final UltraPickaxe ADMIN_PICKAXE = new UltraPickaxe();
public static final Book BOOK = new Book(); | package net.arcanemagic.common.handler;
public class ModItems {
public static final Item.ToolMaterial ULTRA_MATERIAL = EnumHelper.addToolMaterial("arcanemagic:ultra_ingot", 99999, 10000, 99999F, 20F, 30);
public static final ItemArmor.ArmorMaterial ULTRA_ARMOR_MATERIAL = EnumHelper.addArmorMaterial("arcanemagic:ultra_ingot", 99999, new int[]{99999, 99999, 99999, 99999}, 30);
public static final GoldenBread GOLDEN_BREAD = new GoldenBread();
public static final UltraPickaxe ADMIN_PICKAXE = new UltraPickaxe();
public static final Book BOOK = new Book(); | public static final NecromancerStaff NECROMANCER_STAFF = new NecromancerStaff(); | 2 | 2023-12-16 20:38:09+00:00 | 2k |
akhilk999/CustomSwords | src/main/java/org/akhilk999/customswords/CustomSwords.java | [
{
"identifier": "ModBlocks",
"path": "src/main/java/org/akhilk999/customswords/blocks/ModBlocks.java",
"snippet": "public class ModBlocks {\n public static final Block CRYSTALLITE_ORE = registerBlock(\"crystallite-ore\", new ExperienceDroppingBlock(AbstractBlock.Settings.create().instrument(Instrument.BASEDRUM).requiresTool().strength(3.0F, 3.0F), UniformIntProvider.create(3, 7)), Items.ANCIENT_DEBRIS,ItemGroups.NATURAL);\n public static final Block CRYSTALLITE_BLOCK = registerBlock(\"crystallite-block\", new Block(AbstractBlock.Settings.create().requiresTool().strength(5.0F, 6.0F).sounds(BlockSoundGroup.METAL)), Items.NETHERITE_BLOCK, ItemGroups.BUILDING_BLOCKS);\n //public static final Block CRYSTALLITE_BLOCK = registerBlock(\"crystallite-block\", new Block(FabricBlockSettings.create().strength(4f).requiresTool()), Items.NETHERITE_BLOCK, ItemGroups.BUILDING_BLOCKS);\n private static Block registerBlock(String name, Block block, Item prev, RegistryKey<ItemGroup> group){\n registerBlockItem(name, block, prev, group);\n return Registry.register(Registries.BLOCK, new Identifier(\"customswords\", name), block);\n }\n\n private static void registerBlockItem(String name, Block block, Item prev, RegistryKey<ItemGroup> group){\n Item item = Registry.register(Registries.ITEM, new Identifier(\"customswords\", name), new BlockItem(block, new Item.Settings()));\n ItemGroupEvents.modifyEntriesEvent(group).register(entries -> {entries.addAfter(prev,item);});\n }\n\n public static void registerModBlocks(){\n CustomSwords.LOGGER.info(\"Registering blocks for customswords\");\n\n }\n\n}"
},
{
"identifier": "ModItems",
"path": "src/main/java/org/akhilk999/customswords/items/ModItems.java",
"snippet": "public class ModItems {\n public static final Item CRYSTALLITE_INGOT = registerItem(\"crystallite-ingot\", new Item(new Item.Settings()));\n //////////\n //SWORDS//\n /////////\n public static final Item DARK_REPULSER = registerItem(\"dark-repulser\", new DarkRepulserSwordItem(CRYSTALLITE,4, -2.4f, new Item.Settings()));\n public static final Item ELUCIDATOR = registerItem(\"elucidator\", new ElucidatorSwordItem(CRYSTALLITE,4, -2.4f, new Item.Settings()));\n public static final Item LAMBENT_LIGHT = registerItem(\"lambent-light\", new LambentLightSwordItem(CRYSTALLITE,4, -2.4f, new Item.Settings()));\n public static final Item DIVINE_RADIANCE = registerItem(\"divine-radiance\", new DivineRadianceSwordItem(CRYSTALLITE,4, -2.4f, new Item.Settings()));\n\n /* Registers given item with name\n @param name the name of the item\n @param item the actual item\n @return the item after being registered\n */\n private static Item registerItem(String name, Item item){\n return Registry.register(Registries.ITEM, new Identifier(\"customswords\", name), item);\n }\n\n /* Adds all items to their respective ItemGroup\n */\n public static void addToGroup(){\n ItemGroupEvents.modifyEntriesEvent(ItemGroups.COMBAT).register(entries -> {\n entries.addAfter(Items.NETHERITE_SWORD,DARK_REPULSER);\n entries.addAfter(DARK_REPULSER,ELUCIDATOR);\n entries.addAfter(ELUCIDATOR,LAMBENT_LIGHT);\n entries.addAfter(LAMBENT_LIGHT,DIVINE_RADIANCE);\n });\n ItemGroupEvents.modifyEntriesEvent(ItemGroups.INGREDIENTS).register(entries -> {\n entries.addAfter(Items.DIAMOND,CRYSTALLITE_INGOT);\n });\n }\n /* Registers all items\n */\n public static void registerModItems(){\n CustomSwords.LOGGER.info(\"Registering items for customswords\");\n addToGroup();\n }\n\n\n}"
}
] | import net.fabricmc.api.ModInitializer;
import org.akhilk999.customswords.blocks.ModBlocks;
import org.akhilk999.customswords.items.ModItems;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static net.minecraft.item.Items.register; | 1,071 | package org.akhilk999.customswords;
public class CustomSwords implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("customswords");
@Override
public void onInitialize() {
LOGGER.info("CustomSwords has started up.");
ModItems.registerModItems(); | package org.akhilk999.customswords;
public class CustomSwords implements ModInitializer {
public static final Logger LOGGER = LoggerFactory.getLogger("customswords");
@Override
public void onInitialize() {
LOGGER.info("CustomSwords has started up.");
ModItems.registerModItems(); | ModBlocks.registerModBlocks(); | 0 | 2023-12-16 23:43:46+00:00 | 2k |
my-virtual-hub/omni-comm-domain | src/test/java/br/com/myvirtualhub/omni/domain/sms/model/SmsPayloadTest.java | [
{
"identifier": "PhoneNumber",
"path": "src/main/java/br/com/myvirtualhub/omni/domain/core/commons/PhoneNumber.java",
"snippet": "public class PhoneNumber implements Serializable, Copyable<PhoneNumber> {\n\n /**\n * Represents the content of a variable.\n *\n * <p>This class stores the content of a variable as a string.\n */\n private String content;\n\n /**\n * Constructs a new PhoneNumber object. The phone number must be in the format\n * of \"+\" followed by digits, including the country code, with no formatting.\n *\n * @param content the phone number string as entered by the user\n * @throws PhoneNumberException if the phone number is invalid\n */\n public PhoneNumber(String content) throws PhoneNumberException{\n PhoneNumberIsValidValidatorHandler validator = new PhoneNumberIsValidValidatorHandler.Builder().build();\n validator.validate(content);\n setContent(content);\n }\n\n /**\n * Retrieves the content of the PhoneNumber object.\n *\n * @return the content of the PhoneNumber object as a String\n */\n public String getContent() {\n return content;\n }\n\n /**\n * Sets the content of the PhoneNumber object.\n *\n * @param content the new content for the PhoneNumber object\n */\n public void setContent(String content) {\n this.content = content;\n }\n\n @Override\n public PhoneNumber copy() throws PhoneNumberException {\n return new PhoneNumber(getContent());\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof PhoneNumber phoneNumber)) return false;\n return getContent().equals(phoneNumber.getContent());\n }\n\n @Override\n public int hashCode() {\n return Objects.hashCode(getContent());\n }\n\n @Override\n public String toString() {\n return \"PhoneNumber{\" +\n \"content='\" + content + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "PhoneNumberException",
"path": "src/main/java/br/com/myvirtualhub/omni/domain/core/exceptions/PhoneNumberException.java",
"snippet": "public class PhoneNumberException extends OmniException{\n /**\n * Constructs a new PhoneNumberException with the specified message.\n *\n * @param message the detail message for the exception\n */\n public PhoneNumberException(String message) {\n super(message);\n }\n\n /**\n * Constructs a new PhoneNumberException with the specified message and cause.\n *\n * @param message the detail message for the exception\n * @param cause the cause of the exception\n * @throws NullPointerException if the message is null\n */\n public PhoneNumberException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * Exception used to indicate issues with phone number operations.\n *\n * <p>This is a specific type of {@link OmniException}. It should be used\n * for exceptional conditions related to phone number processing such as\n * validation, formatting, parsing, or other phone number related errors.\n *\n * @param message the detail message for the exception\n * @param throwableCause the cause of the exception as a string\n */\n public PhoneNumberException( String message , String throwableCause) {\n super(message, throwableCause);\n }\n}"
}
] | import br.com.myvirtualhub.omni.domain.core.commons.PhoneNumber;
import br.com.myvirtualhub.omni.domain.core.exceptions.PhoneNumberException;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*; | 902 | /*
* Copyright (c) 2024.
*
* This software is provided under the BSD-2-Clause license. By using this software,
* * you agree to respect the terms and conditions of the BSD-2-Clause license.
*/
package br.com.myvirtualhub.omni.domain.sms.model;
class SmsPayloadTest {
@Test | /*
* Copyright (c) 2024.
*
* This software is provided under the BSD-2-Clause license. By using this software,
* * you agree to respect the terms and conditions of the BSD-2-Clause license.
*/
package br.com.myvirtualhub.omni.domain.sms.model;
class SmsPayloadTest {
@Test | void testSmsPayloadCreationAndGetters() throws PhoneNumberException { | 1 | 2023-12-18 03:42:25+00:00 | 2k |
ThomasGorisseGit/TodoList | backend/src/main/java/fr/gorisse/todoApp/TodoListApp/services/TaskService.java | [
{
"identifier": "Task",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/entity/Task.java",
"snippet": "@Data\n@Getter\n@Setter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\n\npublic class Task {\n\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"id_task\")\n private Integer idTask;\n\n private String title;\n private String description;\n\n\n @ManyToOne\n @JsonBackReference\n private TodoList referenceTodoList;\n\n //pas utilisé mais utile pour la JSON\n public int getIdTodoList() {\n return this.referenceTodoList.getIdTodoList();\n }\n\n\n\n}"
},
{
"identifier": "TodoList",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/entity/TodoList.java",
"snippet": "@Data\n@ToString\n@Getter\n@Setter\n@AllArgsConstructor\n@NoArgsConstructor\n@Entity\npublic class TodoList {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Integer idTodoList;\n\n private String title;\n private String description;\n\n\n @Convert(converter = TypeConverter.class)\n private V_Type type; //publique privé ou partagé\n\n @Convert(converter = VisibilityConverter.class)\n private V_Visibility taskVisibility; //commun ou solo\n\n @JsonIgnore\n @ManyToOne\n @JsonManagedReference\n private User author;\n\n\n\n @OneToMany(mappedBy = \"referenceTodoList\", cascade = CascadeType.ALL)\n @JsonManagedReference\n private List<Task> tasks;\n\n\n\n}"
},
{
"identifier": "TaskIntrouvableException",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/exception/TaskIntrouvableException.java",
"snippet": "@ResponseStatus(value = HttpStatus.CONFLICT)\npublic class TaskIntrouvableException extends RuntimeException {\n public TaskIntrouvableException(Integer id) {\n super(\"Pas de tâche avec l'id : \" + id);\n }\n}"
},
{
"identifier": "TaskRepository",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/repository/TaskRepository.java",
"snippet": "@Repository\npublic interface TaskRepository extends CrudRepository<Task, Integer> {\n\n Optional<Task> findTaskByIdTask(Integer id);\n\n}"
},
{
"identifier": "IDeletion",
"path": "backend/src/main/java/fr/gorisse/todoApp/TodoListApp/services/interfaces/IDeletion.java",
"snippet": "public interface IDeletion {\n void delete(int idCurrentEntity);\n void deleteAll(int idParentEntity);\n}"
}
] | import fr.gorisse.todoApp.TodoListApp.entity.Task;
import fr.gorisse.todoApp.TodoListApp.entity.TodoList;
import fr.gorisse.todoApp.TodoListApp.exception.TaskIntrouvableException;
import fr.gorisse.todoApp.TodoListApp.repository.TaskRepository;
import fr.gorisse.todoApp.TodoListApp.services.interfaces.IDeletion;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional; | 798 | package fr.gorisse.todoApp.TodoListApp.services;
@Service
public class TaskService implements IDeletion {
TaskRepository taskRepository;
TodoListService todoListService;
public TaskService(TaskRepository taskRepository,TodoListService todoListService) {
this.taskRepository = taskRepository;
this.todoListService = todoListService;
}
| package fr.gorisse.todoApp.TodoListApp.services;
@Service
public class TaskService implements IDeletion {
TaskRepository taskRepository;
TodoListService todoListService;
public TaskService(TaskRepository taskRepository,TodoListService todoListService) {
this.taskRepository = taskRepository;
this.todoListService = todoListService;
}
| public Task findTaskById(Integer id) { | 0 | 2023-12-15 17:32:43+00:00 | 2k |
Konloch/HeadlessIRC | src/main/java/com/konloch/ircbot/message/text/TextMessage.java | [
{
"identifier": "IntegerMessage",
"path": "src/main/java/com/konloch/ircbot/message/integer/IntegerMessage.java",
"snippet": "public enum IntegerMessage\n{\n\tRPL_NAMREPLY(353, new RPLNameply()),\n\t;\n\t\n\tprivate static final HashMap<Integer, IntegerMessage> LOOKUP = new HashMap<>();\n\t\n\tstatic\n\t{\n\t\tfor(IntegerMessage msg : values())\n\t\t\tLOOKUP.put(msg.opcode, msg);\n\t}\n\t\n\tprivate final int opcode;\n\tprivate final IntegerMessageEvent event;\n\t\n\tIntegerMessage(int opcode, IntegerMessageEvent event)\n\t{\n\t\tthis.opcode = opcode;\n\t\tthis.event = event;\n\t}\n\t\n\tpublic int getOpcode()\n\t{\n\t\treturn opcode;\n\t}\n\t\n\tpublic IntegerMessageEvent getEvent()\n\t{\n\t\treturn event;\n\t}\n\t\n\tpublic static IntegerMessage opcode(int opcode)\n\t{\n\t\treturn LOOKUP.get(opcode);\n\t}\n}"
},
{
"identifier": "Join",
"path": "src/main/java/com/konloch/ircbot/message/text/impl/Join.java",
"snippet": "public class Join implements TextMessageEvent\n{\n\t@Override\n\tpublic void handle(Server server, String[] splitPartMessage)\n\t{\n\t\tString nickname = split(splitPartMessage[0].substring(1), \"!\", 2)[0];\n\t\tString channelName = splitPartMessage[2];\n\t\t\n\t\tChannel channel = server.getChannel(channelName);\n\t\t\n\t\tif (channel != null)\n\t\t{\n\t\t\tchannel.setJoined(true);\n\t\t\t\n\t\t\t//add user to channel\n\t\t\tUser user = channel.add(nickname);\n\t\t\t\n\t\t\t//call on listener event\n\t\t\tserver.getBot().getListeners().callOnJoin(channel, user);\n\t\t}\n\t}\n}"
},
{
"identifier": "PrivMSG",
"path": "src/main/java/com/konloch/ircbot/message/text/impl/PrivMSG.java",
"snippet": "public class PrivMSG implements TextMessageEvent\n{\n\t@Override\n\tpublic void handle(Server server, String[] splitPartMessage)\n\t{\n\t\tString nickname = split(splitPartMessage[0].substring(1), \"!\", 2)[0];\n\t\tString[] locations = split(splitPartMessage[2], \",\");\n\t\tString msg = splitPartMessage[3].substring(1);\n\t\t\n\t\tfor(String location : locations)\n\t\t{\n\t\t\tif (location.startsWith(\"#\"))\n\t\t\t{\n\t\t\t\tChannel channel = server.getChannel(location);\n\t\t\t\t\n\t\t\t\tif (channel != null)\n\t\t\t\t{\n\t\t\t\t\tchannel.setJoined(true);\n\t\t\t\t\t\n\t\t\t\t\tUser user = channel.get(nickname);\n\t\t\t\t\t\n\t\t\t\t\tif (user == null)\n\t\t\t\t\t\tuser = server.getUser(nickname);\n\t\t\t\t\t\n\t\t\t\t\t//call on listener event\n\t\t\t\t\tserver.getBot().getListeners().callChannelMessage(channel, user, msg);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t//load the user object\n\t\t\t\tUser user = server.getUser(nickname);\n\t\t\t\t\n\t\t\t\t//call on listener event\n\t\t\t\tserver.getBot().getListeners().callPrivateMessage(user, msg);\n\t\t\t}\n\t\t}\n\t}\n}"
},
{
"identifier": "Quit",
"path": "src/main/java/com/konloch/ircbot/message/text/impl/Quit.java",
"snippet": "public class Quit implements TextMessageEvent\n{\n\t@Override\n\tpublic void handle(Server server, String[] splitPartMessage)\n\t{\n\t\tString nickname = split(splitPartMessage[0].substring(1), \"!\", 2)[0];\n\t\t\n\t\tfor(Channel channel : server.getChannels())\n\t\t{\n\t\t\t//remove user from channel\n\t\t\tUser user = channel.remove(nickname);\n\t\t\t\n\t\t\tif(user != null)\n\t\t\t{\n\t\t\t\t//call on listener event\n\t\t\t\tserver.getBot().getListeners().callOnLeave(channel, user);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n}"
}
] | import com.konloch.ircbot.message.integer.IntegerMessage;
import com.konloch.ircbot.message.text.impl.Join;
import com.konloch.ircbot.message.text.impl.PrivMSG;
import com.konloch.ircbot.message.text.impl.Quit;
import java.util.HashMap; | 1,043 | package com.konloch.ircbot.message.text;
/**
* @author Konloch
* @since 12/15/2023
*/
public enum TextMessage
{
PRIVMSG("privmsg", new PrivMSG()),
JOIN("join", new Join()), | package com.konloch.ircbot.message.text;
/**
* @author Konloch
* @since 12/15/2023
*/
public enum TextMessage
{
PRIVMSG("privmsg", new PrivMSG()),
JOIN("join", new Join()), | QUIT("quit", new Quit()), | 3 | 2023-12-16 02:09:21+00:00 | 2k |
moiseslx/store-springboot3-jpa | src/main/java/com/moises/store/entities/pk/OrderItemPK.java | [
{
"identifier": "Order",
"path": "src/main/java/com/moises/store/entities/Order.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Data\n@Entity\n@Table(name = \"tb_order\")\npublic class Order implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss'Z'\", timezone = \"GMT\")\n private Instant moment;\n\n private Integer orderStatus;\n\n @ManyToOne\n @JoinColumn(name = \"client_id\")\n private User client;\n\n @OneToMany(mappedBy = \"id.order\")\n private List<OrderItem> items = new ArrayList<>();\n\n @OneToOne(mappedBy = \"order\", cascade = CascadeType.ALL)\n private Payment payment;\n\n //CUSTOM CONSTRUCTOR\n public Order(Long id, Instant moment, User client, OrderStatus status) {\n this.id = id;\n this.moment = moment;\n this.client = client;\n setOrderStatus(status);\n }\n\n //CUSTOM GETTER AND SETTER METHOD\n public OrderStatus getOrderStatus() {\n return OrderStatus.valueOf(orderStatus);\n }\n\n public void setOrderStatus(OrderStatus orderStatus) {\n if (orderStatus != null) {\n this.orderStatus = orderStatus.getCode();\n }\n }\n\n public Double getTotal() {\n double sum = 0.0;\n for (OrderItem x : items) {\n sum += x.getSubTotal();\n }\n return sum;\n }\n}"
},
{
"identifier": "Product",
"path": "src/main/java/com/moises/store/entities/Product.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Entity\n@Table(name = \"tb_product\")\npublic class Product implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Getter @Setter\n private Long id;\n @Getter @Setter\n private String name;\n @Getter @Setter\n private String description;\n @Getter @Setter\n private Double price;\n @Getter @Setter\n private String imageUrl;\n\n @Getter\n @ManyToMany\n @JoinTable(name = \"tb_product_category\", joinColumns = @JoinColumn(name = \"product_id\"), inverseJoinColumns = @JoinColumn(name = \"category_id\"))\n private List<Category> categories = new ArrayList<>();\n\n @OneToMany(mappedBy = \"id.product\")\n private List<OrderItem> items = new ArrayList<>();\n\n // CUSTOM CONSTRUCTOR\n public Product(Long id, String name, String description, Double price, String imageUrl) {\n this.id = id;\n this.name = name;\n this.description = description;\n this.price = price;\n this.imageUrl = imageUrl;\n }\n\n // Adds a category to the list of categories if it is not already present.\n public void addCategory(Category category) {\n if (!this.categories.contains(category)) {\n this.categories.add(category);\n }\n }\n\n // Adds an item to the list of items if it is not already present.\n @JsonIgnore\n public List<Order> getOrders() {\n List<Order> list = new ArrayList<>();\n for (OrderItem x : items) {\n if (!list.contains(x.getOrder())) {\n list.add(x.getOrder());\n }\n }\n return list;\n }\n}"
}
] | import com.moises.store.entities.Order;
import com.moises.store.entities.Product;
import jakarta.persistence.Embeddable;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.io.Serial;
import java.io.Serializable; | 956 | package com.moises.store.entities.pk;
@Data
@EqualsAndHashCode
@Embeddable
public class OrderItemPK implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name = "order_id") | package com.moises.store.entities.pk;
@Data
@EqualsAndHashCode
@Embeddable
public class OrderItemPK implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name = "order_id") | private Order order; | 0 | 2023-12-16 03:44:28+00:00 | 2k |
sasmithx/layered-architecture-Sasmithx | src/main/java/lk/sasax/layeredarchitecture/dao/custom/impl/OrderDAOImpl.java | [
{
"identifier": "SQLUtil",
"path": "src/main/java/lk/sasax/layeredarchitecture/dao/SQLUtil.java",
"snippet": "public class SQLUtil {\n\n public static <T> T execute(String sql, Object... arg) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(sql);\n\n for (int i = 0; i < arg.length; i++) {\n pstm.setObject((i+1), arg[i]);\n }\n\n if (sql.startsWith(\"SELECT\") || sql.startsWith(\"select\")) {\n return (T)pstm.executeQuery();\n }\n else {\n return (T)(Boolean)(pstm.executeUpdate()>0);\n }\n }\n}"
},
{
"identifier": "OrderDAO",
"path": "src/main/java/lk/sasax/layeredarchitecture/dao/custom/OrderDAO.java",
"snippet": "public interface OrderDAO extends CrudDAO<Order> {\n\n ResultSet generateNewId() throws SQLException, ClassNotFoundException;\n\n boolean save(Order entity) throws SQLException, ClassNotFoundException;\n\n void selectOrderId(String orderId) throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "Order",
"path": "src/main/java/lk/sasax/layeredarchitecture/entity/Order.java",
"snippet": "public class Order {\n\n private String orderId;\n private LocalDate orderDate;\n private String customerId;\n private String customerName;\n private BigDecimal orderTotal;\n\n public Order() {\n }\n\n public Order(String orderId, LocalDate orderDate, String customerId, String customerName, BigDecimal orderTotal) {\n this.orderId = orderId;\n this.orderDate = orderDate;\n this.customerId = customerId;\n this.customerName = customerName;\n this.orderTotal = orderTotal;\n }\n\n public String getOrderId() {\n return orderId;\n }\n\n public void setOrderId(String orderId) {\n this.orderId = orderId;\n }\n\n public LocalDate getOrderDate() {\n return orderDate;\n }\n\n public void setOrderDate(LocalDate orderDate) {\n this.orderDate = orderDate;\n }\n\n public String getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(String customerId) {\n this.customerId = customerId;\n }\n\n public String getCustomerName() {\n return customerName;\n }\n\n public void setCustomerName(String customerName) {\n this.customerName = customerName;\n }\n\n public BigDecimal getOrderTotal() {\n return orderTotal;\n }\n\n public void setOrderTotal(BigDecimal orderTotal) {\n this.orderTotal = orderTotal;\n }\n}"
},
{
"identifier": "TransactionConnection",
"path": "src/main/java/lk/sasax/layeredarchitecture/util/TransactionConnection.java",
"snippet": "public class TransactionConnection {\n\n private static final Connection connection;\n\n static {\n try {\n connection = DBConnection.getDbConnection().getConnection();\n } catch (SQLException | ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void rollBack() throws SQLException {\n connection.rollback();\n }\n\n public static Connection getConnection() {\n return connection;\n }\n}"
}
] | import lk.sasax.layeredarchitecture.dao.SQLUtil;
import lk.sasax.layeredarchitecture.dao.custom.OrderDAO;
import lk.sasax.layeredarchitecture.entity.Order;
import lk.sasax.layeredarchitecture.util.TransactionConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; | 1,174 | package lk.sasax.layeredarchitecture.dao.custom.impl;
public class OrderDAOImpl implements OrderDAO {
@Override
public ResultSet generateNewId() throws SQLException, ClassNotFoundException {
/*Connection connection = DBConnection.getDbConnection().getConnection();
Statement stm = connection.createStatement();
return stm.executeQuery("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;");*/
return SQLUtil.execute("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;");
}
@Override
public Order search(String newValue) throws SQLException, ClassNotFoundException {
return null;
}
@Override
public void selectOrderId(String orderId) throws SQLException, ClassNotFoundException {
/*Connection connection = TransactionConnection.setConnection();
PreparedStatement stm = connection.prepareStatement("SELECT oid FROM `Orders` WHERE oid=?");
stm.setString(1, orderId);
*//*if order id already exist*//*
if (stm.executeQuery().next()) {
}*/
ResultSet resultSet = SQLUtil.execute("SELECT oid FROM `Orders` WHERE oid=?", orderId);
resultSet.next();
}
@Override
public boolean save(Order entity) throws SQLException, ClassNotFoundException {
/*Connection connection = TransactionConnection.setAutoCommitFalse();
PreparedStatement stm = connection.prepareStatement("INSERT INTO `Orders` (oid, date, customerID) VALUES (?,?,?)");
stm.setString(1, orderId);
stm.setDate(2, Date.valueOf(orderDate));
stm.setString(3, customerId);*/
boolean isExecuted = SQLUtil.execute("INSERT INTO `Orders` (oid, date, customerID) VALUES (?,?,?)",
entity.getOrderId(),
entity.getOrderDate(),
entity.getCustomerId()
);
if (!isExecuted) { | package lk.sasax.layeredarchitecture.dao.custom.impl;
public class OrderDAOImpl implements OrderDAO {
@Override
public ResultSet generateNewId() throws SQLException, ClassNotFoundException {
/*Connection connection = DBConnection.getDbConnection().getConnection();
Statement stm = connection.createStatement();
return stm.executeQuery("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;");*/
return SQLUtil.execute("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;");
}
@Override
public Order search(String newValue) throws SQLException, ClassNotFoundException {
return null;
}
@Override
public void selectOrderId(String orderId) throws SQLException, ClassNotFoundException {
/*Connection connection = TransactionConnection.setConnection();
PreparedStatement stm = connection.prepareStatement("SELECT oid FROM `Orders` WHERE oid=?");
stm.setString(1, orderId);
*//*if order id already exist*//*
if (stm.executeQuery().next()) {
}*/
ResultSet resultSet = SQLUtil.execute("SELECT oid FROM `Orders` WHERE oid=?", orderId);
resultSet.next();
}
@Override
public boolean save(Order entity) throws SQLException, ClassNotFoundException {
/*Connection connection = TransactionConnection.setAutoCommitFalse();
PreparedStatement stm = connection.prepareStatement("INSERT INTO `Orders` (oid, date, customerID) VALUES (?,?,?)");
stm.setString(1, orderId);
stm.setDate(2, Date.valueOf(orderDate));
stm.setString(3, customerId);*/
boolean isExecuted = SQLUtil.execute("INSERT INTO `Orders` (oid, date, customerID) VALUES (?,?,?)",
entity.getOrderId(),
entity.getOrderDate(),
entity.getCustomerId()
);
if (!isExecuted) { | TransactionConnection.rollBack(); | 3 | 2023-12-16 04:19:42+00:00 | 2k |
madhushiillesinghe/layered-architecture-madhushi | src/main/java/com/example/layeredarchitecture/dao/custom/impl/QueryDaoImpl.java | [
{
"identifier": "QueryDao",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/QueryDao.java",
"snippet": "public interface QueryDao extends SuperDao {\n List<CustomerOrderDTO> customerOrderDetail() throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "DBConnection",
"path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java",
"snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLException {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/company\", \"root\", \"Ijse@1234\");\n }\n\n public static DBConnection getDbConnection() throws SQLException, ClassNotFoundException {\n return dbConnection == null ? dbConnection= new DBConnection() : dbConnection;\n }\n\n public Connection getConnection() {\n return connection;\n }\n}"
},
{
"identifier": "CustomerOrderDTO",
"path": "src/main/java/com/example/layeredarchitecture/dto/CustomerOrderDTO.java",
"snippet": "public class CustomerOrderDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n private String orderId;\n private LocalDate orderDate;\n\n\n public CustomerOrderDTO() {\n\n }\n\n public CustomerOrderDTO(String id, String name, String address,String orderId, LocalDate orderDate) {\n this.id = id;\n this.name = name;\n this.address = address;\n this.orderId = orderId;\n this.orderDate = orderDate;\n\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n public String getOrderId() {\n return orderId;\n }\n\n public void setOrderId(String orderId) {\n this.orderId = orderId;\n }\n\n public LocalDate getOrderDate() {\n return orderDate;\n }\n\n public void setOrderDate(LocalDate orderDate) {\n this.orderDate = orderDate;\n }\n\n\n\n @Override\n public String toString() {\n return \"CustomerOrderDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n \"orderId='\" + orderId + '\\'' +\n \", orderDate=\" + orderDate +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.dao.custom.QueryDao;
import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.dto.CustomerOrderDTO;
import java.sql.*;
import java.util.ArrayList;
import java.util.List; | 719 | package com.example.layeredarchitecture.dao.custom.impl;
public class QueryDaoImpl implements QueryDao {
@Override | package com.example.layeredarchitecture.dao.custom.impl;
public class QueryDaoImpl implements QueryDao {
@Override | public List<CustomerOrderDTO> customerOrderDetail() throws SQLException, ClassNotFoundException { | 2 | 2023-12-17 02:17:36+00:00 | 2k |
HypixelSkyblockmod/ChromaHud | src/java/xyz/apfelmus/cheeto/client/modules/world/BetterStonk.java | [
{
"identifier": "Category",
"path": "src/java/xyz/apfelmus/cf4m/module/Category.java",
"snippet": "public enum Category {\n COMBAT,\n RENDER,\n MOVEMENT,\n PLAYER,\n WORLD,\n MISC,\n NONE;\n\n}"
},
{
"identifier": "ClientTickEvent",
"path": "src/java/xyz/apfelmus/cheeto/client/events/ClientTickEvent.java",
"snippet": "public class ClientTickEvent\nextends Listener {\n public ClientTickEvent() {\n super(Listener.At.HEAD);\n }\n}"
},
{
"identifier": "BooleanSetting",
"path": "src/java/xyz/apfelmus/cheeto/client/settings/BooleanSetting.java",
"snippet": "public class BooleanSetting {\n private boolean enabled;\n\n public BooleanSetting(boolean enable) {\n this.enabled = enable;\n }\n\n public boolean isEnabled() {\n return this.enabled;\n }\n\n public void setState(boolean enable) {\n this.enabled = enable;\n }\n}"
}
] | import java.util.ArrayList;
import java.util.Arrays;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import xyz.apfelmus.cf4m.annotation.Event;
import xyz.apfelmus.cf4m.annotation.Setting;
import xyz.apfelmus.cf4m.annotation.module.Module;
import xyz.apfelmus.cf4m.module.Category;
import xyz.apfelmus.cheeto.client.events.ClientTickEvent;
import xyz.apfelmus.cheeto.client.settings.BooleanSetting; | 721 | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.block.Block
* net.minecraft.client.Minecraft
* net.minecraft.init.Blocks
*/
package xyz.apfelmus.cheeto.client.modules.world;
@Module(name="BetterStonk", category=Category.WORLD)
public class BetterStonk {
@Setting(name="ShiftOnly")
private BooleanSetting shiftOnly = new BooleanSetting(false);
private static Minecraft mc = Minecraft.func_71410_x();
final ArrayList<Block> interactables = new ArrayList<Block>(Arrays.asList(new Block[]{Blocks.field_180410_as, Blocks.field_150467_bQ, Blocks.field_150461_bJ, Blocks.field_150324_C, Blocks.field_180412_aq, Blocks.field_150382_bo, Blocks.field_150483_bI, Blocks.field_150462_ai, Blocks.field_150486_ae, Blocks.field_180409_at, Blocks.field_150453_bW, Blocks.field_180402_cm, Blocks.field_150367_z, Blocks.field_150409_cd, Blocks.field_150381_bn, Blocks.field_150477_bB, Blocks.field_150460_al, Blocks.field_150438_bZ, Blocks.field_180411_ar, Blocks.field_150442_at, Blocks.field_150323_B, Blocks.field_150455_bV, Blocks.field_150441_bU, Blocks.field_150416_aS, Blocks.field_150413_aR, Blocks.field_150472_an, Blocks.field_150444_as, Blocks.field_150415_aT, Blocks.field_150447_bR, Blocks.field_150471_bO, Blocks.field_150430_aB, Blocks.field_180413_ao, Blocks.field_150465_bP}));
@Event | /*
* Decompiled with CFR 0.150.
*
* Could not load the following classes:
* net.minecraft.block.Block
* net.minecraft.client.Minecraft
* net.minecraft.init.Blocks
*/
package xyz.apfelmus.cheeto.client.modules.world;
@Module(name="BetterStonk", category=Category.WORLD)
public class BetterStonk {
@Setting(name="ShiftOnly")
private BooleanSetting shiftOnly = new BooleanSetting(false);
private static Minecraft mc = Minecraft.func_71410_x();
final ArrayList<Block> interactables = new ArrayList<Block>(Arrays.asList(new Block[]{Blocks.field_180410_as, Blocks.field_150467_bQ, Blocks.field_150461_bJ, Blocks.field_150324_C, Blocks.field_180412_aq, Blocks.field_150382_bo, Blocks.field_150483_bI, Blocks.field_150462_ai, Blocks.field_150486_ae, Blocks.field_180409_at, Blocks.field_150453_bW, Blocks.field_180402_cm, Blocks.field_150367_z, Blocks.field_150409_cd, Blocks.field_150381_bn, Blocks.field_150477_bB, Blocks.field_150460_al, Blocks.field_150438_bZ, Blocks.field_180411_ar, Blocks.field_150442_at, Blocks.field_150323_B, Blocks.field_150455_bV, Blocks.field_150441_bU, Blocks.field_150416_aS, Blocks.field_150413_aR, Blocks.field_150472_an, Blocks.field_150444_as, Blocks.field_150415_aT, Blocks.field_150447_bR, Blocks.field_150471_bO, Blocks.field_150430_aB, Blocks.field_180413_ao, Blocks.field_150465_bP}));
@Event | public void onTick(ClientTickEvent event) { | 1 | 2023-12-21 16:22:25+00:00 | 2k |
vitri-ent/finorza | src/main/java/io/pyke/vitri/finorza/inference/config/Config.java | [
{
"identifier": "IWindow",
"path": "src/main/java/io/pyke/vitri/finorza/inference/api/IWindow.java",
"snippet": "public interface IWindow {\r\n\tvoid vitri$resize(int newWidth, int newHeight);\r\n}\r"
},
{
"identifier": "ModOptionsScreen",
"path": "src/main/java/io/pyke/vitri/finorza/inference/gui/ModOptionsScreen.java",
"snippet": "public class ModOptionsScreen extends OptionsSubScreen {\r\n\tprivate final Screen previous;\r\n\tprivate OptionsList list;\r\n\r\n\tpublic ModOptionsScreen(Screen previous) {\r\n\t\tsuper(previous, Minecraft.getInstance().options, new TextComponent(\"Finorza Options\"));\r\n\t\tthis.previous = previous;\r\n\t}\r\n\r\n\tprotected void init() {\r\n\t\tthis.minecraft.keyboardHandler.setSendRepeatsToGui(true);\r\n\t\tthis.list = new OptionsList(this.minecraft, this.width, this.height, 32, this.height - 32, 25);\r\n\t\tthis.list.addSmall(Config.asOptions());\r\n\t\tthis.children.add(this.list);\r\n\t\tthis.addButton(\r\n\t\t\tnew Button(this.width / 2 - 100, this.height - 27, 200, 20, CommonComponents.GUI_DONE, (button) -> {\r\n\t\t\t\tConfigManager.save();\r\n\t\t\t\tthis.minecraft.setScreen(this.previous);\r\n\t\t\t}));\r\n\t}\r\n\r\n\tpublic void render(PoseStack matrices, int mouseX, int mouseY, float delta) {\r\n\t\tthis.renderBackground(matrices);\r\n\t\tthis.list.render(matrices, mouseX, mouseY, delta);\r\n\t\tdrawCenteredString(matrices, this.font, this.title, this.width / 2, 5, 0xFFFFFF);\r\n\t\tsuper.render(matrices, mouseX, mouseY, delta);\r\n\t\tList<FormattedCharSequence> tooltip = tooltipAt(this.list, mouseX, mouseY);\r\n\t\tif (tooltip != null) {\r\n\t\t\tthis.renderTooltip(matrices, tooltip, mouseX, mouseY);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void removed() {\r\n\t\tConfigManager.save();\r\n\t}\r\n}\r"
}
] | import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import com.google.gson.annotations.SerializedName;
import net.minecraft.client.Minecraft;
import net.minecraft.client.Option;
import net.minecraft.client.gui.screens.GenericDirtMessageScreen;
import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.network.chat.TextComponent;
import io.pyke.vitri.finorza.inference.api.IWindow;
import io.pyke.vitri.finorza.inference.gui.ModOptionsScreen;
| 651 | package io.pyke.vitri.finorza.inference.config;
public class Config {
public static final BooleanConfigOption SYNCHRONIZE_INTEGRATED_SERVER = new BooleanConfigOption(
"synchronizeIntegratedServer", false, (ignored, value) -> {
Minecraft mc = Minecraft.getInstance();
if (mc.hasSingleplayerServer()) {
mc.level.disconnect();
mc.clearLevel(new GenericDirtMessageScreen(new TextComponent("Saving world")));
| package io.pyke.vitri.finorza.inference.config;
public class Config {
public static final BooleanConfigOption SYNCHRONIZE_INTEGRATED_SERVER = new BooleanConfigOption(
"synchronizeIntegratedServer", false, (ignored, value) -> {
Minecraft mc = Minecraft.getInstance();
if (mc.hasSingleplayerServer()) {
mc.level.disconnect();
mc.clearLevel(new GenericDirtMessageScreen(new TextComponent("Saving world")));
| mc.setScreen(new ModOptionsScreen(new TitleScreen()));
| 1 | 2023-12-20 05:19:21+00:00 | 2k |
emtee40/ApkSignatureKill-pc | apksigner/src/main/java/com/android/apksig/internal/pkcs7/SignerInfo.java | [
{
"identifier": "Asn1OpaqueObject",
"path": "apksigner/src/main/java/com/android/apksig/internal/asn1/Asn1OpaqueObject.java",
"snippet": "public class Asn1OpaqueObject {\n private final ByteBuffer mEncoded;\n\n public Asn1OpaqueObject(ByteBuffer encoded) {\n mEncoded = encoded.slice();\n }\n\n public Asn1OpaqueObject(byte[] encoded) {\n mEncoded = ByteBuffer.wrap(encoded);\n }\n\n public ByteBuffer getEncoded() {\n return mEncoded.slice();\n }\n}"
},
{
"identifier": "Asn1Tagging",
"path": "apksigner/src/main/java/com/android/apksig/internal/asn1/Asn1Tagging.java",
"snippet": "public enum Asn1Tagging {\n NORMAL,\n EXPLICIT,\n IMPLICIT,\n}"
},
{
"identifier": "Asn1Type",
"path": "apksigner/src/main/java/com/android/apksig/internal/asn1/Asn1Type.java",
"snippet": "public enum Asn1Type {\n ANY,\n CHOICE,\n INTEGER,\n OBJECT_IDENTIFIER,\n OCTET_STRING,\n SEQUENCE,\n SEQUENCE_OF,\n SET_OF,\n BIT_STRING,\n UTC_TIME,\n GENERALIZED_TIME,\n BOOLEAN,\n // This type can be used to annotate classes that encapsulate ASN.1 structures that are not\n // classified as a SEQUENCE or SET.\n UNENCODED_CONTAINER\n}"
}
] | import com.android.apksig.internal.asn1.Asn1Class;
import com.android.apksig.internal.asn1.Asn1Field;
import com.android.apksig.internal.asn1.Asn1OpaqueObject;
import com.android.apksig.internal.asn1.Asn1Tagging;
import com.android.apksig.internal.asn1.Asn1Type;
import java.nio.ByteBuffer;
import java.util.List; | 708 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.apksig.internal.pkcs7;
/**
* PKCS #7 {@code SignerInfo} as specified in RFC 5652.
*/
@Asn1Class(type = Asn1Type.SEQUENCE)
public class SignerInfo {
@Asn1Field(index = 0, type = Asn1Type.INTEGER)
public int version;
@Asn1Field(index = 1, type = Asn1Type.CHOICE)
public SignerIdentifier sid;
@Asn1Field(index = 2, type = Asn1Type.SEQUENCE)
public AlgorithmIdentifier digestAlgorithm;
@Asn1Field(
index = 3,
type = Asn1Type.SET_OF, | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.apksig.internal.pkcs7;
/**
* PKCS #7 {@code SignerInfo} as specified in RFC 5652.
*/
@Asn1Class(type = Asn1Type.SEQUENCE)
public class SignerInfo {
@Asn1Field(index = 0, type = Asn1Type.INTEGER)
public int version;
@Asn1Field(index = 1, type = Asn1Type.CHOICE)
public SignerIdentifier sid;
@Asn1Field(index = 2, type = Asn1Type.SEQUENCE)
public AlgorithmIdentifier digestAlgorithm;
@Asn1Field(
index = 3,
type = Asn1Type.SET_OF, | tagging = Asn1Tagging.IMPLICIT, tagNumber = 0, | 1 | 2023-12-16 11:11:16+00:00 | 2k |
nimashidewanmini/layered-architecture-nimashi | src/main/java/com/example/layeredarchitecture/controller/ManageCustomersFormController.java | [
{
"identifier": "CustomerDao",
"path": "src/main/java/com/example/layeredarchitecture/dao/CustomerDao.java",
"snippet": "public interface CustomerDao {\n ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException;\n boolean saveCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException ;\n void updateCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException ;\n boolean existCustomer(String id) throws SQLException, ClassNotFoundException ;\n void deleteCustomer(String id) throws SQLException, ClassNotFoundException ;\n\n String genarateId() throws SQLException, ClassNotFoundException ;\n}"
},
{
"identifier": "customerDAOImpl",
"path": "src/main/java/com/example/layeredarchitecture/dao/customerDAOImpl.java",
"snippet": "public class customerDAOImpl implements CustomerDao{\n @Override\n public ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n Statement stm = connection.createStatement();\n ResultSet rst = stm.executeQuery(\"SELECT * FROM Customer\");\n\n ArrayList<CustomerDTO> customerDTOS=new ArrayList<>();\n\n while (rst.next()){\n customerDTOS.add(new CustomerDTO(\n rst.getString(\"id\"),\n rst.getString(\"name\"),\n rst.getString(\"address\")));\n }\n return getAllCustomer();\n }\n\n @Override\n public boolean saveCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"INSERT INTO Customer (id,name, address) VALUES (?,?,?)\");\n pstm.setString(1, dto.getId());\n pstm.setString(2, dto.getName());\n pstm.setString(3, dto.getAddress());\n return pstm.executeUpdate() > 0;\n }\n\n\n\n @Override\n\n public void updateCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"UPDATE Customer SET name=?, address=? WHERE id=?\");\n pstm.setString(1, dto.getName());\n pstm.setString(2, dto.getAddress());\n pstm.setString(3, dto.getId());\n pstm.executeUpdate();\n }\n\n @Override\n public boolean existCustomer(String id) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"SELECT id FROM Customer WHERE id=?\");\n pstm.setString(1, id);\n return pstm.executeQuery().next();\n }\n\n @Override\n public void deleteCustomer(String id) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(\"DELETE FROM Customer WHERE id=?\");\n pstm.setString(1, id);\n pstm.executeUpdate();\n }\n\n @Override\n public String genarateId() throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n ResultSet rst = connection.createStatement().executeQuery(\"SELECT id FROM Customer ORDER BY id DESC LIMIT 1;\");\n if (rst.next()) {\n String id = rst.getString(\"id\");\n int newCustomerId = Integer.parseInt(id.replace(\"C00-\", \"\")) + 1;\n return String.format(\"C00-%03d\", newCustomerId);\n } else {\n return \"C00-001\";\n }\n }\n\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO() {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "CustomerTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/CustomerTM.java",
"snippet": "public class CustomerTM implements Comparable<CustomerTM> {\n private String id;\n private String name;\n private String address;\n\n public CustomerTM() {\n }\n\n public CustomerTM(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerTM{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n\n\n @Override\n public int compareTo(CustomerTM o) {\n return id.compareTo(o.getId());\n }\n}"
}
] | import com.example.layeredarchitecture.dao.CustomerDao;
import com.example.layeredarchitecture.dao.customerDAOImpl;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.view.tdm.CustomerTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | 1,558 | package com.example.layeredarchitecture.controller;
public class ManageCustomersFormController {
public AnchorPane root;
public TextField txtCustomerName;
public TextField txtCustomerId;
public JFXButton btnDelete;
public JFXButton btnSave;
public TextField txtCustomerAddress; | package com.example.layeredarchitecture.controller;
public class ManageCustomersFormController {
public AnchorPane root;
public TextField txtCustomerName;
public TextField txtCustomerId;
public JFXButton btnDelete;
public JFXButton btnSave;
public TextField txtCustomerAddress; | public TableView<CustomerTM> tblCustomers; | 3 | 2023-12-16 04:14:29+00:00 | 2k |
ElvesAguiar/dispesas_pessoais_api | src/main/java/com/elves/expensesApi/services/TransactionService.java | [
{
"identifier": "TransactionDto",
"path": "src/main/java/com/elves/expensesApi/dto/TransactionDto.java",
"snippet": "public class TransactionDto {\n private String id;\n\n @NotBlank(message = \"Campo não pode ser vazio.\")\n private String title;\n\n @NotNull(message = \"Campo não pode ser nulo.\")\n private Double value;\n\n @NotNull(message = \"Campo não pode ser nulo.\")\n private Date date;\n\n public TransactionDto() {\n }\n\n public TransactionDto(String id, String title, Double transactionValue, Date trasactionDate) {\n this.id = id;\n this.title = title;\n this.value = transactionValue;\n this.date = trasactionDate;\n }\n\n public TransactionDto(Transaction entity) {\n id = entity.getId().toString();\n title = entity.getTitle();\n value = entity.getValue();\n date = entity.getDate();\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public Double getValue() {\n return value;\n }\n\n public Date getDate() {\n return date;\n }\n}"
},
{
"identifier": "ResourceNotFoundException",
"path": "src/main/java/com/elves/expensesApi/services/exceptions/ResourceNotFoundException.java",
"snippet": "public class ResourceNotFoundException extends RuntimeException{\n public ResourceNotFoundException(String msg){\n super(msg);\n }\n}"
},
{
"identifier": "Transaction",
"path": "src/main/java/com/elves/expensesApi/models/Transaction.java",
"snippet": "@Entity\n@Table(name = \"tb_transaction\")\npublic class Transaction {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String title;\n private Double transactionValue;\n private Date trasactionDate;\n\n public Transaction(){\n\n }\n\n public Transaction(Long id, String title, Double value, Date date) {\n this.id = id;\n this.title = title;\n this.transactionValue = value;\n this.trasactionDate = date;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public Double getValue() {\n return transactionValue;\n }\n\n public void setValue(Double value) {\n this.transactionValue = value;\n }\n\n public Date getDate() {\n return trasactionDate;\n }\n\n public void setDate(Date date) {\n this.trasactionDate = date;\n }\n}"
},
{
"identifier": "TransactionRepository",
"path": "src/main/java/com/elves/expensesApi/repositories/TransactionRepository.java",
"snippet": "@Repository\npublic interface TransactionRepository extends JpaRepository<Transaction, Long> {\n}"
}
] | import com.elves.expensesApi.dto.TransactionDto;
import com.elves.expensesApi.services.exceptions.ResourceNotFoundException;
import com.elves.expensesApi.models.Transaction;
import com.elves.expensesApi.repositories.TransactionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List; | 917 | package com.elves.expensesApi.services;
@Service
public class TransactionService {
@Autowired
private TransactionRepository repository;
@Transactional(readOnly = true)
public List<TransactionDto> findAll (){
return repository.findAll().stream().map(tr -> new TransactionDto(tr)).toList();
}
@Transactional
public TransactionDto insert(TransactionDto dto){
Transaction tr = new Transaction();
tr.setTitle(dto.getTitle());
tr.setValue(dto.getValue());
tr.setDate(dto.getDate());
dto=new TransactionDto(repository.save(tr));
return dto;
}
@Transactional
public void delete(Long id){ | package com.elves.expensesApi.services;
@Service
public class TransactionService {
@Autowired
private TransactionRepository repository;
@Transactional(readOnly = true)
public List<TransactionDto> findAll (){
return repository.findAll().stream().map(tr -> new TransactionDto(tr)).toList();
}
@Transactional
public TransactionDto insert(TransactionDto dto){
Transaction tr = new Transaction();
tr.setTitle(dto.getTitle());
tr.setValue(dto.getValue());
tr.setDate(dto.getDate());
dto=new TransactionDto(repository.save(tr));
return dto;
}
@Transactional
public void delete(Long id){ | Transaction tr = repository.findById(id).orElseThrow(()-> new ResourceNotFoundException("Recurso não encontrado!")); | 1 | 2023-12-21 15:03:02+00:00 | 2k |
J-SPOT/playground | backend/funnyboard/src/main/java/funnyboard/service/ArticleService.java | [
{
"identifier": "ArticleCreationHasId",
"path": "backend/funnyboard/src/main/java/funnyboard/config/error/exception/article/ArticleCreationHasId.java",
"snippet": "public class ArticleCreationHasId extends InvalidInputValueException {\n public ArticleCreationHasId() {\n super(ErrorCode.ARTICLE_CREATION_HAS_ID);\n }\n}"
},
{
"identifier": "ArticleNotFoundException",
"path": "backend/funnyboard/src/main/java/funnyboard/config/error/exception/article/ArticleNotFoundException.java",
"snippet": "public class ArticleNotFoundException extends NotFoundException {\n public ArticleNotFoundException() {\n super(ErrorCode.ARTICLE_NOT_FOUND);\n }\n}"
},
{
"identifier": "ArticleUpdateIdNotValid",
"path": "backend/funnyboard/src/main/java/funnyboard/config/error/exception/article/ArticleUpdateIdNotValid.java",
"snippet": "public class ArticleUpdateIdNotValid extends InvalidInputValueException {\n public ArticleUpdateIdNotValid() {\n super(ErrorCode.ARTICLE_UPDATE_NOT_VALID);\n }\n}"
},
{
"identifier": "Article",
"path": "backend/funnyboard/src/main/java/funnyboard/domain/Article.java",
"snippet": "@Entity\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\n@ToString\npublic class Article {\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n private String title;\n private String content;\n\n public static ArticleForm toForm(Article article) {\n return new ArticleForm(article.getId(), article.getTitle(), article.getContent());\n }\n\n public static ArticleUpdateRequest toUpdateRequest(Article article) {\n return new ArticleUpdateRequest(article.getId(), article.getTitle(), article.getContent());\n }\n\n public void patch(ArticleUpdateRequest dto) {\n if (dto.getTitle() != null) {\n this.title = dto.getTitle();\n }\n if (dto.getContent() != null) {\n this.content = dto.getContent();\n }\n }\n}"
},
{
"identifier": "ArticleForm",
"path": "backend/funnyboard/src/main/java/funnyboard/dto/ArticleForm.java",
"snippet": "@ToString\n@Getter\n@AllArgsConstructor\n@NoArgsConstructor\npublic class ArticleForm {\n private Long id;\n private String title;\n private String content;\n\n public Article toEntity() {\n return new Article(id, title, content);\n }\n}"
},
{
"identifier": "ArticleUpdateRequest",
"path": "backend/funnyboard/src/main/java/funnyboard/dto/ArticleUpdateRequest.java",
"snippet": "@ToString\n@AllArgsConstructor\n@NoArgsConstructor\n@Getter\npublic class ArticleUpdateRequest {\n private Long id;\n private String title;\n private String content;\n\n public Article toEntity() {\n return new Article(id, title, content);\n }\n}"
},
{
"identifier": "ArticleRepository",
"path": "backend/funnyboard/src/main/java/funnyboard/repository/ArticleRepository.java",
"snippet": "@Repository\npublic interface ArticleRepository extends JpaRepository<Article, Long> {\n}"
}
] | import funnyboard.config.error.exception.article.ArticleCreationHasId;
import funnyboard.config.error.exception.article.ArticleNotFoundException;
import funnyboard.config.error.exception.article.ArticleUpdateIdNotValid;
import funnyboard.domain.Article;
import funnyboard.dto.ArticleForm;
import funnyboard.dto.ArticleUpdateRequest;
import funnyboard.repository.ArticleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors; | 758 | package funnyboard.service;
@Service
@Slf4j
public class ArticleService {
private final ArticleRepository articleRepository;
public ArticleService(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
| package funnyboard.service;
@Service
@Slf4j
public class ArticleService {
private final ArticleRepository articleRepository;
public ArticleService(ArticleRepository articleRepository) {
this.articleRepository = articleRepository;
}
| public ArticleForm create(ArticleForm dto) { | 4 | 2023-12-15 16:05:45+00:00 | 2k |
kaftsang/gemini-java-client | src/main/java/org/catmintt/geminiclient/web/GeminiController.java | [
{
"identifier": "GeminiService",
"path": "src/main/java/org/catmintt/geminiclient/service/GeminiService.java",
"snippet": "@Component\npublic class GeminiService {\n\n private static final String BASE_URL = \"https://generativelanguage.googleapis.com\";\n\n private static final String TEXT_ONLY_INPUT_URL = BASE_URL + \"/v1beta/models/gemini-pro:generateContent\";\n\n @Value(\"${gemini.api.key}\")\n private String API_KEY;\n\n @Autowired\n WebClient webClient;\n\n public Mono<GeminiResponse> textOnlyInput(GeminiRequest request) {\n String url = TEXT_ONLY_INPUT_URL + \"?key=\" + API_KEY;\n return webClient.post()\n .uri(url)\n .header(\"Content-Type\", \"application/json\")\n .bodyValue(request)\n .retrieve()\n .bodyToMono(GeminiResponse.class);\n }\n\n public String textAndImageInput(GeminiRequest request) {\n return null;\n }\n\n public String chat(GeminiRequest request) {\n return null;\n }\n\n public String configuration(GeminiRequest request) {\n return null;\n }\n\n public String streamGenerateContent(GeminiRequest request) {\n return null;\n }\n\n public String countTokens(GeminiRequest request) {\n return null;\n }\n\n public String embedding(GeminiRequest request) {\n return null;\n }\n\n public String getModel(GeminiRequest request) {\n return null;\n }\n\n public String listModels(GeminiRequest request) {\n return null;\n }\n}"
},
{
"identifier": "Content",
"path": "src/main/java/org/catmintt/geminiclient/service/model/Content.java",
"snippet": "public class Content {\n\n private List<Part> parts;\n\n private String role;\n\n public List<Part> getParts() {\n return parts;\n }\n\n public void setParts(List<Part> parts) {\n this.parts = parts;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n}"
},
{
"identifier": "GeminiRequest",
"path": "src/main/java/org/catmintt/geminiclient/service/model/GeminiRequest.java",
"snippet": "public class GeminiRequest {\n\n private List<Content> contents;\n\n public List<Content> getContents() {\n return contents;\n }\n\n public void setContents(List<Content> contents) {\n this.contents = contents;\n }\n}"
},
{
"identifier": "GeminiResponse",
"path": "src/main/java/org/catmintt/geminiclient/service/model/GeminiResponse.java",
"snippet": "public class GeminiResponse {\n\n private List<Candidate> candidates;\n\n private PromptFeedback promptFeedback;\n\n public List<Candidate> getCandidates() {\n return candidates;\n }\n\n public void setCandidates(List<Candidate> candidates) {\n this.candidates = candidates;\n }\n\n public PromptFeedback getPromptFeedback() {\n return promptFeedback;\n }\n\n public void setPromptFeedback(PromptFeedback promptFeedback) {\n this.promptFeedback = promptFeedback;\n }\n}"
},
{
"identifier": "Part",
"path": "src/main/java/org/catmintt/geminiclient/service/model/Part.java",
"snippet": "public class Part {\n\n private String text;\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n}"
}
] | import org.catmintt.geminiclient.service.GeminiService;
import org.catmintt.geminiclient.service.model.Content;
import org.catmintt.geminiclient.service.model.GeminiRequest;
import org.catmintt.geminiclient.service.model.GeminiResponse;
import org.catmintt.geminiclient.service.model.Part;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.util.ArrayList; | 1,001 | package org.catmintt.geminiclient.web;
@RestController
@RequestMapping("api/gemini")
public class GeminiController {
@Autowired | package org.catmintt.geminiclient.web;
@RestController
@RequestMapping("api/gemini")
public class GeminiController {
@Autowired | GeminiService geminiService; | 0 | 2023-12-17 11:30:30+00:00 | 2k |
federic0casu/DSMT-Project | web-app/src/main/java/it/unipi/dsmt/javaee/webapp/servlets/LoginServlet.java | [
{
"identifier": "UserDAO",
"path": "web-app/src/main/java/it/unipi/dsmt/javaee/webapp/DAO/UserDAO.java",
"snippet": "public class UserDAO {\n private final Connection connection;\n public UserDAO(Connection connection) {\n this.connection = connection;\n }\n public UserDTO getUserByUsernameAndPassword(String username, String password) throws SQLException {\n String query = \"SELECT * FROM users WHERE username = ? AND password = ?\";\n try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {\n preparedStatement.setString(1, username);\n preparedStatement.setString(2, password);\n\n try (ResultSet resultSet = preparedStatement.executeQuery()) {\n if (resultSet.next()) {\n return new UserDTO(resultSet.getInt(\"id\"),\n resultSet.getString(\"username\"),\n resultSet.getString(\"password\"));\n }\n }\n }\n return null; // Return null if no user found\n }\n}"
},
{
"identifier": "UserDTO",
"path": "web-app/src/main/java/it/unipi/dsmt/javaee/webapp/DTO/UserDTO.java",
"snippet": "public class UserDTO {\n private final int id;\n private final String username;\n private final String password;\n\n public UserDTO(int id, String username, String password) {\n this.id = id;\n this.username = username;\n this.password = password;\n }\n}"
},
{
"identifier": "MySQLConnector",
"path": "web-app/src/main/java/it/unipi/dsmt/javaee/webapp/repository/MySQLConnector.java",
"snippet": "public class MySQLConnector {\n private static final String URL = \"jdbc:mysql://db:3306/fraud_detection_db\";\n private static final String USER = \"fraud_detection_user\";\n private static final String PASSWORD = \"fraud_detection_password\";\n\n private final Connection connection;\n\n public MySQLConnector() {\n try {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(URL, USER, PASSWORD);\n } catch (ClassNotFoundException | SQLException e) {\n throw new RuntimeException(e.getMessage());\n }\n }\n\n public Connection getConnection() {\n return connection;\n }\n \n public void closeConnection() {\n try {\n if (connection != null && !connection.isClosed()) {\n connection.close();\n }\n } catch (SQLException e) {\n throw new RuntimeException(e.getMessage());\n }\n }\n}"
}
] | import it.unipi.dsmt.javaee.webapp.DAO.UserDAO;
import it.unipi.dsmt.javaee.webapp.DTO.UserDTO;
import it.unipi.dsmt.javaee.webapp.repository.MySQLConnector;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException; | 736 | package it.unipi.dsmt.javaee.webapp.servlets;
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
MySQLConnector connector = new MySQLConnector();
try (Connection connection = connector.getConnection()) {
if (connection != null) { | package it.unipi.dsmt.javaee.webapp.servlets;
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
MySQLConnector connector = new MySQLConnector();
try (Connection connection = connector.getConnection()) {
if (connection != null) { | UserDAO userDAO = new UserDAO(connection); | 0 | 2023-12-15 09:51:30+00:00 | 2k |
ohhoonim/lms | domain/src/test/java/dev/ohhoonim/lms/domain/post/PostUsecaseTest.java | [
{
"identifier": "PostAgent",
"path": "domain/src/main/java/dev/ohhoonim/lms/domain/post/api/PostAgent.java",
"snippet": "@Service\npublic class PostAgent implements PostUsecase {\n \n private final PostQueryPort postQueryPort;\n private final PostCommandPort postCommandPort;\n\n public PostAgent(PostQueryPort postQueryPort, PostCommandPort postCommandPort) {\n this.postQueryPort = postQueryPort;\n this.postCommandPort = postCommandPort;\n }\n \n @Override\n public List<Post> posts(Condition<Post, Long> postConditions) {\n return postQueryPort.posts(postConditions);\n }\n\n @Override\n public List<Comment> refreshComments(Long postId) {\n return postQueryPort.refreshComments(postId);\n }\n\n @Override\n public Post getPost(Long id) {\n return postQueryPort.getPost(id).get();\n }\n\n @Override\n public void addPost(Post post) {\n postCommandPort.addPost(post);\n }\n\n @Override\n public void updatePost(Post post) {\n postCommandPort.updatePost(post);\n }\n\n @Override\n public void deletePost(Long id) {\n postCommandPort.deletePost(id);\n }\n\n \n\n \n}"
},
{
"identifier": "PostCommandPort",
"path": "domain/src/main/java/dev/ohhoonim/lms/domain/post/infra/PostCommandPort.java",
"snippet": "public interface PostCommandPort {\n\n void addPost(Post post);\n\n void updatePost(Post post);\n\n void deletePost(Long id);\n \n}"
},
{
"identifier": "PostQueryPort",
"path": "domain/src/main/java/dev/ohhoonim/lms/domain/post/infra/PostQueryPort.java",
"snippet": "public interface PostQueryPort {\n\n List<Post> posts(Condition<Post, Long> condition);\n\n Optional<Post> getPost(Long id);\n\n List<Comment> refreshComments(Long postId);\n \n}"
}
] | import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import dev.ohhoonim.lms.domain.post.api.PostAgent;
import dev.ohhoonim.lms.domain.post.infra.PostCommandPort;
import dev.ohhoonim.lms.domain.post.infra.PostQueryPort;
import dev.ohhoonim.lms.domain.utils.Condition; | 690 | package dev.ohhoonim.lms.domain.post;
@ExtendWith(MockitoExtension.class)
public class PostUsecaseTest {
@InjectMocks | package dev.ohhoonim.lms.domain.post;
@ExtendWith(MockitoExtension.class)
public class PostUsecaseTest {
@InjectMocks | PostAgent postAgent; | 0 | 2023-12-18 06:39:50+00:00 | 2k |
matthiasbergneels/dhbwmawwi2023seb | src/lecture/chapter4/CarRun.java | [
{
"identifier": "Brand",
"path": "src/lecture/chapter5/Brand.java",
"snippet": "public enum Brand {\n MERCEDES(\"$$$\"),\n TESLA(\"$$\"),\n FIAT(\"$\"),\n OPEL(\"$\");\n\n private String priceTag;\n Brand(String priceTag){\n this.priceTag = priceTag;\n }\n\n public String getPriceTag(){\n return priceTag;\n }\n\n @Override\n public String toString(){\n return switch(this){\n case MERCEDES -> \"Mercedes\";\n case TESLA -> \"Tesla\";\n case FIAT -> \"FIAT\";\n case OPEL -> \"Opel\";\n };\n }\n}"
},
{
"identifier": "Car",
"path": "src/lecture/chapter5/Car.java",
"snippet": "public class Car {\n\n // Attribute\n private String color;\n private int hp;\n private double currentSpeed;\n public final Brand BRAND;\n private byte doorCount;\n\n // Klassenattribute\n private static int carCount;\n\n // finale Klassenattribute\n public static final String COLOR_RED = \"ROT\";\n public static final String COLOR_BLUE = \"BLAU\";\n public static final String COLOR_BLACK = \"SCHWARZ\";\n public static final String COLOR_WHITE = \"WEISS\";\n public static final String COLOR_GREY = \"GRAU\";\n\n\n static{\n // Lade aktuelle CarCount aus Datenbank\n System.out.println(\"Initialisierungsblock für die Klasse Car\");\n carCount = 0;\n }\n\n\n {\n System.out.println(\"Initialisierungsblock vor dem Konstruktor\");\n currentSpeed = 0;\n }\n\n // Konstruktoren\n public Car(String color, Brand brand, int hp, byte doorCount){\n this.color = color;\n BRAND = brand;\n this.hp = hp;\n this.doorCount = doorCount;\n\n carCount++;\n }\n\n\n\n public Car(){\n this(\"Schwarz\", Brand.TESLA, 500, (byte)5);\n /*color = \"Schwarz\";\n BRAND = \"Tesla\";\n hp = 500;\n doorCount = 5;\n\n currentSpeed = 0;\n */\n }\n\n // Methoden\n public void accelerate(double speedDelta){\n this.currentSpeed += speedDelta;\n }\n\n public void brake(){\n currentSpeed -= 10;\n }\n\n public double getCurrentSpeed(){\n return currentSpeed;\n }\n\n public String getColor(){\n return color;\n }\n\n public int getHp(){\n return hp;\n }\n\n public void setColor(String color){\n if(color.equals(COLOR_BLUE) ||\n color.equals(COLOR_BLACK)||\n color.equals(COLOR_RED)||\n color.equals(COLOR_GREY)||\n color.equals(COLOR_WHITE)){\n this.color = color;\n } else {\n this.color = COLOR_BLACK;\n }\n }\n\n protected void setHp(int pHp){\n // TODO\n }\n\n public String getBrandPriceTag(){\n return BRAND.getPriceTag();\n }\n\n @Override\n protected void finalize() throws Throwable {\n carCount--;\n System.out.println(\"Das Auto von der Marke \" + this.BRAND + \" mit \" + this.hp + \" PS wird verschrottet.\");\n }\n\n // Klassen-Methoden\n public static int getCarCount(){\n return carCount;\n }\n\n public static void printCarInfo(Car carToPrint){\n System.out.println(\"Autodetails:\");\n System.out.println(\"Marke: \" + carToPrint.BRAND);\n System.out.println(\"Farbe: \" + carToPrint.color);\n System.out.println(\"Leistung: \" + carToPrint.hp);\n System.out.println(\"Aktuelle Geschwindigkeit: \" + carToPrint.currentSpeed);\n }\n\n\n}"
}
] | import lecture.chapter5.Brand;
import lecture.chapter5.Car; | 995 | package lecture.chapter4;
public class CarRun {
public static void main(String[] args) {
| package lecture.chapter4;
public class CarRun {
public static void main(String[] args) {
| Car myCar = new Car("Blau", Brand.FIAT, 100, (byte)5); | 1 | 2023-12-20 21:17:12+00:00 | 2k |
aborroy/alfresco-genai | alfresco-ai/alfresco-ai-applier/src/main/java/org/alfresco/genai/service/GenAiClient.java | [
{
"identifier": "Summary",
"path": "alfresco-ai/alfresco-ai-applier/src/main/java/org/alfresco/genai/model/Summary.java",
"snippet": "public class Summary {\n\n /**\n * The summarized text content of the document.\n */\n private String summary;\n\n /**\n * A list of tags associated with the document.\n */\n private List<String> tags;\n\n /**\n * The model used for summarization.\n */\n private String model;\n\n /**\n * Gets the summarized text content of the document.\n *\n * @return The summary text.\n */\n public String getSummary() {\n return summary;\n }\n\n /**\n * Sets the summarized text content of the document.\n *\n * @param summary The summary text.\n * @return This {@code Summary} instance for method chaining.\n */\n public Summary summary(String summary) {\n this.summary = summary;\n return this;\n }\n\n /**\n * Gets the list of tags associated with the document.\n *\n * @return The list of tags.\n */\n public List<String> getTags() {\n return tags;\n }\n\n /**\n * Sets the list of tags associated with the document.\n *\n * @param tags The list of tags.\n * @return This {@code Summary} instance for method chaining.\n */\n public Summary tags(List<String> tags) {\n this.tags = tags;\n return this;\n }\n\n /**\n * Gets the model used for summarization.\n *\n * @return The summarization model.\n */\n public String getModel() {\n return model;\n }\n\n /**\n * Sets the model used for summarization.\n *\n * @param model The summarization model.\n * @return This {@code Summary} instance for method chaining.\n */\n public Summary model(String model) {\n this.model = model;\n return this;\n }\n\n}"
},
{
"identifier": "Term",
"path": "alfresco-ai/alfresco-ai-applier/src/main/java/org/alfresco/genai/model/Term.java",
"snippet": "public class Term {\n\n /**\n * The selected term content.\n */\n private String term;\n\n /**\n * The model information associated with the generated answer.\n */\n private String model;\n\n /**\n * Gets the generated term content.\n *\n * @return The term content.\n */\n public String getTerm() {\n return term;\n }\n\n /**\n * Sets the term content and returns the current instance for method chaining.\n *\n * @param term The term content to set.\n * @return The current {@code Term} instance.\n */\n public Term term(String term) {\n this.term = term;\n return this;\n }\n\n /**\n * Gets the model information associated with the generated answer.\n *\n * @return The model information.\n */\n public String getModel() {\n return model;\n }\n\n /**\n * Sets the model information and returns the current instance for method chaining.\n *\n * @param model The model information to set.\n * @return The current {@code Answer} instance.\n */\n public Term model(String model) {\n this.model = model;\n return this;\n }\n}"
}
] | import jakarta.annotation.PostConstruct;
import okhttp3.*;
import org.alfresco.genai.model.Summary;
import org.alfresco.genai.model.Term;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JsonParser;
import org.springframework.boot.json.JsonParserFactory;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit; | 1,263 | package org.alfresco.genai.service;
/**
* The {@code GenAiClient} class is a Spring service responsible for interacting with the GenAI service to obtain
* summaries and terms. It uses an {@link OkHttpClient} to perform HTTP requests to the GenAI service endpoint.
*/
@Service
public class GenAiClient {
/**
* The base URL of the GenAI service obtained from configuration.
*/
@Value("${genai.url}")
String genaiUrl;
/**
* The request timeout for GenAI service requests obtained from configuration.
*/
@Value("${genai.request.timeout}")
Integer genaiTimeout;
/**
* Static instance of {@link JsonParser} to parse JSON responses from the GenAI service.
*/
static final JsonParser JSON_PARSER = JsonParserFactory.getJsonParser();
/**
* The OkHttpClient instance for making HTTP requests to the GenAI service.
*/
OkHttpClient client;
/**
* Initializes the OkHttpClient with specified timeouts during bean creation.
*/
@PostConstruct
public void init() {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(genaiTimeout, TimeUnit.SECONDS)
.build();
}
/**
* Retrieves a document summary from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file for which the summary is requested.
* @return A {@link Summary} object containing the summary, tags, and model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/ | package org.alfresco.genai.service;
/**
* The {@code GenAiClient} class is a Spring service responsible for interacting with the GenAI service to obtain
* summaries and terms. It uses an {@link OkHttpClient} to perform HTTP requests to the GenAI service endpoint.
*/
@Service
public class GenAiClient {
/**
* The base URL of the GenAI service obtained from configuration.
*/
@Value("${genai.url}")
String genaiUrl;
/**
* The request timeout for GenAI service requests obtained from configuration.
*/
@Value("${genai.request.timeout}")
Integer genaiTimeout;
/**
* Static instance of {@link JsonParser} to parse JSON responses from the GenAI service.
*/
static final JsonParser JSON_PARSER = JsonParserFactory.getJsonParser();
/**
* The OkHttpClient instance for making HTTP requests to the GenAI service.
*/
OkHttpClient client;
/**
* Initializes the OkHttpClient with specified timeouts during bean creation.
*/
@PostConstruct
public void init() {
client = new OkHttpClient()
.newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(genaiTimeout, TimeUnit.SECONDS)
.build();
}
/**
* Retrieves a document summary from the GenAI service for the provided PDF file.
*
* @param pdfFile The PDF file for which the summary is requested.
* @return A {@link Summary} object containing the summary, tags, and model information.
* @throws IOException If an I/O error occurs during the HTTP request or response processing.
*/ | public Summary getSummary(File pdfFile) throws IOException { | 0 | 2023-12-21 12:28:53+00:00 | 2k |
dishantharuka/layered-architecture | src/main/java/com/example/layeredarchitecture/controller/ManageCustomersFormController.java | [
{
"identifier": "DBConnection",
"path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java",
"snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLException {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/company\", \"root\", \"12345678\");\n }\n\n public static DBConnection getDbConnection() throws SQLException, ClassNotFoundException {\n return dbConnection == null ? dbConnection= new DBConnection() : dbConnection;\n }\n\n public Connection getConnection() {\n return connection;\n }\n}"
},
{
"identifier": "CustomerTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/CustomerTM.java",
"snippet": "public class CustomerTM implements Comparable<CustomerTM> {\n private String id;\n private String name;\n private String address;\n\n public CustomerTM() {\n }\n\n public CustomerTM(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerTM{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n\n\n @Override\n public int compareTo(CustomerTM o) {\n return id.compareTo(o.getId());\n }\n}"
}
] | import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.view.tdm.CustomerTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | 673 | package com.example.layeredarchitecture.controller;
public class ManageCustomersFormController {
public AnchorPane root;
public TextField txtCustomerName;
public TextField txtCustomerId;
public JFXButton btnDelete;
public JFXButton btnSave;
public TextField txtCustomerAddress; | package com.example.layeredarchitecture.controller;
public class ManageCustomersFormController {
public AnchorPane root;
public TextField txtCustomerName;
public TextField txtCustomerId;
public JFXButton btnDelete;
public JFXButton btnSave;
public TextField txtCustomerAddress; | public TableView<CustomerTM> tblCustomers; | 1 | 2023-12-16 04:23:56+00:00 | 2k |
AnandakrishnanV/WordCounter | src/main/java/com/ak/wordcount/WordCounter.java | [
{
"identifier": "IWordCounter",
"path": "src/main/java/com/ak/wordcount/interfaces/IWordCounter.java",
"snippet": "public interface IWordCounter {\n\n\tvoid addWords(String text);\n\n\tint getWordCount(String word);\n\n}"
},
{
"identifier": "Translator",
"path": "src/main/java/com/ak/wordcount/interfaces/Translator.java",
"snippet": "public interface Translator {\n\n\tString translate(String word);\n}"
},
{
"identifier": "TextProcessingUtil",
"path": "src/main/java/com/ak/wordcount/util/TextProcessingUtil.java",
"snippet": "public class TextProcessingUtil {\n\n\t/**\n\t * Splits the given text into words based on non-word characters.\n\t * \n\t * @param text The input text to be split.\n\t * @return List of words.\n\t */\n\tpublic static List<String> splitTextIntoWords(String text) {\n\t\treturn Arrays.asList(text.toLowerCase().split(\"\\\\W+\"));\n\t}\n\n\t/**\n\t * Checks if the Word contains non-alphabetic characters\n\t * \n\t * @param word Input word to be checked.\n\t * @return boolean true or false.\n\t */\n\tpublic static boolean checkWordValidity(String word) {\n\n\t\tif (!word.matches(\"[a-zA-Z]+\")) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n}"
},
{
"identifier": "WordCountUtil",
"path": "src/main/java/com/ak/wordcount/util/WordCountUtil.java",
"snippet": "public class WordCountUtil {\n\t\n\tprivate static final Logger LOGGER = Logger.getLogger(WordCountUtil.class.getName());\n\n\t/**\n\t * Processes a single word: validates, translates, and updates its count.\n\t * \n\t * @param word The word to be processed.\n\t * @param wordCounts The map of word counts.\n\t * @param translator The translator interface.\n\t */\n\tpublic static void processWord(String word, ConcurrentHashMap<String, AtomicInteger> wordCounts,\n\t\t\tTranslator translator) {\n\t\tif (!TextProcessingUtil.checkWordValidity(word)) {\n\t\t\treturn; // Skip invalid words\n\t\t}\n\t\tString translatedWord = translator.translate(word);\n\t\tupdateWordCount(translatedWord, wordCounts);\n\t}\n\n\t/**\n\t * Processes a list of words in parallel, updating their counts.\n\t * \n\t * @param words The list of words to be processed.\n\t * @param wordCounts\n\t * @param translator\n\t */\n\tpublic static void processWordsInParallel(List<String> words, ConcurrentHashMap<String, AtomicInteger> wordCounts,\n\t\t\tTranslator translator) {\n\t\tForkJoinPool customThreadPool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());\n\t\ttry {\n\t\t\tcustomThreadPool\n\t\t\t\t\t.submit(() -> words.parallelStream().forEach(word -> processWord(word, wordCounts, translator)))\n\t\t\t\t\t.get(); // Ensures completion of all tasks\n\t\t} catch (InterruptedException | ExecutionException e) {\n\t\t\tLOGGER.severe(\"Error in parallel processing: \" + e.getMessage());\n\t\t\tThread.currentThread().interrupt();\n\t\t\tthrow new RuntimeException(\"Error processing words in parallel\", e);\n\t\t} finally {\n\t\t\tcustomThreadPool.shutdown(); // Prevents resource leakage\n\t\t}\n\t}\n\n\t/**\n\t * Updates the count of a given word in the word counter.\n\t * \n\t * @param word The word whose count is to be updated.\n\t * @param wordCounts The map of word counts.\n\t */\n\tpublic static void updateWordCount(String word, ConcurrentHashMap<String, AtomicInteger> wordCounts) {\n\t\twordCounts.compute(word, (key, count) -> {\n\t\t\tif (count == null)\n\t\t\t\treturn new AtomicInteger(1);\n\t\t\tcount.incrementAndGet();\n\t\t\treturn count;\n\t\t});\n\t}\n\n}"
}
] | import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import com.ak.wordcount.interfaces.IWordCounter;
import com.ak.wordcount.interfaces.Translator;
import com.ak.wordcount.util.TextProcessingUtil;
import com.ak.wordcount.util.WordCountUtil; | 1,121 | package com.ak.wordcount;
/**
* Word Counter with two functions:
* addWords takes input a String text, adds valid words to the hash map
* getWordCount takes single word as input, returns count if present
*
*/
@Service
@Primary
public class WordCounter implements IWordCounter {
private final Translator translator;
private final ConcurrentHashMap<String, AtomicInteger> wordCounts;
private static final Logger LOGGER = Logger.getLogger(WordCounter.class.getName());
public WordCounter(Translator translator) {
this.translator = translator;
this.wordCounts = new ConcurrentHashMap<>();
}
/**
* Adds words from a given text to the word counter.
*
* @param text The input text containing words to be counted.
*/
@Override
public void addWords(String text) {
if (text == null || text.isEmpty()) {
LOGGER.warning("Empty or null text provided");
return;
} | package com.ak.wordcount;
/**
* Word Counter with two functions:
* addWords takes input a String text, adds valid words to the hash map
* getWordCount takes single word as input, returns count if present
*
*/
@Service
@Primary
public class WordCounter implements IWordCounter {
private final Translator translator;
private final ConcurrentHashMap<String, AtomicInteger> wordCounts;
private static final Logger LOGGER = Logger.getLogger(WordCounter.class.getName());
public WordCounter(Translator translator) {
this.translator = translator;
this.wordCounts = new ConcurrentHashMap<>();
}
/**
* Adds words from a given text to the word counter.
*
* @param text The input text containing words to be counted.
*/
@Override
public void addWords(String text) {
if (text == null || text.isEmpty()) {
LOGGER.warning("Empty or null text provided");
return;
} | List<String> words = TextProcessingUtil.splitTextIntoWords(text); | 2 | 2023-12-19 07:02:57+00:00 | 2k |
123yyh123/xiaofanshu | xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/controller/UserRelationController.java | [
{
"identifier": "Result",
"path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java",
"snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n private T data;\n}"
},
{
"identifier": "UserRelationService",
"path": "xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/UserRelationService.java",
"snippet": "public interface UserRelationService {\n Result<Boolean> selectOneByUserIdAndBlackIdIsExist(Long toId, Long fromId);\n\n Result<Boolean> selectOneByUserIdAndAttentionIdIsExist(Long toId, Long fromId);\n\n Result<List<UserRelationVO>> selectAttentionList(Long userId, Integer pageNum, Integer pageSize);\n\n Result<List<UserRelationVO>> selectFansList(Long userId, Integer pageNum, Integer pageSize);\n\n Result<Boolean> attention(Long userId, Long targetUserId);\n\n Result<?> updateRemarkName(Long userId, Long targetUserId, String remarkName);\n}"
},
{
"identifier": "UserRelationVO",
"path": "xfs-modules-api/xfs-user-api/src/main/java/com/yyh/xfs/user/vo/UserRelationVO.java",
"snippet": "@Data\npublic class UserRelationVO {\n /**\n * 用户id\n */\n private Long userId;\n\n /**\n * 用户昵称(当有备注时,显示备注)\n */\n private String nickname;\n\n /**\n * 用户头像\n */\n private String avatarUrl;\n\n /**\n * 用户简介\n */\n private String selfIntroduction;\n\n /**\n * 是否为双向关系\n */\n private Boolean bidirectional;\n}"
},
{
"identifier": "ViewUserVO",
"path": "xfs-modules-api/xfs-user-api/src/main/java/com/yyh/xfs/user/vo/ViewUserVO.java",
"snippet": "@Getter\n@Setter\npublic class ViewUserVO implements Serializable {\n private static final long serialVersionUID = 1L;\n private Long id;\n private String uid;\n private String nickname;\n private String avatarUrl;\n private Integer age;\n private Integer sex;\n private String area;\n private String birthday;\n private String selfIntroduction;\n private String homePageBackground;\n private Integer attentionNum;\n private Integer fansNum;\n private Integer attentionStatus;\n}"
}
] | import com.yyh.xfs.common.domain.Result;
import com.yyh.xfs.user.service.UserRelationService;
import com.yyh.xfs.user.vo.UserRelationVO;
import com.yyh.xfs.user.vo.ViewUserVO;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 910 | package com.yyh.xfs.user.controller;
/**
* @author yyh
* @date 2024-01-15
*/
@RestController
@RequestMapping("/user/relation")
public class UserRelationController {
private final UserRelationService userRelationService;
public UserRelationController(UserRelationService userRelationService) {
this.userRelationService = userRelationService;
}
/**
* 查询是否存在黑名单
* @param toId 拉黑的用户id
* @param fromId 被拉黑的用户id
* @return 是否存在黑名单
*/
@GetMapping("/isBlack")
public Result<Boolean> selectOneByUserIdAndBlackIdIsExist(Long toId, Long fromId) {
return userRelationService.selectOneByUserIdAndBlackIdIsExist(toId, fromId);
}
/**
* 查询是否存在关注
* @param toId 关注的用户id
* @param fromId 被关注的用户id
* @return 是否存在关注
*/
@GetMapping("/isAttention")
public Result<Boolean> selectOneByUserIdAndAttentionIdIsExist(Long toId, Long fromId) {
return userRelationService.selectOneByUserIdAndAttentionIdIsExist(toId, fromId);
}
@GetMapping("/attentionList") | package com.yyh.xfs.user.controller;
/**
* @author yyh
* @date 2024-01-15
*/
@RestController
@RequestMapping("/user/relation")
public class UserRelationController {
private final UserRelationService userRelationService;
public UserRelationController(UserRelationService userRelationService) {
this.userRelationService = userRelationService;
}
/**
* 查询是否存在黑名单
* @param toId 拉黑的用户id
* @param fromId 被拉黑的用户id
* @return 是否存在黑名单
*/
@GetMapping("/isBlack")
public Result<Boolean> selectOneByUserIdAndBlackIdIsExist(Long toId, Long fromId) {
return userRelationService.selectOneByUserIdAndBlackIdIsExist(toId, fromId);
}
/**
* 查询是否存在关注
* @param toId 关注的用户id
* @param fromId 被关注的用户id
* @return 是否存在关注
*/
@GetMapping("/isAttention")
public Result<Boolean> selectOneByUserIdAndAttentionIdIsExist(Long toId, Long fromId) {
return userRelationService.selectOneByUserIdAndAttentionIdIsExist(toId, fromId);
}
@GetMapping("/attentionList") | public Result<List<UserRelationVO>> selectAttentionList(Long userId, Integer pageNum, Integer pageSize) { | 2 | 2023-12-15 08:13:42+00:00 | 2k |
catools2/athena | athena-api-boot/src/test/java/org/catools/athena/pact/provider/core/AthenaUserControllerPactProviderTest.java | [
{
"identifier": "UserDto",
"path": "athena-core/src/main/java/org/catools/athena/core/model/UserDto.java",
"snippet": "@Data\n@NoArgsConstructor\n@Accessors(chain = true)\npublic class UserDto implements Serializable {\n private Long id;\n\n @NotBlank\n @Size(max = 300)\n private String name;\n}"
},
{
"identifier": "AthenaCoreBuilder",
"path": "athena-api-boot/src/test/java/org/catools/athena/rest/core/builder/AthenaCoreBuilder.java",
"snippet": "@UtilityClass\npublic class AthenaCoreBuilder {\n public static UserDto buildUserDto() {\n return Instancio.of(UserDto.class)\n .ignore(field(UserDto::getId))\n .create();\n }\n\n public static User buildUser(UserDto userDto) {\n return new User()\n .setId(userDto.getId())\n .setName(userDto.getName());\n }\n\n public static ProjectDto buildProjectDto() {\n return Instancio.of(ProjectDto.class)\n .ignore(field(ProjectDto::getId))\n .generate(field(ProjectDto::getCode), gen -> gen.string().length(1, 5))\n .create();\n }\n\n public static Project buildProject(ProjectDto projectDto) {\n return new Project()\n .setId(projectDto.getId())\n .setCode(projectDto.getCode())\n .setName(projectDto.getName());\n }\n\n public static EnvironmentDto buildEnvironmentDto(ProjectDto project) {\n return Instancio.of(EnvironmentDto.class)\n .ignore(field(EnvironmentDto::getId))\n .generate(field(EnvironmentDto::getCode), gen -> gen.string().length(1, 5))\n .set(field(EnvironmentDto::getProjectCode), project.getCode())\n .create();\n }\n\n public static Environment buildEnvironment(EnvironmentDto environmentDto, Project project) {\n return new Environment()\n .setId(environmentDto.getId())\n .setName(environmentDto.getName())\n .setCode(environmentDto.getCode())\n .setProject(project);\n }\n}"
},
{
"identifier": "AthenaCoreControllerTest",
"path": "athena-api-boot/src/test/java/org/catools/athena/rest/core/controller/AthenaCoreControllerTest.java",
"snippet": "@SpringBootTest\npublic class AthenaCoreControllerTest extends AthenaBaseTest {\n\n @Autowired\n protected AthenaProjectController athenaProjectController;\n\n @Autowired\n protected AthenaEnvironmentController athenaEnvironmentController;\n\n @Autowired\n protected AthenaUserController athenaUserController;\n\n @Autowired\n protected AthenaPipelineController athenaPipelineController;\n}"
},
{
"identifier": "AthenaCorePactTestConstants",
"path": "athena-api-boot/src/test/java/org/catools/athena/pact/consumer/core/AthenaCorePactTestConstants.java",
"snippet": "public class AthenaCorePactTestConstants {\n\n public static final String PACT_FOLDER = \"target/pacts\";\n public static final String USER_CONSUMER_NAME = \"AthenaUserClient\";\n public static final String USER_PROVIDER_NAME = \"AthenaUserController\";\n\n}"
}
] | import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
import au.com.dius.pact.provider.junitsupport.Consumer;
import au.com.dius.pact.provider.junitsupport.Provider;
import au.com.dius.pact.provider.junitsupport.State;
import au.com.dius.pact.provider.junitsupport.loader.PactFolder;
import org.catools.athena.core.model.UserDto;
import org.catools.athena.rest.core.builder.AthenaCoreBuilder;
import org.catools.athena.rest.core.controller.AthenaCoreControllerTest;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import static org.catools.athena.pact.consumer.core.AthenaCorePactTestConstants.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue; | 973 | package org.catools.athena.pact.provider.core;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = "server.port=8080")
@Provider(USER_PROVIDER_NAME)
@Consumer(USER_CONSUMER_NAME)
@PactFolder(PACT_FOLDER)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) | package org.catools.athena.pact.provider.core;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = "server.port=8080")
@Provider(USER_PROVIDER_NAME)
@Consumer(USER_CONSUMER_NAME)
@PactFolder(PACT_FOLDER)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class) | public class AthenaUserControllerPactProviderTest extends AthenaCoreControllerTest { | 2 | 2023-12-16 22:30:49+00:00 | 2k |
premiering/permad-game | src/main/java/club/premiering/permad/entity/RigidEntity.java | [
{
"identifier": "AABoundingBox",
"path": "src/main/java/club/premiering/permad/math/AABoundingBox.java",
"snippet": "public class AABoundingBox {\n public float x, y, width, height;\n\n public AABoundingBox(Vector2 centerPos, Vector2 size) {\n this.x = centerPos.x - size.x / 2;\n this.y = centerPos.y - size.y / 2;\n this.width = size.x;\n this.height = size.y;\n }\n\n public Vector2 getCenter() {\n return new Vector2(x + width / 2, y + height / 2);\n }\n}"
},
{
"identifier": "MathUtil",
"path": "src/main/java/club/premiering/permad/math/MathUtil.java",
"snippet": "public class MathUtil {\n public static float clamp(float val, float min, float max) {\n return Math.max(min, Math.min(max, val));\n }\n}"
},
{
"identifier": "Vector2",
"path": "src/main/java/club/premiering/permad/math/Vector2.java",
"snippet": "public class Vector2 implements Cloneable {\n public float x, y;\n\n public Vector2(float x, float y) {\n this.x = x;\n this.y = y;\n }\n\n public Vector2(double x, double y) {\n this.x = (float) x;\n this.y = (float) y;\n }\n\n public Vector2() {\n this(0, 0);\n }\n\n public float dist(Vector2 point) {\n return Math.abs(this.x - point.x) + Math.abs(this.y - point.y);\n }\n\n public Vector2 distVec(Vector2 b) {\n return new Vector2(b.x - this.x, b.y - this.y);\n }\n\n public Vector2 rotate(float angle, Vector2 rotationAxis) {\n float cos = (float)Math.cos(angle);\n float sin = (float)Math.sin(angle);\n\n this.sub(rotationAxis);\n\n float newX = this.x * cos - this.y * sin;\n float newY = this.x * sin + this.y * cos;\n\n this.x = newX;\n this.y = newY;\n\n this.add(rotationAxis);\n return this;\n }\n \n public Vector2 set(float x, float y) {\n this.x = x;\n this.y = y;\n return this;\n }\n\n public Vector2 add(Vector2 vec) {\n return this.add(vec.x, vec.y);\n }\n\n public Vector2 add(float x, float y) {\n this.x += x;\n this.y += y;\n return this;\n }\n\n public Vector2 sub(Vector2 v) {\n x -= v.x;\n y -= v.y;\n return this;\n }\n\n public Vector2 sub(float x, float y) {\n this.x -= x;\n this.y -= y;\n return this;\n }\n\n public Vector2 mul(float x) {\n this.mul(x, x);\n return this;\n }\n\n public Vector2 mul(float x, float y) {\n this.x *= x;\n this.y *= y;\n return this;\n }\n\n public Vector2 divide(float x) {\n return this.divide(x, x);\n }\n\n public Vector2 divide(float x, float y) {\n this.x /= x;\n this.y /= y;\n return this;\n }\n\n public Vector2 lerpTo(Vector2 destination, float o) {\n o = MathUtil.clamp(o, 0, 1);//Pass by value with primitives, so we're fine (at least I think)\n this.x += (destination.x - this.x) * o;\n this.y += (destination.y - this.y) * o;\n return this;\n }\n\n @Override\n public String toString() {\n return \"Vector2{\" +\n \"x=\" + x +\n \", y=\" + y +\n '}';\n }\n\n @Override\n public Vector2 clone() {\n try {\n Vector2 clone = (Vector2) super.clone();\n clone.x = this.x;\n clone.y = this.y;\n return clone;\n } catch (CloneNotSupportedException e) {\n throw new AssertionError();\n }\n }\n}"
}
] | import club.premiering.permad.math.AABoundingBox;
import club.premiering.permad.math.BoundingBox;
import club.premiering.permad.math.MathUtil;
import club.premiering.permad.math.Vector2;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.Collection; | 1,310 | package club.premiering.permad.entity;
// This represents an entity which takes part in any way of physics in the game
// Currently the solution is very hacky and needs reworking, this should be a top priority.
// (Only calculates AABBs and (detection only) rotated AABBs)
public abstract class RigidEntity extends Entity {
@Getter
@Setter
private boolean active = true;
@Getter
@Setter
private boolean solid = false;//If other rigids touch us, do we stop them?
@Getter
@Setter
private boolean collideWithSolids = false;//If we touch other rigids, do we stop?
@Getter
@Setter
private boolean onGround = false;
@Getter
@Setter
private boolean canBeOutsideWorld = true;
@Getter
private Collection<Entity> touchingEntities = new ArrayList<>();//The entities that this entity are currently touching | package club.premiering.permad.entity;
// This represents an entity which takes part in any way of physics in the game
// Currently the solution is very hacky and needs reworking, this should be a top priority.
// (Only calculates AABBs and (detection only) rotated AABBs)
public abstract class RigidEntity extends Entity {
@Getter
@Setter
private boolean active = true;
@Getter
@Setter
private boolean solid = false;//If other rigids touch us, do we stop them?
@Getter
@Setter
private boolean collideWithSolids = false;//If we touch other rigids, do we stop?
@Getter
@Setter
private boolean onGround = false;
@Getter
@Setter
private boolean canBeOutsideWorld = true;
@Getter
private Collection<Entity> touchingEntities = new ArrayList<>();//The entities that this entity are currently touching | protected Collection<AABoundingBox> aabbs = new ArrayList<>(); | 0 | 2023-12-20 03:13:05+00:00 | 2k |
VRavindu/layered-architecture-Vimukthi-Ravindu | src/main/java/com/example/layeredarchitecture/dao/custom/impl/OrderDAOimpl.java | [
{
"identifier": "SQLUtil",
"path": "src/main/java/com/example/layeredarchitecture/dao/SQLUtil.java",
"snippet": "public class SQLUtil {\n\n public static <T> T exucute(String sql, Object... args) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(sql);\n\n for (int i = 0; i< args.length; i++){\n pstm.setObject(i+1,args[i]);\n }\n if(sql.startsWith(\"SELECT\")){\n return (T) pstm.executeQuery();\n }else {\n return (T)(Boolean)(pstm.executeUpdate() > 0);\n }\n }\n}"
},
{
"identifier": "OrderDAO",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/OrderDAO.java",
"snippet": "public interface OrderDAO extends CrudDAO<OrderDTO> {\n boolean saveOrder(String orderId, LocalDate orderDate, String customerId) throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "DBConnection",
"path": "src/main/java/com/example/layeredarchitecture/db/DBConnection.java",
"snippet": "public class DBConnection {\n private static DBConnection dbConnection;\n private final Connection connection;\n\n private DBConnection() throws ClassNotFoundException, SQLException {\n Class.forName(\"com.mysql.cj.jdbc.Driver\");\n connection = DriverManager.getConnection(\"jdbc:mysql://localhost:3306/company\", \"root\", \"Rv@1234\");\n }\n\n public static DBConnection getDbConnection() throws SQLException, ClassNotFoundException {\n return dbConnection == null ? dbConnection= new DBConnection() : dbConnection;\n }\n\n public Connection getConnection() {\n return connection;\n }\n}"
},
{
"identifier": "OrderDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/OrderDTO.java",
"snippet": "public class OrderDTO {\n private String orderId;\n private LocalDate orderDate;\n private String customerId;\n private String customerName;\n private BigDecimal orderTotal;\n\n public OrderDTO() {\n }\n\n public OrderDTO(String orderId, LocalDate orderDate, String customerId, String customerName, BigDecimal orderTotal) {\n this.orderId = orderId;\n this.orderDate = orderDate;\n this.customerId = customerId;\n this.customerName = customerName;\n this.orderTotal = orderTotal;\n }\n\n public OrderDTO(String orderId, LocalDate orderDate, String customerId) {\n this.orderId = orderId;\n this.orderDate = orderDate;\n this.customerId = customerId;\n }\n\n public String getOrderId() {\n return orderId;\n }\n\n public void setOrderId(String orderId) {\n this.orderId = orderId;\n }\n\n public LocalDate getOrderDate() {\n return orderDate;\n }\n\n public void setOrderDate(LocalDate orderDate) {\n this.orderDate = orderDate;\n }\n\n public String getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(String customerId) {\n this.customerId = customerId;\n }\n\n public String getCustomerName() {\n return customerName;\n }\n\n public void setCustomerName(String customerName) {\n this.customerName = customerName;\n }\n\n public BigDecimal getOrderTotal() {\n return orderTotal;\n }\n\n public void setOrderTotal(BigDecimal orderTotal) {\n this.orderTotal = orderTotal;\n }\n\n @Override\n public String toString() {\n return \"OrderDTO{\" +\n \"orderId='\" + orderId + '\\'' +\n \", orderDate=\" + orderDate +\n \", customerId='\" + customerId + '\\'' +\n \", customerName='\" + customerName + '\\'' +\n \", orderTotal=\" + orderTotal +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.dao.SQLUtil;
import com.example.layeredarchitecture.dao.custom.OrderDAO;
import com.example.layeredarchitecture.db.DBConnection;
import com.example.layeredarchitecture.model.OrderDTO;
import java.sql.*;
import java.time.LocalDate;
import java.util.ArrayList; | 1,144 | package com.example.layeredarchitecture.dao.custom.impl;
public class OrderDAOimpl implements OrderDAO {
@Override
public String generateNewId() throws SQLException, ClassNotFoundException {
ResultSet rst = SQLUtil.exucute("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;");
return rst.next() ? String.format("OID-%03d", (Integer.parseInt(rst.getString("oid").replace("OID-", "")) + 1)) : "OID-001";
}
@Override
public boolean exist(String orderId) throws SQLException, ClassNotFoundException {
return SQLUtil.exucute("SELECT oid FROM `Orders` WHERE oid=?", orderId);
}
public boolean saveOrder(String orderId, LocalDate orderDate, String customerId) throws SQLException, ClassNotFoundException {
return SQLUtil.exucute("INSERT INTO `orders` (oid, date, customerID) VALUES (?,?,?)",orderId,orderDate,customerId);
}
@Override
public boolean delete(String id) throws SQLException, ClassNotFoundException {
return false;
}
@Override | package com.example.layeredarchitecture.dao.custom.impl;
public class OrderDAOimpl implements OrderDAO {
@Override
public String generateNewId() throws SQLException, ClassNotFoundException {
ResultSet rst = SQLUtil.exucute("SELECT oid FROM `Orders` ORDER BY oid DESC LIMIT 1;");
return rst.next() ? String.format("OID-%03d", (Integer.parseInt(rst.getString("oid").replace("OID-", "")) + 1)) : "OID-001";
}
@Override
public boolean exist(String orderId) throws SQLException, ClassNotFoundException {
return SQLUtil.exucute("SELECT oid FROM `Orders` WHERE oid=?", orderId);
}
public boolean saveOrder(String orderId, LocalDate orderDate, String customerId) throws SQLException, ClassNotFoundException {
return SQLUtil.exucute("INSERT INTO `orders` (oid, date, customerID) VALUES (?,?,?)",orderId,orderDate,customerId);
}
@Override
public boolean delete(String id) throws SQLException, ClassNotFoundException {
return false;
}
@Override | public OrderDTO search(String id) throws SQLException, ClassNotFoundException { | 3 | 2023-12-16 04:19:18+00:00 | 2k |
egisac/ethicalvoting | src/main/java/net/egis/ethicalvoting/integrations/EthicalPAPI.java | [
{
"identifier": "EthicalVoting",
"path": "src/main/java/net/egis/ethicalvoting/EthicalVoting.java",
"snippet": "@Getter\npublic final class EthicalVoting extends JavaPlugin {\n\n @Getter\n private static EthicalVoting self;\n\n private StorageInterface storage;\n private ProfileManager profiles;\n private PlayerConnectionListener connectionListener;\n private VotifierVoteListener voteListener;\n private FireworkDamageListener fireworkDamageListener;\n private VotePartyHandler votePartyHandler;\n private VoteRewardHandler voteRewardHandler;\n\n @Override\n public void onEnable() {\n self = this;\n\n new InventoryAPI(this).init();\n\n saveDefaultConfig();\n pickStorageType();\n loadPluginData();\n loadFeatures();\n registerEventListeners();\n registerCommands();\n registerIntegrations();\n\n getLogger().info(\"Storage Type: \" + storage.getAdapterType());\n checkUpdates();\n\n getLogger().info(\"EthicalVoting has been successfully enabled.\");\n }\n\n @Override\n public void onDisable() {\n profiles.shutdown();\n voteRewardHandler.getVoteQueue().shutdown();\n\n getLogger().info(\"EthicalVoting has been successfully disabled.\");\n }\n\n public void registerIntegrations() {\n if (getServer().getPluginManager().getPlugin(\"PlaceholderAPI\") != null) {\n new EthicalPAPI().register();\n getLogger().info(\"PlaceholderAPI integration has been successfully enabled.\");\n } else {\n getLogger().warning(\"PlaceholderAPI integration has failed to load.\");\n }\n }\n\n /*\n Defines which database type will be used to store user data.\n Current options:\n - MySQL\n - YAML (Bukkit internal)\n */\n public void pickStorageType() {\n String storageInterface = getConfig().getString(\"database.type\");\n\n if (storageInterface == null) {\n getLogger().severe(\"Storage Interface is null. Report this to plugin developer.\");\n getServer().shutdown();\n return;\n }\n\n if (storageInterface.equalsIgnoreCase(\"mysql\")) {\n storage = new MySQLInterface();\n\n String host = getConfig().getString(\"database.host\");\n int port = getConfig().getInt(\"database.port\");\n String database = getConfig().getString(\"database.database\");\n String username = getConfig().getString(\"database.username\");\n String password = getConfig().getString(\"database.password\");\n\n if (host == null || database == null || username == null || password == null) {\n getLogger().severe(\"MySQL credentials are null. Report this to plugin developer.\");\n getServer().shutdown();\n return;\n }\n\n if (!storage.jdbcInit(\"jdbc:mysql://\" + host + \":\" + port + \"/\" + database, username, password)) {\n getLogger().severe(\"Failed to connect to MySQL database. Report this to plugin developer.\");\n getServer().shutdown();\n return;\n }\n } else {\n storage = new YamlInterface(this);\n }\n }\n\n public void registerCommands() {\n EthicalVotingCommand ethicalVotingCommand = new EthicalVotingCommand();\n getCommand(\"ethicalvoting\").setExecutor(ethicalVotingCommand);\n getCommand(\"ethicalvoting\").setTabCompleter(ethicalVotingCommand);\n VoteCommand voteCommand = new VoteCommand();\n getCommand(\"vote\").setExecutor(voteCommand);\n getCommand(\"vote\").setTabCompleter(voteCommand);\n }\n\n public void loadPluginData() {\n this.profiles = new ProfileManager(storage);\n }\n\n public void registerEventListeners() {\n this.connectionListener = new PlayerConnectionListener(this);\n this.voteListener = new VotifierVoteListener(this);\n this.fireworkDamageListener = new FireworkDamageListener();\n getServer().getPluginManager().registerEvents(connectionListener, this);\n getServer().getPluginManager().registerEvents(voteListener, this);\n getServer().getPluginManager().registerEvents(fireworkDamageListener, this);\n }\n\n public void loadFeatures() {\n votePartyHandler = new VotePartyHandler(this);\n voteRewardHandler = new VoteRewardHandler(this);\n }\n\n public void checkUpdates() {\n new UpdateChecker(this, 12345).getVersion(version -> {\n if (!this.getDescription().getVersion().equals(version)) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (player.isOp()) {\n String prefix = getConfig().getString(\"messages.prefix\");\n player.sendMessage(Translate.translate(prefix + \"&7There is a new &aupdate &7available &fhttps://www.spigot.org/\"));\n getLogger().warning(\"There is a new update available at https://www.spigot.org/ [\" + version + \"]\");\n }\n }\n }\n });\n }\n\n}"
},
{
"identifier": "EthicalProfile",
"path": "src/main/java/net/egis/ethicalvoting/data/player/EthicalProfile.java",
"snippet": "@Getter @Setter @AllArgsConstructor\r\npublic class EthicalProfile implements Comparable<EthicalProfile> {\r\n\r\n private UUID uuid;\r\n private String lastUsername;\r\n private int votes;\r\n\r\n public void incrementVotes(int v) {\r\n votes+=v;\r\n EthicalVoting plugin = EthicalVoting.getSelf();\r\n plugin.getProfiles().saveProfile(this);\r\n }\r\n\r\n public void updateUsername(String username) {\r\n lastUsername = username;\r\n EthicalVoting plugin = EthicalVoting.getSelf();\r\n plugin.getProfiles().saveProfile(this);\r\n }\r\n\r\n @Override\r\n public int compareTo(EthicalProfile o) {\r\n return o.getVotes() - votes;\r\n }\r\n\r\n}\r"
}
] | import me.clip.placeholderapi.expansion.PlaceholderExpansion;
import net.egis.ethicalvoting.EthicalVoting;
import net.egis.ethicalvoting.data.player.EthicalProfile;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List; | 1,545 | package net.egis.ethicalvoting.integrations;
public class EthicalPAPI extends PlaceholderExpansion {
@Override
public @NotNull String getIdentifier() {
return "ethicalvoting";
}
@Override
public @NotNull String getAuthor() {
return "Egis";
}
@Override
public @NotNull String getVersion() {
return "1.0.0";
}
@Override
public @NotNull List<String> getPlaceholders() {
return List.of("votes", "vote_party");
}
@Override
public @Nullable String onPlaceholderRequest(Player player, @NotNull String params) { | package net.egis.ethicalvoting.integrations;
public class EthicalPAPI extends PlaceholderExpansion {
@Override
public @NotNull String getIdentifier() {
return "ethicalvoting";
}
@Override
public @NotNull String getAuthor() {
return "Egis";
}
@Override
public @NotNull String getVersion() {
return "1.0.0";
}
@Override
public @NotNull List<String> getPlaceholders() {
return List.of("votes", "vote_party");
}
@Override
public @Nullable String onPlaceholderRequest(Player player, @NotNull String params) { | EthicalVoting plugin = EthicalVoting.getSelf(); | 0 | 2023-12-15 16:48:38+00:00 | 2k |
stvnliu/epq-api | src/main/java/me/imsonmia/epqapi/controller/UserController.java | [
{
"identifier": "Message",
"path": "src/main/java/me/imsonmia/epqapi/model/Message.java",
"snippet": "@Entity\n@Table(name = \"message\")\npublic class Message {\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Id\n Long id;\n MessageType type;\n String fromUserId;\n String toUserId;\n String content;\n Long timeMillis;\n public Long getId() {\n return id;\n }\n public MessageType getType() {\n return type;\n }\n public String getFromUserId() {\n return fromUserId;\n }\n public String getToUserId() {\n return toUserId;\n }\n public void setFromUserId(String fromUserId) {\n this.fromUserId = fromUserId;\n }\n public void setToUserId(String toUserId) {\n this.toUserId = toUserId;\n }\n public String getContent() {\n return content;\n }\n public void setContent(String content) {\n this.content = content;\n }\n public Long getTimeMillis() {\n return timeMillis;\n }\n public void setTimeMillis(Long timeMillis) {\n this.timeMillis = timeMillis;\n }\n public void setType(MessageType type) {\n this.type = type;\n }\n public Message() {\n\n }\n public Message(Long id,\n MessageType type,\n String fromUserId,\n String toUserId,\n String content,\n Long timeMillis) {\n this.id = id;\n this.type = type;\n this.fromUserId = fromUserId;\n this.toUserId = toUserId;\n this.content = content;\n this.timeMillis = timeMillis;\n }\n}"
},
{
"identifier": "User",
"path": "src/main/java/me/imsonmia/epqapi/model/User.java",
"snippet": "@Entity\n@Table(name = \"user\")\npublic class User {\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Getter\n Long id;\n @Getter\n @Setter\n String userName;\n @Getter\n @Setter\n Date dateJoined;\n public User() {\n\n }\n public User(Long id, String userName, Date dateJoined) {\n this.id = id;\n this.userName = userName;\n this.dateJoined = dateJoined;\n }\n}"
},
{
"identifier": "MessageRepository",
"path": "src/main/java/me/imsonmia/epqapi/repository/MessageRepository.java",
"snippet": "public interface MessageRepository extends CrudRepository<Message, Long> {\n}"
},
{
"identifier": "UserRepository",
"path": "src/main/java/me/imsonmia/epqapi/repository/UserRepository.java",
"snippet": "public interface UserRepository extends CrudRepository<User, Long> {\n User findByUserName(String userName);\n}"
}
] | import java.time.Instant;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import me.imsonmia.epqapi.model.Message;
import me.imsonmia.epqapi.model.User;
import me.imsonmia.epqapi.repository.MessageRepository;
import me.imsonmia.epqapi.repository.UserRepository; | 798 | package me.imsonmia.epqapi.controller;
@RestController
@RequestMapping("/api/v1")
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired | package me.imsonmia.epqapi.controller;
@RestController
@RequestMapping("/api/v1")
public class UserController {
@Autowired
private UserRepository userRepository;
@Autowired | private MessageRepository messageRepository; | 2 | 2023-12-21 17:50:17+00:00 | 2k |
approachcircle/Pong | src/main/java/net/approachcircle/game/PongScreen.java | [
{
"identifier": "CollisionUtility",
"path": "src/main/java/net/approachcircle/game/backend/CollisionUtility.java",
"snippet": "public class CollisionUtility {\n public static boolean isCollidingWith(Transformable first, Transformable second) {\n return (first.getX() <= second.getX() + second.getWidth() &&\n first.getX() + first.getWidth() >= second.getX() - (second.getWidth() * 1.25f) &&\n first.getY() + (second.getHeight() / 2) <= second.getY() + second.getHeight() &&\n first.getY() + first.getHeight() >= second.getY() - (first.getHeight() / 2));\n }\n public static boolean isCollidingWith(Vector2 firstPosition, Size firstSize, Vector2 secondPosition, Size secondSize) {\n return (firstPosition.x <= secondPosition.x + secondSize.width &&\n firstPosition.x + firstSize.width >= secondPosition.x - (secondSize.width * 1.25f) &&\n firstPosition.y + (secondSize.height / 2) <= secondPosition.y + secondSize.height &&\n firstPosition.y + firstSize.height >= secondPosition.y - (firstSize.height / 2));\n }\n\n public static boolean isCollidingWithWall(Transformable object, Wall wall) {\n switch (wall) {\n case Top -> {\n return object.getY() + object.getHeight() / 2 >= Gdx.graphics.getHeight();\n }\n case Bottom -> {\n return object.getY() - object.getHeight() / 2 < 0;\n }\n case Left -> {\n return object.getX() + object.getWidth() / 2 < 0;\n }\n case Right -> {\n return object.getX() - object.getWidth() / 2 >= Gdx.graphics.getWidth();\n }\n default -> throw new EnumConstantNotPresentException(Wall.class, wall.toString());\n }\n }\n}"
},
{
"identifier": "Screen",
"path": "src/main/java/net/approachcircle/game/backend/Screen.java",
"snippet": "public abstract class Screen implements Renderable {\n @Override\n public String toString() {\n return this.getClass().getSimpleName();\n }\n public EscapeBehaviour getEscapeBehaviour() {\n return EscapeBehaviour.Other;\n }\n}"
},
{
"identifier": "ScreenStack",
"path": "src/main/java/net/approachcircle/game/backend/ScreenStack.java",
"snippet": "public class ScreenStack {\n private final Stack<Screen> stack;\n private final InputManager inputManager;\n public ScreenStack(InputManager inputManager) {\n this.inputManager = inputManager;\n stack = new Stack<>();\n }\n\n public Screen pop() {\n if (stack.isEmpty()) {\n return null;\n }\n inputManager.clearInputProcessors();\n Screen previous = stack.pop();\n String log = String.format(\"screen popped: %s -> %s\", previous, peek());\n System.out.println(log);\n return previous;\n }\n\n public void popTo(Class<? extends Screen> screen) {\n if (!containsTypeOf(screen)) {\n throw new IllegalStateException(String.format(\"screen '%s' not present in screen stack.\", screen));\n }\n while (!isSameType(peek(), screen)) {\n pop();\n }\n }\n\n public boolean containsInstanceOf(Screen screen) {\n return stack.contains(screen);\n }\n\n public boolean containsTypeOf(Class<? extends Screen> screen) {\n for (Screen s : stack) {\n // this check is naive, but should do the trick\n // provided no two screens have the same class name\n if (isSameType(s, screen)) {\n return true;\n }\n }\n return false;\n }\n\n public boolean isSameType(Screen first, Class<? extends Screen> second) {\n return first.getClass() == second;\n }\n\n public void push(Screen screen) {\n String log = String.format(\"screen pushed: %s -> %s\", peek(), screen);\n inputManager.clearInputProcessors();\n stack.push(screen);\n System.out.println(log);\n }\n\n public Screen peek() {\n if (stack.isEmpty()) {\n return null;\n }\n return stack.peek();\n }\n\n public void insert(int index, Screen screen) {\n stack.add(index, screen);\n }\n\n public boolean isEmpty() {\n return stack.isEmpty();\n }\n\n public void clear() {\n stack.clear();\n }\n}"
},
{
"identifier": "Size",
"path": "src/main/java/net/approachcircle/game/backend/Size.java",
"snippet": "public class Size {\n public float width;\n public float height;\n public Size(float width, float height) {this.width = width; this.height = height;}\n}"
}
] | import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.math.Vector2;
import net.approachcircle.game.backend.CollisionUtility;
import net.approachcircle.game.backend.Screen;
import net.approachcircle.game.backend.ScreenStack;
import net.approachcircle.game.backend.Size;
import java.util.Random; | 1,417 | package net.approachcircle.game;
public class PongScreen extends Screen {
private final Player player;
private final Opponent opponent;
private final Ball ball;
private final Score score;
private final ScreenStack screenStack;
private final Difficulty difficulty;
public PongScreen(Difficulty difficulty) {
this.screenStack = Game.getInstance().getScreenStack();
player = new Player();
// TODO: here we should pass an argument to the constructor
// TODO: of Opponent letting it know if this is a multiplayer
// TODO: game or a single-player game. exceptions should be thrown
// TODO: if methods are called in the wrong game mode context
opponent = new Opponent();
opponent.setDifficulty(difficulty);
ball = new Ball();
chooseRandomStartTrajectory();
switch (difficulty) {
case Easy -> ball.speedIncline += 0;
case Normal -> ball.speedIncline += 1;
case Hard -> ball.speedIncline += 1.25f;
case Extreme -> ball.speedIncline += 2.25f;
case Impossible -> ball.speedIncline += 4;
default -> throw new EnumConstantNotPresentException(Difficulty.class, difficulty.name());
}
this.difficulty = difficulty;
score = new Score();
}
private void handleCollisionProjection() { | package net.approachcircle.game;
public class PongScreen extends Screen {
private final Player player;
private final Opponent opponent;
private final Ball ball;
private final Score score;
private final ScreenStack screenStack;
private final Difficulty difficulty;
public PongScreen(Difficulty difficulty) {
this.screenStack = Game.getInstance().getScreenStack();
player = new Player();
// TODO: here we should pass an argument to the constructor
// TODO: of Opponent letting it know if this is a multiplayer
// TODO: game or a single-player game. exceptions should be thrown
// TODO: if methods are called in the wrong game mode context
opponent = new Opponent();
opponent.setDifficulty(difficulty);
ball = new Ball();
chooseRandomStartTrajectory();
switch (difficulty) {
case Easy -> ball.speedIncline += 0;
case Normal -> ball.speedIncline += 1;
case Hard -> ball.speedIncline += 1.25f;
case Extreme -> ball.speedIncline += 2.25f;
case Impossible -> ball.speedIncline += 4;
default -> throw new EnumConstantNotPresentException(Difficulty.class, difficulty.name());
}
this.difficulty = difficulty;
score = new Score();
}
private void handleCollisionProjection() { | if (CollisionUtility.isCollidingWith( | 0 | 2023-12-20 16:25:30+00:00 | 2k |
jollyboss123/astra | modules/app/src/main/java/com/jolly/astra/GreetingController.java | [
{
"identifier": "OAuthentication",
"path": "modules/heimdall/src/main/java/com/jolly/heimdall/OAuthentication.java",
"snippet": "public class OAuthentication<T extends Map<String, Object> & Serializable & Principal> extends AbstractAuthenticationToken implements\n OAuth2AuthenticatedPrincipal {\n @Serial\n private static final long serialVersionUID = 7566213493599769417L;\n\n /**\n * Bearer string to set as Authorization header if we ever need to call a downstream service on behalf of the same resource-owner.\n */\n private final String tokenString;\n /**\n * Claim-set associated with the access-token (attributes retrieved from the token or introspection end-point).\n */\n private final T claims;\n\n /**\n * @param claims Claim-set of any-type\n * @param authorities Granted authorities associated with this authentication instance\n * @param tokenString Original encoded Bearer string (in case resource-server needs)\n */\n public OAuthentication(T claims, Collection<? extends GrantedAuthority> authorities, String tokenString) {\n super(authorities);\n super.setAuthenticated(true);\n super.setDetails(claims);\n this.claims = claims;\n this.tokenString = Optional.ofNullable(tokenString)\n .map(t -> t.toLowerCase().startsWith(\"bearer \") ? t.substring(7) : t)\n .orElse(null);\n }\n\n @Override\n public void setAuthenticated(boolean authenticated) {\n throw new RuntimeException(\"OAuthentication authentication status is immutable\");\n }\n\n @Override\n public Object getCredentials() {\n return tokenString;\n }\n\n @Override\n public Object getPrincipal() {\n return claims;\n }\n\n @Override\n public Map<String, Object> getAttributes() {\n return claims;\n }\n\n public T getClaims() {\n return claims;\n }\n\n public String getBearerHeader() {\n if (!StringUtils.hasText(tokenString)) {\n return null;\n }\n\n return String.format(\"Bearer %s\", tokenString);\n }\n\n @Override\n public boolean equals(Object object) {\n if (this == object) return true;\n if (object == null || getClass() != object.getClass()) return false;\n if (!super.equals(object)) return false;\n OAuthentication<?> that = (OAuthentication<?>) object;\n return Objects.equals(tokenString, that.tokenString) && Objects.equals(claims, that.claims);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(super.hashCode(), tokenString, claims);\n }\n}"
},
{
"identifier": "OpenIdClaimSet",
"path": "modules/heimdall/src/main/java/com/jolly/heimdall/claimset/OpenIdClaimSet.java",
"snippet": "public class OpenIdClaimSet extends UnmodifiableClaimSet implements IdTokenClaimAccessor, Principal {\n @Serial\n private static final long serialVersionUID = 4908273025927451191L;\n\n /**\n * JSON path for the claim to use as \"name\" source\n */\n private final String usernameClaim;\n\n public OpenIdClaimSet(Map<String, Object> claims, String usernameClaim) {\n super(claims);\n this.usernameClaim = usernameClaim;\n }\n\n public OpenIdClaimSet(Map<String, Object> claims) {\n this(claims, StandardClaimNames.SUB);\n }\n\n @Override\n public String getName() {\n try {\n return getByJsonPath(usernameClaim);\n } catch (PathNotFoundException ex) {\n return getByJsonPath(JwtClaimNames.SUB);\n }\n }\n\n @Override\n public Map<String, Object> getClaims() {\n return this;\n }\n}"
}
] | import com.jolly.heimdall.OAuthentication;
import com.jolly.heimdall.claimset.OpenIdClaimSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController; | 986 | package com.jolly.astra;
@RestController
public class GreetingController {
private static final Logger log = LoggerFactory.getLogger(GreetingController.class);
@GetMapping("/greet")
@PreAuthorize("isAuthenticated()") | package com.jolly.astra;
@RestController
public class GreetingController {
private static final Logger log = LoggerFactory.getLogger(GreetingController.class);
@GetMapping("/greet")
@PreAuthorize("isAuthenticated()") | public String greet(OAuthentication<OpenIdClaimSet> auth) { | 1 | 2023-12-17 05:24:05+00:00 | 2k |
Blawuken/MicroG-Extended | play-services-basement/src/main/java/com/google/android/gms/common/GoogleCertificatesLookupQuery.java | [
{
"identifier": "AbstractSafeParcelable",
"path": "play-services-basement/src/main/java/com/google/android/gms/common/internal/safeparcel/AbstractSafeParcelable.java",
"snippet": "public abstract class AbstractSafeParcelable implements SafeParcelable {\n\n @SuppressWarnings(\"unchecked\")\n public static <T extends AbstractSafeParcelable> SafeParcelableCreatorAndWriter<T> findCreator(java.lang.Class<T> tClass) {\n String creatorClassName = tClass.getName() + \"$000Creator\";\n try {\n return (SafeParcelableCreatorAndWriter<T>) java.lang.Class.forName(creatorClassName).newInstance();\n } catch (Exception e) {\n throw new RuntimeException(\"No Creator found for \" + tClass.getName(), e);\n }\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n}"
},
{
"identifier": "SafeParcelable",
"path": "play-services-basement/src/main/java/com/google/android/gms/common/internal/safeparcel/SafeParcelable.java",
"snippet": "public interface SafeParcelable extends Parcelable {\n int SAFE_PARCEL_OBJECT_MAGIC = 0x4F45;\n\n @Target(ElementType.TYPE)\n @interface Class {\n }\n\n @Target(ElementType.CONSTRUCTOR)\n @interface Constructor {\n\n }\n\n @Target(ElementType.PARAMETER)\n @interface Param {\n int value();\n }\n\n @Retention(RetentionPolicy.RUNTIME)\n @Target(ElementType.FIELD)\n @interface Field {\n int value();\n\n boolean mayNull() default false;\n\n java.lang.Class<?> subClass() default SafeParcelable.class;\n\n boolean useValueParcel() default false;\n\n boolean useDirectList() default false;\n\n long versionCode() default -1;\n\n String defaultValue() default \"\";\n\n String type() default \"\";\n\n String getterName() default \"\";\n\n String getter() default \"\";\n }\n}"
},
{
"identifier": "SafeParcelableCreatorAndWriter",
"path": "play-services-basement/src/main/java/com/google/android/gms/common/internal/safeparcel/SafeParcelableCreatorAndWriter.java",
"snippet": "public interface SafeParcelableCreatorAndWriter<T extends SafeParcelable> extends Parcelable.Creator<T> {\n void writeToParcel(T object, Parcel parcel, int flags);\n}"
},
{
"identifier": "ObjectWrapper",
"path": "play-services-basement/src/main/java/com/google/android/gms/dynamic/ObjectWrapper.java",
"snippet": "public class ObjectWrapper<T> extends IObjectWrapper.Stub {\n private final T t;\n\n public ObjectWrapper(T t) {\n this.t = t;\n }\n\n @Nullable\n public static Object unwrap(IObjectWrapper obj) {\n if (obj == null) {\n return null;\n }\n\n if (obj instanceof ObjectWrapper) {\n return ((ObjectWrapper) obj).t;\n }\n\n IBinder binder = obj.asBinder();\n Field[] fields = binder.getClass().getDeclaredFields();\n\n if (fields.length < 1) {\n throw new IllegalArgumentException(\"No fields were found\");\n }\n\n // Ignore synthetic field(s) from JaCoCo or elsewhere\n // https://www.jacoco.org/jacoco/trunk/doc/faq.html\n\n @Nullable\n Field field = null;\n\n for (Field currentField : fields) {\n if (currentField.isSynthetic()) {\n continue;\n }\n\n if (field == null) {\n field = currentField;\n } else {\n throw new IllegalArgumentException(\"Too many non-synthetic fields were found\");\n }\n }\n\n if (field == null) {\n throw new IllegalArgumentException(\"No non-synthetic fields were found\");\n }\n\n if (!field.isAccessible()) {\n field.setAccessible(true);\n try {\n return field.get(binder);\n } catch (NullPointerException localNullPointerException) {\n throw new IllegalArgumentException(\"Binder object is null.\",\n localNullPointerException);\n } catch (IllegalArgumentException localIllegalArgumentException) {\n throw new IllegalArgumentException(\"remoteBinder is the wrong class.\",\n localIllegalArgumentException);\n } catch (IllegalAccessException localIllegalAccessException) {\n throw new IllegalArgumentException(\"Could not access the field in remoteBinder.\",\n localIllegalAccessException);\n }\n } else {\n throw new IllegalArgumentException();\n }\n }\n\n @Nullable\n public static <T> T unwrapTyped(IObjectWrapper obj, Class<T> clazz) {\n try {\n return clazz.cast(unwrap(obj));\n } catch (ClassCastException e) {\n return null;\n }\n }\n\n public static <T> ObjectWrapper<T> wrap(T t) {\n return new ObjectWrapper<T>(t);\n }\n}"
}
] | import android.content.Context;
import android.os.Parcel;
import androidx.annotation.NonNull;
import com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import com.google.android.gms.common.internal.safeparcel.SafeParcelableCreatorAndWriter;
import com.google.android.gms.dynamic.IObjectWrapper;
import com.google.android.gms.dynamic.ObjectWrapper; | 1,392 | /*
* SPDX-FileCopyrightText: 2023 microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package com.google.android.gms.common;
@SafeParcelable.Class
public class GoogleCertificatesLookupQuery extends AbstractSafeParcelable {
@Field(value = 1, getterName = "getCallingPackage")
String callingPackage;
@Field(2)
boolean allowTestKeys;
@Field(3)
boolean ignoreTestKeysOverride;
@Field(4)
IObjectWrapper contextWrapper;
private Context context;
@Field(5)
boolean isChimeraPackage;
@Field(6)
boolean includeHashesInErrorMessage;
public String getCallingPackage() {
return callingPackage;
}
public Context getContext() {
if (context == null && contextWrapper != null) {
context = ObjectWrapper.unwrapTyped(contextWrapper, Context.class);
}
return context;
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
CREATOR.writeToParcel(this, dest, flags);
}
| /*
* SPDX-FileCopyrightText: 2023 microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package com.google.android.gms.common;
@SafeParcelable.Class
public class GoogleCertificatesLookupQuery extends AbstractSafeParcelable {
@Field(value = 1, getterName = "getCallingPackage")
String callingPackage;
@Field(2)
boolean allowTestKeys;
@Field(3)
boolean ignoreTestKeysOverride;
@Field(4)
IObjectWrapper contextWrapper;
private Context context;
@Field(5)
boolean isChimeraPackage;
@Field(6)
boolean includeHashesInErrorMessage;
public String getCallingPackage() {
return callingPackage;
}
public Context getContext() {
if (context == null && contextWrapper != null) {
context = ObjectWrapper.unwrapTyped(contextWrapper, Context.class);
}
return context;
}
@Override
public void writeToParcel(@NonNull Parcel dest, int flags) {
CREATOR.writeToParcel(this, dest, flags);
}
| public static final SafeParcelableCreatorAndWriter<GoogleCertificatesLookupQuery> CREATOR = findCreator(GoogleCertificatesLookupQuery.class); | 2 | 2023-12-17 16:14:53+00:00 | 2k |
DreaMagici4n/pagination | src/pagination/Controller/Pagination.java | [
{
"identifier": "FIFO",
"path": "src/pagination/Controller/algoritimosSubstituicao/FIFO.java",
"snippet": "public class FIFO extends Base{\n /**\n * Algoritimo de Substituicao FIFO(First In, First Out)\n *\n * @param sequencia sequecia de acessos a paginas na memoria\n * @param pages paginas a serem carregadas na memoria\n * @param ram memoria a ser carregada\n */\n public FIFO(List<Integer> sequencia, List<Page> pages, Ram ram) {\n super(sequencia, pages, ram);\n \n this.init();\n }\n \n @Override\n protected void change(int id) {\n int olderPosition = ram.getOlderPosition();\n\n this.removeMessage(this.molduras.get(olderPosition).getId());\n\n for (Page page : this.pages) {\n if (page.getId() == id) {\n this.faltas++;\n page.getAccess();\n page.setIdade(System.nanoTime());\n this.molduras.set(olderPosition, page);\n\n this.addMessage(page.getId());\n break;\n }\n }\n ram.setMolduras(this.molduras);\n\n }\n}"
},
{
"identifier": "Otimo",
"path": "src/pagination/Controller/algoritimosSubstituicao/Otimo.java",
"snippet": "public class Otimo extends Base {\n private List<Integer> distanceToAcess;\n\n /**\n * Algoritimo de Substituicao OPT(Otimo)\n *\n * @param sequencia sequecia de acessos a paginas na memoria\n * @param pages paginas a serem carregadas na memoria\n * @param ram memoria a ser carregada\n */\n public Otimo(List<Integer> sequencia, List<Page> pages, Ram ram) {\n super(sequencia, pages, ram);\n \n this.init();\n \n this.distanceToAcess = new ArrayList<>(sequencia);\n }\n \n @Override\n protected boolean check(int id) {\n if(!this.distanceToAcess.isEmpty()) {\n this.distanceToAcess.remove(0);\n }\n \n for (int i = 0; i < this.ram.getTamanhoMoldura(); i++) {\n Page page = this.molduras.get(i);\n\n if (page.getId() == id) {\n this.containMessage(id);\n page.getAccess();\n return true;\n }\n }\n this.notContainMessage(id);\n\n \n return false;\n }\n\n @Override\n protected void change(int id) {\n int maisTempoSemAcesso = this.ram.getMaisTempoSemAcesso(this.distanceToAcess);\n\n this.removeMessage(this.molduras.get(maisTempoSemAcesso).getId());\n\n for (Page page : this.pages) {\n if (page.getId() == id) {\n this.faltas++;\n page.getAccess();\n page.setIdade(System.nanoTime());\n this.molduras.set(maisTempoSemAcesso, page);\n this.addMessage(page.getId()); \n break;\n }\n }\n this.ram.setMolduras(this.molduras);\n }\n}"
},
{
"identifier": "LRU",
"path": "src/pagination/Controller/algoritimosSubstituicao/LRU.java",
"snippet": "public class LRU extends Base {\n /**\n * Algoritimo de Substituicao LRU(Least Recently Used)\n *\n * @param sequencia sequecia de acessos a paginas na memoria\n * @param pages paginas a serem carregadas na memoria\n * @param ram memoria a ser carregada\n */\n public LRU(List<Integer> sequencia, List<Page> pages, Ram ram) {\n super(sequencia, pages, ram);\n\n this.init();\n }\n\n @Override\n protected void change(int id) {\n int leastAcessed = this.ram.leastAcessed();\n\n this.removeMessage(this.molduras.get(leastAcessed).getId());\n\n for (Page page : this.pages) {\n if (page.getId() == id) {\n this.faltas++;\n page.getAccess();\n page.setIdade(System.nanoTime());\n this.molduras.set(leastAcessed, page);\n this.addMessage(page.getId());\n break;\n }\n }\n ram.setMolduras(this.molduras);\n }\n}"
}
] | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import pagination.Controller.algoritimosSubstituicao.FIFO;
import pagination.Controller.algoritimosSubstituicao.Otimo;
import pagination.Controller.algoritimosSubstituicao.LRU; | 1,235 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package pagination.Controller;
/**
*
* @author lucas
*/
public class Pagination {
private static Scanner input;
private static List<Page> pages;
private static Ram ram;
private static CadeiaReferencia referencia;
private static FIFO fifo;
private static Otimo otimo; | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package pagination.Controller;
/**
*
* @author lucas
*/
public class Pagination {
private static Scanner input;
private static List<Page> pages;
private static Ram ram;
private static CadeiaReferencia referencia;
private static FIFO fifo;
private static Otimo otimo; | private static LRU lru; | 2 | 2023-12-15 21:30:11+00:00 | 2k |
Dhananjay-mygithubcode/CRM-PROJECT | src/main/java/com/inn/cafe/restImpl/UserRestImpl.java | [
{
"identifier": "CafeConstants",
"path": "src/main/java/com/inn/cafe/constents/CafeConstants.java",
"snippet": "public class CafeConstants {\n public static final String SOMETHING_WENT_WRONG = \"Something Went Wrong.\";\n\n public static final String INVALID_INFO = \"Invalid Data.\";\n\n public static final String UNAUTHORIZED_ACCESS = \"unauthorized access.\";\n public static final String INVALID_DATA = \"Invalid Data.\";\n public static final String STORE_LOCATION = \"E:\\\\Cafe System\\\\com.inn.cafe\\\\CafeStoredFiles\";\n\n}"
},
{
"identifier": "UserRest",
"path": "src/main/java/com/inn/cafe/rest/UserRest.java",
"snippet": "@RequestMapping(path = \"/user\")\npublic interface UserRest {\n @PostMapping(path = \"/signup\")\n public ResponseEntity<String> signUp(@RequestBody(required = true) Map<String, String> requestMap);\n\n @PostMapping(path = \"/login\")\n public ResponseEntity<String> login(@RequestBody(required = true) Map<String, String> requestMap);\n\n @GetMapping(path = \"/get\")\n public ResponseEntity<List<UserWrapper>> getAllUser();\n\n @PostMapping(path = \"/update\")\n public ResponseEntity<String> update(@RequestBody(required = true) Map<String, String> requestMap);\n\n @GetMapping(path = \"/checkToken\")\n public ResponseEntity<String> checkToken();\n\n @PostMapping(path = \"/changePassword\")\n public ResponseEntity<String> changePassword(@RequestBody Map<String, String> requestMap);\n\n @PostMapping(path = \"/forgotPassword\")\n public ResponseEntity<String> forgetPassword(@RequestBody Map<String, String> requestMap);\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/com/inn/cafe/service/UserService.java",
"snippet": "public interface UserService {\n ResponseEntity<String> signUp(Map<String,String> requestMap);\n\n ResponseEntity<String> login(Map<String, String> requestMap);\n\n ResponseEntity<List<UserWrapper>> getAllUser();\n\n ResponseEntity<String> update(Map<String, String> requestMap);\n\n ResponseEntity<String> checkToken();\n\n ResponseEntity<String> changePassword(Map<String, String> requestMap);\n\n ResponseEntity<String> forgetPassword(Map<String, String> requestMap);\n}"
},
{
"identifier": "CafeUtils",
"path": "src/main/java/com/inn/cafe/utils/CafeUtils.java",
"snippet": "@Slf4j\npublic class CafeUtils {\n public CafeUtils(){\n\n }\n public static ResponseEntity<String> getResponeEntity(String responseMessage , HttpStatus httpStatus){\n return new ResponseEntity<String>(\"{\\\"messag\\\":\\\"\"+responseMessage+\"\\\"}\", httpStatus);\n }\n\n public static String getUUID(){\n Date data = new Date();\n long time = data.getTime();\n return \"BILL\" + time;\n }\n public static JSONArray getJsonArrayFromString(String data) throws JSONException {\n JSONArray jsonArray = new JSONArray(data);\n return jsonArray;\n }\n\n public static Map<String , Object> getMapFromJson(String data){\n if(!Strings.isNullOrEmpty(data))\n return new Gson().fromJson(data , new TypeToken<Map<String , Object>>(){\n }.getType());\n return new HashMap<>();\n }\n\n public static Boolean isFileExist(String path){\n// log.info(\"Inside isFileExist {}\" , path);\n try {\n File file = new File(path);\n return (file != null && file.exists()) ? Boolean.TRUE : Boolean.FALSE;\n\n }catch (Exception ex){\n ex.printStackTrace();\n }\n return false;\n }\n\n}"
},
{
"identifier": "UserWrapper",
"path": "src/main/java/com/inn/cafe/wrapper/UserWrapper.java",
"snippet": "@Data\n@NoArgsConstructor\npublic class UserWrapper {\n private Integer id;\n private String name;\n private String email;\n private String contactNumber;\n private String status;\n\n public UserWrapper(Integer id, String name, String email, String contactNumber, String status) {\n this.id = id;\n this.name = name;\n this.email = email;\n this.contactNumber = contactNumber;\n this.status = status;\n }\n}"
}
] | import com.inn.cafe.constents.CafeConstants;
import com.inn.cafe.rest.UserRest;
import com.inn.cafe.service.UserService;
import com.inn.cafe.utils.CafeUtils;
import com.inn.cafe.wrapper.UserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | 1,107 | package com.inn.cafe.restImpl;
@RestController
public class UserRestImpl implements UserRest {
@Autowired
UserService userService;
@Override
public ResponseEntity<String> signUp(Map<String, String> requestMap) {
try {
//System.out.println("inside userRestImpl");
return userService.signUp(requestMap);
} catch (Exception ex) {
ex.printStackTrace();
}
//System.out.println("Before return"); | package com.inn.cafe.restImpl;
@RestController
public class UserRestImpl implements UserRest {
@Autowired
UserService userService;
@Override
public ResponseEntity<String> signUp(Map<String, String> requestMap) {
try {
//System.out.println("inside userRestImpl");
return userService.signUp(requestMap);
} catch (Exception ex) {
ex.printStackTrace();
}
//System.out.println("Before return"); | return CafeUtils.getResponeEntity(CafeConstants.SOMETHING_WENT_WRONG, HttpStatus.INTERNAL_SERVER_ERROR); | 3 | 2023-12-20 11:47:58+00:00 | 2k |
hoangtien2k3qx1/microservice-webflux | accountservice/src/main/java/com/hoangtien2k3/event/EventConsumer.java | [
{
"identifier": "AccountDTO",
"path": "accountservice/src/main/java/com/hoangtien2k3/model/AccountDTO.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Builder\npublic class AccountDTO {\n private String id;\n private String email;\n private String currency;\n private double balance;\n private double reserved;\n\n public static AccountDTO entityToModel(Account account){\n return AccountDTO.builder()\n .email(account.getEmail())\n .currency(account.getCurrency())\n .balance(account.getBalance())\n .reserved(account.getReserved())\n .id(account.getId())\n .build();\n }\n\n public static Account dtoToEntity(AccountDTO accountDTO){\n Account account = new Account();\n account.setId(accountDTO.getId());\n account.setReserved(accountDTO.getReserved());\n account.setBalance(accountDTO.getBalance());\n account.setCurrency(accountDTO.getCurrency());\n account.setEmail(accountDTO.getEmail());\n return account;\n }\n}"
},
{
"identifier": "ProfileDTO",
"path": "commonservcie/src/main/java/com/hoangtien2k3/model/ProfileDTO.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class ProfileDTO {\n private long id;\n private String email;\n private String status;\n private double initialBalance;\n private String name;\n private String role;\n}"
},
{
"identifier": "AccountService",
"path": "accountservice/src/main/java/com/hoangtien2k3/service/AccountService.java",
"snippet": "@Service\n@Slf4j\npublic class AccountService {\n\n @Autowired\n AccountRepository accountRepository;\n\n public Mono<AccountDTO> createNewAccount(AccountDTO accountDTO){\n return Mono.just(accountDTO)\n .map(AccountDTO::dtoToEntity)\n .flatMap(account -> accountRepository.save(account))\n .map(AccountDTO::entityToModel)\n .doOnError(throwable ->\n log.error(throwable.getMessage())\n );\n }\n\n public Mono<AccountDTO> checkBalance(String id){\n return findById(id);\n }\n\n public Mono<AccountDTO> findById(String id){\n return accountRepository.findById(id)\n .map(AccountDTO::entityToModel)\n .switchIfEmpty(\n Mono.error(\n new CommonException(\"A01\", \"Account not found\", HttpStatus.NOT_FOUND))\n );\n }\n\n}"
},
{
"identifier": "Constants",
"path": "commonservcie/src/main/java/com/hoangtien2k3/utils/Constants.java",
"snippet": "public class Constants {\n public static final String PROFILE_ONBOARDING_TOPIC = \"profileOnboarding\";\n public static final String PROFILE_ONBOARDED_TOPIC = \"profileOnboarded\";\n\n public static final String STATUS_PROFILE_PENDING = \"PENDING\";\n public static final String STATUS_PROFILE_ACTIVE = \"ACTIVE\";\n\n public static final String STATUS_PAYMENT_CREATING = \"CREATING\";\n public static final String STATUS_PAYMENT_REJECTED = \"REJECTED\";\n public static final String STATUS_PAYMENT_PROCESSING = \"PROCESSING\";\n public static final String STATUS_PAYMENT_SUCCESSFUL = \"SUCCESSFUL\";\n\n public static final String PAYMENT_REQUEST_TOPIC = \"paymentRequest\";\n public static final String PAYMENT_CREATED_TOPIC = \"paymentCreated\";\n public static final String PAYMENT_COMPLETED_TOPIC = \"paymentCompleted\";\n}"
}
] | import com.google.gson.Gson;
import com.hoangtien2k3.model.AccountDTO;
import com.hoangtien2k3.model.ProfileDTO;
import com.hoangtien2k3.service.AccountService;
import com.hoangtien2k3.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.kafka.receiver.KafkaReceiver;
import reactor.kafka.receiver.ReceiverOptions;
import reactor.kafka.receiver.ReceiverRecord;
import java.util.Collections; | 946 | package com.hoangtien2k3.event;
@Service
@Slf4j
public class EventConsumer {
Gson gson = new Gson(); // convert Json -> DTO
@Autowired
AccountService accountService;
@Autowired
EventProducer eventProducer;
public EventConsumer(ReceiverOptions<String,String> receiverOptions){ | package com.hoangtien2k3.event;
@Service
@Slf4j
public class EventConsumer {
Gson gson = new Gson(); // convert Json -> DTO
@Autowired
AccountService accountService;
@Autowired
EventProducer eventProducer;
public EventConsumer(ReceiverOptions<String,String> receiverOptions){ | KafkaReceiver.create(receiverOptions.subscription(Collections.singleton(Constants.PROFILE_ONBOARDING_TOPIC))) | 3 | 2023-12-18 10:04:27+00:00 | 2k |
TheEpicBlock/FLUIwID | src/main/java/nl/theepicblock/fluiwid/mixin/Invulnerability.java | [
{
"identifier": "Fluiwid",
"path": "src/main/java/nl/theepicblock/fluiwid/Fluiwid.java",
"snippet": "public class Fluiwid implements ModInitializer {\n\tprivate static final String MOD_ID = \"fluiwid\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n\tpublic static final StatusEffect WATER_EFFECT = Registry.register(Registries.STATUS_EFFECT, id(\"water\"), new WaterStatusEffect(StatusEffectCategory.BENEFICIAL, 0x9654f9));\n\tpublic static final Potion WATER_POTION = Registry.register(Registries.POTION, id(\"fluiwid\"), new Potion(new StatusEffectInstance(WATER_EFFECT, 3600, 0, false, false, true)));\n\tpublic static final Potion LONG_WATER_POTION = Registry.register(Registries.POTION, id(\"long_fluiwid\"), new Potion(\"fluiwid\", new StatusEffectInstance(WATER_EFFECT, 9600*2, 0, false, false, true)));\n\tpublic static final TagKey<DamageType> FLUID_INVULNERABLE = TagKey.of(RegistryKeys.DAMAGE_TYPE, id(\"invulnerabilities\"));\n\n\t@Override\n\tpublic void onInitialize() {\n\t\tBrewingRecipeRegistry.registerPotionRecipe(Potions.AWKWARD, Items.WATER_BUCKET, WATER_POTION);\n\t\tBrewingRecipeRegistry.registerPotionRecipe(WATER_POTION, Items.GUNPOWDER, LONG_WATER_POTION);\n\n\t\tServerPlayNetworking.registerGlobalReceiver(UpdateC2SDataPacket.TYPE, (packet, player, responseSender) -> {\n\t\t\tvar data = ((PlayerDuck)player).fluiwid$getData();\n\t\t\tif (data != null) {\n\t\t\t\tpacket.apply(data);\n\n\t\t\t\tvar sendThrough = new UpdateS2CDataPacket(player.getId(), packet.offsets());\n\t\t\t\tPlayerLookup.tracking(player).forEach(p -> {\n\t\t\t\t\tif (p != player) {\n\t\t\t\t\t\tServerPlayNetworking.send(p, sendThrough);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\n\tpublic static Identifier id(String path) {\n\t\treturn new Identifier(MOD_ID, path);\n\t}\n}"
},
{
"identifier": "PlayerDuck",
"path": "src/main/java/nl/theepicblock/fluiwid/PlayerDuck.java",
"snippet": "public interface PlayerDuck {\n @Nullable FishyBusiness fluiwid$getData();\n}"
}
] | import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.player.PlayerEntity;
import nl.theepicblock.fluiwid.Fluiwid;
import nl.theepicblock.fluiwid.PlayerDuck;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; | 720 | package nl.theepicblock.fluiwid.mixin;
@Mixin(PlayerEntity.class)
public class Invulnerability {
@Inject(method = "isInvulnerableTo", at = @At("HEAD"), cancellable = true)
private void fluidInvulnerability(DamageSource damageSource, CallbackInfoReturnable<Boolean> cir) {
if (this instanceof PlayerDuck quack && quack.fluiwid$getData() != null) { | package nl.theepicblock.fluiwid.mixin;
@Mixin(PlayerEntity.class)
public class Invulnerability {
@Inject(method = "isInvulnerableTo", at = @At("HEAD"), cancellable = true)
private void fluidInvulnerability(DamageSource damageSource, CallbackInfoReturnable<Boolean> cir) {
if (this instanceof PlayerDuck quack && quack.fluiwid$getData() != null) { | if (damageSource.isIn(Fluiwid.FLUID_INVULNERABLE)) { | 0 | 2023-12-18 12:05:13+00:00 | 2k |
lilo-afk/TasksManager | src/main/java/br/com/fateccarapicuiba/taskmanagement/controllers/TaskController.java | [
{
"identifier": "TaskRepository",
"path": "src/main/java/br/com/fateccarapicuiba/taskmanagement/irepository/TaskRepository.java",
"snippet": "@Repository\npublic interface TaskRepository extends JpaRepository<TaskModel, Integer> {\n\n}"
},
{
"identifier": "PriorityTaskEnum",
"path": "src/main/java/br/com/fateccarapicuiba/taskmanagement/models/PriorityTaskEnum.java",
"snippet": "public enum PriorityTaskEnum {\n BAIXA(2, \"Baixa\"),\n MEDIA(3, \"Média\"),\n ALTA(4, \"Alta\");\n\n private final int value;\n private final String displayName;\n\n PriorityTaskEnum(int value, String displayName) {\n this.value = value;\n this.displayName = displayName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public int getValue() {\n return value;\n }\n}"
},
{
"identifier": "StatusTaskEnum",
"path": "src/main/java/br/com/fateccarapicuiba/taskmanagement/models/StatusTaskEnum.java",
"snippet": "public enum StatusTaskEnum {\n A_FAZER(2, \"A fazer\"),\n FAZENDO(3, \"Fazendo\"),\n CONCLUIDA(4, \"Concluída\");\n\n private final int value;\n private final String displayName;\n\n StatusTaskEnum(int value, String displayName) {\n this.value = value;\n this.displayName = displayName;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public int getValue() {\n return value;\n }\n}"
},
{
"identifier": "TaskModel",
"path": "src/main/java/br/com/fateccarapicuiba/taskmanagement/models/TaskModel.java",
"snippet": "@Data\n@Entity(name = \"tb_tasks\")\npublic class TaskModel implements Serializable {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private int id;\n private String name;\n\n @Column(length = 45)\n private String task;\n\n @Enumerated(EnumType.STRING)\n private StatusTaskEnum status;\n\n @Enumerated(EnumType.STRING)\n private PriorityTaskEnum priority;\n\n private LocalDate dueDate;\n}"
}
] | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import br.com.fateccarapicuiba.taskmanagement.irepository.TaskRepository;
import br.com.fateccarapicuiba.taskmanagement.models.PriorityTaskEnum;
import br.com.fateccarapicuiba.taskmanagement.models.StatusTaskEnum;
import br.com.fateccarapicuiba.taskmanagement.models.TaskModel; | 675 | package br.com.fateccarapicuiba.taskmanagement.controllers;
@RestController
public class TaskController {
@Autowired | package br.com.fateccarapicuiba.taskmanagement.controllers;
@RestController
public class TaskController {
@Autowired | TaskRepository taskRepository; | 0 | 2023-12-18 01:10:40+00:00 | 2k |
Frig00/Progetto-Ing-Software | src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/service/CalendarDatesService.java | [
{
"identifier": "CalendarDatesDao",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/dao/CalendarDatesDao.java",
"snippet": "public class CalendarDatesDao implements ICalendarDatesDao {\n /**\n * Connessione al database mediante il framework di Hibernate\n */\n private HibernateConnection conn;\n\n /**\n * Viene assegnata all'attributo privato conn l'istanza Singleton della connessione di Hibernate al database\n */\n public CalendarDatesDao() {\n this.conn = HibernateConnection.getInstance();\n }\n\n public HibernateConnection getConn() {\n return conn;\n }\n\n public void setConn(HibernateConnection conn) {\n this.conn = conn;\n }\n\n /**\n * Metodo che implementa la query al database che ritorna tutte le tuple nella table di riferimento\n *\n * @return una lista di CalendarDatesEntity\n */\n @Override\n @SuppressWarnings(\"unchecked\")\n public List<CalendarDatesEntity> findAll() {\n List<CalendarDatesEntity> calendarDatesEntities = (List<CalendarDatesEntity>) conn.getCurrentSession().createQuery(\"from CalendarDatesEntity\").list();\n return calendarDatesEntities;\n }\n}"
},
{
"identifier": "CalendarDatesEntity",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/entity/CalendarDatesEntity.java",
"snippet": "@Entity\n@Table(name = \"calendar_dates\", schema = \"trenissimo\")\npublic class CalendarDatesEntity {\n @Basic\n @Column(name = \"service_id\", nullable = true)\n private Long serviceId;\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"date\", nullable = false)\n private int date;\n @Basic\n @Column(name = \"exception_type\", nullable = true)\n private Integer exceptionType;\n @ManyToOne\n @JoinColumn(name = \"service_id\", referencedColumnName = \"service_id\", insertable = false, updatable = false)\n private CalendarEntity calendarByServiceId;\n\n public Long getServiceId() {\n return serviceId;\n }\n\n public void setServiceId(Long serviceId) {\n this.serviceId = serviceId;\n }\n\n public int getDate() {\n return date;\n }\n\n public void setDate(int date) {\n this.date = date;\n }\n\n public Integer getExceptionType() {\n return exceptionType;\n }\n\n public void setExceptionType(Integer exceptionType) {\n this.exceptionType = exceptionType;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n CalendarDatesEntity that = (CalendarDatesEntity) o;\n return date == that.date && Objects.equals(serviceId, that.serviceId) && Objects.equals(exceptionType, that.exceptionType);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(serviceId, date, exceptionType);\n }\n\n public CalendarEntity getCalendarByServiceId() {\n return calendarByServiceId;\n }\n\n public void setCalendarByServiceId(CalendarEntity calendarByServiceId) {\n this.calendarByServiceId = calendarByServiceId;\n }\n\n @Override\n public String toString() {\n return \"CalendarDatesEntity{\" +\n \"serviceId=\" + serviceId +\n \", date=\" + date +\n \", exceptionType=\" + exceptionType +\n '}';\n }\n}"
},
{
"identifier": "ICalendarDatesService",
"path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/persistence/util/service/ICalendarDatesService.java",
"snippet": "public interface ICalendarDatesService {\n\n List<CalendarDatesEntity> findAll();\n\n}"
}
] | import it.unipv.po.aioobe.trenissimo.model.persistence.dao.CalendarDatesDao;
import it.unipv.po.aioobe.trenissimo.model.persistence.entity.CalendarDatesEntity;
import it.unipv.po.aioobe.trenissimo.model.persistence.util.service.ICalendarDatesService;
import java.util.List; | 1,116 | package it.unipv.po.aioobe.trenissimo.model.persistence.service;
/**
* Classe che, secondo il pattern Facade, implementa gli stessi metodi di CalendarDatesDao con l'aggiunta della gestione delle sessioni del framework Hibernate.
* Classe progettata per nascondere al modello delle classi la complessità del sistema sottostante (Hibernate)
*
* @author ArrayIndexOutOfBoundsException
*/
public class CalendarDatesService implements ICalendarDatesService {
private static CalendarDatesDao calendarDatesDao;
public CalendarDatesService() {
calendarDatesDao = new CalendarDatesDao();
}
@Override | package it.unipv.po.aioobe.trenissimo.model.persistence.service;
/**
* Classe che, secondo il pattern Facade, implementa gli stessi metodi di CalendarDatesDao con l'aggiunta della gestione delle sessioni del framework Hibernate.
* Classe progettata per nascondere al modello delle classi la complessità del sistema sottostante (Hibernate)
*
* @author ArrayIndexOutOfBoundsException
*/
public class CalendarDatesService implements ICalendarDatesService {
private static CalendarDatesDao calendarDatesDao;
public CalendarDatesService() {
calendarDatesDao = new CalendarDatesDao();
}
@Override | public List<CalendarDatesEntity> findAll() { | 1 | 2023-12-21 10:41:11+00:00 | 2k |
Workworks/rule-engine-practice | drools-demo/src/test/java/org/kfaino/test/DroolsTest.java | [
{
"identifier": "ComparisonOperatorEntity",
"path": "drools-demo/src/main/java/org/kfaino/drools/entity/ComparisonOperatorEntity.java",
"snippet": "public class ComparisonOperatorEntity {\n private String names;\n private List<String> list;\n\n public String getNames() {\n return names;\n }\n\n public void setNames(String names) {\n this.names = names;\n }\n\n public List<String> getList() {\n return list;\n }\n\n public void setList(List<String> list) {\n this.list = list;\n }\n}"
},
{
"identifier": "Order",
"path": "drools-demo/src/main/java/org/kfaino/drools/entity/Order.java",
"snippet": "public class Order {\n private Double originalPrice;//订单原始价格,即优惠前价格\n private Double realPrice;//订单真实价格,即优惠后价格\n\n public String toString() {\n return \"Order{\" +\n \"originalPrice=\" + originalPrice +\n \", realPrice=\" + realPrice +\n '}';\n }\n\n public Double getOriginalPrice() {\n return originalPrice;\n }\n\n public void setOriginalPrice(Double originalPrice) {\n this.originalPrice = originalPrice;\n }\n\n public Double getRealPrice() {\n return realPrice;\n }\n\n public void setRealPrice(Double realPrice) {\n this.realPrice = realPrice;\n }\n}"
},
{
"identifier": "Student",
"path": "drools-demo/src/main/java/org/kfaino/drools/entity/Student.java",
"snippet": "public class Student {\n private int id;\n private String name;\n private int age;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public int getAge() {\n return age;\n }\n\n public void setAge(int age) {\n this.age = age;\n }\n}"
},
{
"identifier": "UserService",
"path": "drools-demo/src/main/java/org/kfaino/drools/service/UserService.java",
"snippet": "public class UserService {\n public void save(){\n System.out.println(\"UserService.save()...\");\n }\n}"
}
] | import org.kfaino.drools.entity.ComparisonOperatorEntity;
import org.kfaino.drools.entity.Order;
import org.kfaino.drools.entity.Student;
import org.kfaino.drools.service.UserService;
import org.drools.core.base.RuleNameEqualsAgendaFilter;
import org.drools.core.base.RuleNameStartsWithAgendaFilter;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.QueryResults;
import org.kie.api.runtime.rule.QueryResultsRow;
import java.util.ArrayList;
import java.util.List; | 1,051 | package org.kfaino.test;
public class DroolsTest {
@Test
public void test1(){
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
Order order = new Order();
order.setOriginalPrice(500d);
//将Order对象插入到工作内存中
session.insert(order);
System.out.println("----优惠后价格:"+order.getRealPrice());
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
System.out.println("优惠后价格:"+order.getRealPrice());
}
//测试比较操作符
@Test
public void test2(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象 | package org.kfaino.test;
public class DroolsTest {
@Test
public void test1(){
System.setProperty("drools.dateformat","yyyy-MM-dd HH:mm");
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象
Order order = new Order();
order.setOriginalPrice(500d);
//将Order对象插入到工作内存中
session.insert(order);
System.out.println("----优惠后价格:"+order.getRealPrice());
//激活规则,由Drools框架自动进行规则匹配,如果规则匹配成功,则执行当前规则
session.fireAllRules();
//关闭会话
session.dispose();
System.out.println("优惠后价格:"+order.getRealPrice());
}
//测试比较操作符
@Test
public void test2(){
KieServices kieServices = KieServices.Factory.get();
//获得Kie容器对象
KieContainer kieContainer = kieServices.newKieClasspathContainer();
//从Kie容器对象中获取会话对象
KieSession session = kieContainer.newKieSession();
//Fact对象,事实对象 | ComparisonOperatorEntity fact = new ComparisonOperatorEntity(); | 0 | 2023-12-21 06:23:04+00:00 | 2k |
SagenApp/gpt-for-uds | src/main/java/app/sagen/chatgptclient/gpt/JsonIterator.java | [
{
"identifier": "ChatCompletionResponse",
"path": "src/main/java/app/sagen/chatgptclient/data/ChatCompletionResponse.java",
"snippet": "public final class ChatCompletionResponse {\n @SerializedName(\"id\")\n private final String id;\n @SerializedName(\"object\")\n private final String object;\n @SerializedName(\"created\")\n private final long created;\n @SerializedName(\"model\")\n private final String model;\n @SerializedName(\"system_fingerprint\")\n private final String systemFingerprint;\n @SerializedName(\"choices\")\n private final List<Choice> choices;\n\n public ChatCompletionResponse(\n String id,\n String object,\n long created,\n String model,\n String systemFingerprint,\n List<Choice> choices) {\n this.id = id;\n this.object = object;\n this.created = created;\n this.model = model;\n this.systemFingerprint = systemFingerprint;\n this.choices = choices;\n }\n\n @SerializedName(\"id\")\n public String id() {\n return id;\n }\n\n @SerializedName(\"object\")\n public String object() {\n return object;\n }\n\n @SerializedName(\"created\")\n public long created() {\n return created;\n }\n\n @SerializedName(\"model\")\n public String model() {\n return model;\n }\n\n @SerializedName(\"system_fingerprint\")\n public String systemFingerprint() {\n return systemFingerprint;\n }\n\n @SerializedName(\"choices\")\n public List<Choice> choices() {\n return choices;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) return true;\n if (obj == null || obj.getClass() != this.getClass()) return false;\n var that = (ChatCompletionResponse) obj;\n return Objects.equals(this.id, that.id) &&\n Objects.equals(this.object, that.object) &&\n this.created == that.created &&\n Objects.equals(this.model, that.model) &&\n Objects.equals(this.systemFingerprint, that.systemFingerprint) &&\n Objects.equals(this.choices, that.choices);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, object, created, model, systemFingerprint, choices);\n }\n\n @Override\n public String toString() {\n return \"ChatCompletionResponse[\" +\n \"id=\" + id + \", \" +\n \"object=\" + object + \", \" +\n \"created=\" + created + \", \" +\n \"model=\" + model + \", \" +\n \"systemFingerprint=\" + systemFingerprint + \", \" +\n \"choices=\" + choices + ']';\n }\n\n}"
},
{
"identifier": "ChatCompletionResponseChunk",
"path": "src/main/java/app/sagen/chatgptclient/data/ChatCompletionResponseChunk.java",
"snippet": "public final class ChatCompletionResponseChunk {\n @SerializedName(\"id\")\n private final String id;\n @SerializedName(\"system_fingerprint\")\n private final String systemFingerprint;\n @SerializedName(\"textPart\")\n private final String textPart;\n\n public ChatCompletionResponseChunk(\n String id,\n String systemFingerprint,\n String textPart) {\n this.id = id;\n this.systemFingerprint = systemFingerprint;\n this.textPart = textPart;\n }\n\n @SerializedName(\"id\")\n public String id() {\n return id;\n }\n\n @SerializedName(\"system_fingerprint\")\n public String systemFingerprint() {\n return systemFingerprint;\n }\n\n @SerializedName(\"textPart\")\n public String textPart() {\n return textPart;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == this) return true;\n if (obj == null || obj.getClass() != this.getClass()) return false;\n var that = (ChatCompletionResponseChunk) obj;\n return Objects.equals(this.id, that.id) &&\n Objects.equals(this.systemFingerprint, that.systemFingerprint) &&\n Objects.equals(this.textPart, that.textPart);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(id, systemFingerprint, textPart);\n }\n\n @Override\n public String toString() {\n return \"ChatCompletionResponseChunk[\" +\n \"id=\" + id + \", \" +\n \"systemFingerprint=\" + systemFingerprint + \", \" +\n \"textPart=\" + textPart + ']';\n }\n\n}"
}
] | import app.sagen.chatgptclient.data.ChatCompletionResponse;
import app.sagen.chatgptclient.data.ChatCompletionResponseChunk;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UncheckedIOException; | 1,381 | package app.sagen.chatgptclient.gpt;
// Helper class to iterate over SSE responses from a BufferedReader and convert them to Stream
record JsonIterator(
BufferedReader bufferedReader,
Gson gson
) implements Iterable<ChatCompletionResponseChunk> {
@Override
public java.util.Iterator<ChatCompletionResponseChunk> iterator() {
return new ChatCompletionResponseChunkIterator();
}
private class ChatCompletionResponseChunkIterator implements java.util.Iterator<ChatCompletionResponseChunk> {
ChatCompletionResponseChunk nextElement;
@Override
public boolean hasNext() {
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("data:") && !line.equalsIgnoreCase("data: [DONE]")) {
if (parseLineAndUpdateNext(line)) {
return true;
}
// Ignore empty responses
}
// Else ignore empty lines or other parts of the SSE protocol like "id:" or "retry:"
}
return false;
} catch (IOException e) {
throw new UncheckedIOException("Error reading from the SSE stream", e);
}
}
private boolean parseLineAndUpdateNext(String line) {
String jsonContent = line.substring(5).trim(); // Remove "data:" prefix | package app.sagen.chatgptclient.gpt;
// Helper class to iterate over SSE responses from a BufferedReader and convert them to Stream
record JsonIterator(
BufferedReader bufferedReader,
Gson gson
) implements Iterable<ChatCompletionResponseChunk> {
@Override
public java.util.Iterator<ChatCompletionResponseChunk> iterator() {
return new ChatCompletionResponseChunkIterator();
}
private class ChatCompletionResponseChunkIterator implements java.util.Iterator<ChatCompletionResponseChunk> {
ChatCompletionResponseChunk nextElement;
@Override
public boolean hasNext() {
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.startsWith("data:") && !line.equalsIgnoreCase("data: [DONE]")) {
if (parseLineAndUpdateNext(line)) {
return true;
}
// Ignore empty responses
}
// Else ignore empty lines or other parts of the SSE protocol like "id:" or "retry:"
}
return false;
} catch (IOException e) {
throw new UncheckedIOException("Error reading from the SSE stream", e);
}
}
private boolean parseLineAndUpdateNext(String line) {
String jsonContent = line.substring(5).trim(); // Remove "data:" prefix | ChatCompletionResponse preliminaryNext = gson.fromJson(jsonContent, ChatCompletionResponse.class); | 0 | 2023-12-18 22:47:47+00:00 | 2k |
TerronesDiaz/easyOnlineShopApiRest | src/main/java/com/example/easyOnlineShop/easyOnlineShop/Service/impl/DigitalProductIMPL.java | [
{
"identifier": "DigitalProductDTO",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Dto/DigitalProductDTO.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class DigitalProductDTO extends ProductDTO {\n\n private double fileSize;\n private String format;\n private CommissionType commissionType;\n private double commissionValue;\n}"
},
{
"identifier": "DigitalProduct",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Entity/DigitalProduct.java",
"snippet": "@EqualsAndHashCode(callSuper = true)\n@Entity\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@DiscriminatorValue(\"DIGITAL\")\npublic class DigitalProduct extends Product {\n\n @Column(name = \"file_size\")\n private double fileSize;\n\n @NonNull\n @Column(name = \"format\")\n private String format;\n\n @NonNull\n @Enumerated(EnumType.STRING)\n @Column(name = \"commission_type\")\n private CommissionType commissionType;\n\n @Column(name = \"commission_value\")\n private double commissionValue;\n}"
},
{
"identifier": "ProductImage",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Entity/ProductImage.java",
"snippet": "@Entity\r\n@Table(name = \"Product_Image\")\r\n@Data\r\n@NoArgsConstructor\r\n@AllArgsConstructor\r\npublic class ProductImage {\r\n\r\n @Id\r\n @GeneratedValue(strategy = GenerationType.IDENTITY)\r\n @Column(name = \"image_id\")\r\n private long imageId;\r\n\r\n @Lob\r\n @Column(name = \"image_url\", nullable = false)\r\n private String imageURL;\r\n\r\n @NonNull\r\n @Column(name = \"image_name\", nullable = false)\r\n private String imageName;\r\n\r\n @ManyToOne\r\n @JoinColumn(name = \"product_id\") // This is the name of the column in table 'Product_Image' that joins the column 'product_id' in 'Product'\r\n private Product product; // Inverse relationship with the entity Product.\r\n\r\n}\r"
},
{
"identifier": "ProductStatus",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Enums/ProductStatus.java",
"snippet": "public enum ProductStatus {\n AVAILABLE,\n DELETED,\n\n}"
},
{
"identifier": "DigitalProductRepository",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Repo/DigitalProductRepository.java",
"snippet": "@EnableJpaRepositories\n@Repository\npublic interface DigitalProductRepository extends JpaRepository<DigitalProduct, Long> {\n\n}"
},
{
"identifier": "ProductImageRepository",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Repo/ProductImageRepository.java",
"snippet": "@EnableJpaRepositories\n@Repository\npublic interface ProductImageRepository extends JpaRepository<ProductImage, Long> {\n\n}"
},
{
"identifier": "DigitalProductService",
"path": "src/main/java/com/example/easyOnlineShop/easyOnlineShop/Service/DigitalProductService.java",
"snippet": "public interface DigitalProductService {\n List<DigitalProductDTO> findAllDigitalProducts();\n\n String addDigitalProduct(DigitalProductDTO physicalProductDTO);\n\n String editDigitalProduct(DigitalProductDTO physicalProductDTO);\n\n}"
}
] | import com.example.easyOnlineShop.easyOnlineShop.Dto.DigitalProductDTO;
import com.example.easyOnlineShop.easyOnlineShop.Entity.DigitalProduct;
import com.example.easyOnlineShop.easyOnlineShop.Entity.ProductImage;
import com.example.easyOnlineShop.easyOnlineShop.Enums.ProductStatus;
import com.example.easyOnlineShop.easyOnlineShop.Repo.DigitalProductRepository;
import com.example.easyOnlineShop.easyOnlineShop.Repo.ProductImageRepository;
import com.example.easyOnlineShop.easyOnlineShop.Service.DigitalProductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors; | 1,019 | package com.example.easyOnlineShop.easyOnlineShop.Service.impl;
@Service
@Transactional
public class DigitalProductIMPL implements DigitalProductService {
private final DigitalProductRepository digitalProductRepository;
private final ProductImageRepository productImageRepository;
// Inject the repository through the constructor
public DigitalProductIMPL(DigitalProductRepository digitalProductRepository, ProductImageRepository productImageRepository) {
this.digitalProductRepository = digitalProductRepository;
this.productImageRepository = productImageRepository;
}
@Override
public List<DigitalProductDTO> findAllDigitalProducts() {
// Convert the entities to DTOs and return the list
return digitalProductRepository.findAll().stream()
.map(this::entityToDto)
.collect(Collectors.toList());
}
@Override
public String addDigitalProduct(DigitalProductDTO digitalProductDTO) {
// Convert DTO to entity, save and return a message or the product id | package com.example.easyOnlineShop.easyOnlineShop.Service.impl;
@Service
@Transactional
public class DigitalProductIMPL implements DigitalProductService {
private final DigitalProductRepository digitalProductRepository;
private final ProductImageRepository productImageRepository;
// Inject the repository through the constructor
public DigitalProductIMPL(DigitalProductRepository digitalProductRepository, ProductImageRepository productImageRepository) {
this.digitalProductRepository = digitalProductRepository;
this.productImageRepository = productImageRepository;
}
@Override
public List<DigitalProductDTO> findAllDigitalProducts() {
// Convert the entities to DTOs and return the list
return digitalProductRepository.findAll().stream()
.map(this::entityToDto)
.collect(Collectors.toList());
}
@Override
public String addDigitalProduct(DigitalProductDTO digitalProductDTO) {
// Convert DTO to entity, save and return a message or the product id | DigitalProduct entity = dtoToEntity(digitalProductDTO); | 1 | 2023-12-21 20:13:34+00:00 | 2k |
snow-yu/java-demos | validate-demo/src/test/java/com/snow/validation/ValidationTest.java | [
{
"identifier": "TeacherReq",
"path": "validate-demo/src/main/java/com/snow/validation/model/TeacherReq.java",
"snippet": "public class TeacherReq {\n\n @NotBlank(message = \"姓名不能为空\")\n @Length(max = 50, message = \"姓名最大长度{max}\")\n private String name;\n\n @NotNull(message = \"年龄不能为空\")\n @Range(min = 18, max = 100, message = \"年龄必须在{min}-{max}之间\")\n private Integer age;\n\n /**\n * @Validated 不允许使用在成员属性上,所以只能用@Valid\n * 如果不加 @Valid 就不会对 StudentReq类进行校验,只会判断 @NotNull,List<Son>是否为空,并不会校验StudentReq类里面的成员属性\n */\n @Valid\n @NotEmpty(message = \"学生不能为空\")\n @Size(min = 2, max = 10, message = \"学生个数必须在{min}-{max}之间\")\n private List<StudentReq> studentList;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getAge() {\n return age;\n }\n\n public void setAge(Integer age) {\n this.age = age;\n }\n\n public List<StudentReq> getStudentList() {\n return studentList;\n }\n\n public void setStudentList(List<StudentReq> studentList) {\n this.studentList = studentList;\n }\n\n @Override\n public String toString() {\n return \"TeacherReq{\" +\n \"name='\" + name + '\\'' +\n \", age=\" + age +\n \", studentList=\" + studentList +\n '}';\n }\n}"
},
{
"identifier": "ValidationService",
"path": "validate-demo/src/main/java/com/snow/validation/service/ValidationService.java",
"snippet": "@Validated\npublic interface ValidationService {\n\n /**\n * 入参对象校验 在类上新增@Validated\n * 在入参对象加 @Valid\n *\n * @param teacherReq 教师\n */\n void addTeacher(@Valid TeacherReq teacherReq);\n\n /**\n * 入参基本类型校验 在类上新增@Validated\n * 在入参值上新增校验注解\n *\n * @param age 年龄\n * @param name 姓名\n */\n void addUser(@NotNull @Min(10) Integer age, @NotEmpty String name);\n}"
}
] | import com.snow.validation.model.TeacherReq;
import com.snow.validation.service.ValidationService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; | 759 | package com.snow.validation;
/**
* @author jiaXue
* date 2023/12/19
*/
@SpringBootTest
public class ValidationTest {
@Autowired
private ValidationService validationService;
// service 校验验证
@Test
void testObjectService() {
try {
// 验证不通过 | package com.snow.validation;
/**
* @author jiaXue
* date 2023/12/19
*/
@SpringBootTest
public class ValidationTest {
@Autowired
private ValidationService validationService;
// service 校验验证
@Test
void testObjectService() {
try {
// 验证不通过 | validationService.addTeacher(new TeacherReq()); | 0 | 2023-12-14 00:22:49+00:00 | 2k |
kavindumal/layered-architecture-kavindu-malshan-jayasinghe | src/main/java/com/example/layeredarchitecture/controller/ManageCustomersFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/com/example/layeredarchitecture/bo/BOFactory.java",
"snippet": "public class BOFactory {\n private BOFactory(){}\n\n private static BOFactory boFactory;\n\n public static BOFactory getBOFactory() {\n return (boFactory == null) ? boFactory = new BOFactory() : boFactory;\n }\n\n public enum BOType{\n CUSTOMER,ITEM,PLACE_ORDER\n }\n\n public SuperBO getBO(BOType boType){\n switch (boType){\n case CUSTOMER -> {\n return new CustomerBOImpl();\n }\n case ITEM -> {\n return new ItemBOImpl();\n }\n case PLACE_ORDER -> {\n return new PlaceOrderBOImpl();\n }\n default -> {\n return null;\n }\n }\n }\n}"
},
{
"identifier": "CustomerBOImpl",
"path": "src/main/java/com/example/layeredarchitecture/bo/CustomerBOImpl.java",
"snippet": "public class CustomerBOImpl implements CustomerBO {\n CustomerDAO customerDAO = (CustomerDAO) DAOFactory.getDAOFactory().getDAO(DAOFactory.DAOType.CUSTOMER);\n\n @Override\n public boolean saveCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException{\n //customer business logic example\n return customerDAO.save(dto);\n }\n\n @Override\n public ArrayList<CustomerDTO> getAllCustomer() throws SQLException, ClassNotFoundException {\n return customerDAO.getAll();\n }\n\n @Override\n public boolean updateCustomer(CustomerDTO dto) throws SQLException, ClassNotFoundException {\n return customerDAO.update(dto);\n }\n\n @Override\n public boolean existCustomer(String id) throws SQLException, ClassNotFoundException {\n return customerDAO.exist(id);\n }\n\n @Override\n public boolean deleteCustomer(String id) throws SQLException, ClassNotFoundException {\n return customerDAO.delete(id);\n }\n\n @Override\n public String generateIDCustomer() throws SQLException, ClassNotFoundException {\n return customerDAO.generateID();\n }\n\n @Override\n public CustomerDTO searchCustomer(String id) throws SQLException, ClassNotFoundException {\n return customerDAO.search(id);\n }\n}"
},
{
"identifier": "CustomerDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/CustomerDTO.java",
"snippet": "public class CustomerDTO implements Serializable {\n private String id;\n private String name;\n private String address;\n\n public CustomerDTO() {\n }\n\n public CustomerDTO(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerDTO{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "CustomerTM",
"path": "src/main/java/com/example/layeredarchitecture/view/tdm/CustomerTM.java",
"snippet": "public class CustomerTM implements Comparable<CustomerTM> {\n private String id;\n private String name;\n private String address;\n\n public CustomerTM() {\n }\n\n public CustomerTM(String id, String name, String address) {\n this.id = id;\n this.name = name;\n this.address = address;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n @Override\n public String toString() {\n return \"CustomerTM{\" +\n \"id='\" + id + '\\'' +\n \", name='\" + name + '\\'' +\n \", address='\" + address + '\\'' +\n '}';\n }\n\n\n @Override\n public int compareTo(CustomerTM o) {\n return id.compareTo(o.getId());\n }\n}"
}
] | import com.example.layeredarchitecture.bo.BOFactory;
import com.example.layeredarchitecture.bo.CustomerBOImpl;
import com.example.layeredarchitecture.model.CustomerDTO;
import com.example.layeredarchitecture.view.tdm.CustomerTM;
import com.jfoenix.controls.JFXButton;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; | 1,568 | package com.example.layeredarchitecture.controller;
public class ManageCustomersFormController {
public AnchorPane root;
public TextField txtCustomerName;
public TextField txtCustomerId;
public JFXButton btnDelete;
public JFXButton btnSave;
public TextField txtCustomerAddress;
public TableView<CustomerTM> tblCustomers;
public JFXButton btnAddNewCustomer;
CustomerBOImpl customerBO = (CustomerBOImpl) BOFactory.getBOFactory().getBO(BOFactory.BOType.CUSTOMER);
public void initialize() {
tblCustomers.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("id"));
tblCustomers.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("name"));
tblCustomers.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("address"));
initUI();
tblCustomers.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
btnDelete.setDisable(newValue == null);
btnSave.setText(newValue != null ? "Update" : "Save");
btnSave.setDisable(newValue == null);
if (newValue != null) {
txtCustomerId.setText(newValue.getId());
txtCustomerName.setText(newValue.getName());
txtCustomerAddress.setText(newValue.getAddress());
txtCustomerId.setDisable(false);
txtCustomerName.setDisable(false);
txtCustomerAddress.setDisable(false);
}
});
txtCustomerAddress.setOnAction(event -> btnSave.fire());
loadAllCustomers();
}
private void loadAllCustomers() {
tblCustomers.getItems().clear();
/*Get all customers*/
try {
| package com.example.layeredarchitecture.controller;
public class ManageCustomersFormController {
public AnchorPane root;
public TextField txtCustomerName;
public TextField txtCustomerId;
public JFXButton btnDelete;
public JFXButton btnSave;
public TextField txtCustomerAddress;
public TableView<CustomerTM> tblCustomers;
public JFXButton btnAddNewCustomer;
CustomerBOImpl customerBO = (CustomerBOImpl) BOFactory.getBOFactory().getBO(BOFactory.BOType.CUSTOMER);
public void initialize() {
tblCustomers.getColumns().get(0).setCellValueFactory(new PropertyValueFactory<>("id"));
tblCustomers.getColumns().get(1).setCellValueFactory(new PropertyValueFactory<>("name"));
tblCustomers.getColumns().get(2).setCellValueFactory(new PropertyValueFactory<>("address"));
initUI();
tblCustomers.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
btnDelete.setDisable(newValue == null);
btnSave.setText(newValue != null ? "Update" : "Save");
btnSave.setDisable(newValue == null);
if (newValue != null) {
txtCustomerId.setText(newValue.getId());
txtCustomerName.setText(newValue.getName());
txtCustomerAddress.setText(newValue.getAddress());
txtCustomerId.setDisable(false);
txtCustomerName.setDisable(false);
txtCustomerAddress.setDisable(false);
}
});
txtCustomerAddress.setOnAction(event -> btnSave.fire());
loadAllCustomers();
}
private void loadAllCustomers() {
tblCustomers.getItems().clear();
/*Get all customers*/
try {
| ArrayList<CustomerDTO> allCustomers = customerBO.getAllCustomer(); | 2 | 2023-12-16 04:16:50+00:00 | 2k |
TranHuy2k2/saga-choreography | payment-service/src/main/java/com/example/paymentservice/config/PaymentConsumerConfig.java | [
{
"identifier": "OrderStatus",
"path": "common-dtos/src/main/java/com/example/commondtos/enums/OrderStatus.java",
"snippet": "public enum OrderStatus {\n ORDER_CREATED, ORDER_COMPLETED, ORDER_CANCELLED\n}"
},
{
"identifier": "OrderEvent",
"path": "common-dtos/src/main/java/com/example/commondtos/event/OrderEvent.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class OrderEvent implements Event {\n private UUID eventId = UUID.randomUUID();\n private Date date = new Date();\n private OrderRequestDTO orderRequestDTO;\n private OrderStatus orderStatus;\n public OrderEvent(OrderRequestDTO orderRequestDTO, OrderStatus orderStatus) {\n this.orderRequestDTO = orderRequestDTO;\n this.orderStatus = orderStatus;\n }\n}"
},
{
"identifier": "PaymentEvent",
"path": "common-dtos/src/main/java/com/example/commondtos/event/PaymentEvent.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PaymentEvent implements Event{\n private UUID eventId = UUID.randomUUID();\n private Date date = new Date();\n private PaymentRequestDTO paymentRequestDTO;\n private PaymentStatus paymentStatus;\n public PaymentEvent(PaymentRequestDTO paymentRequestDTO, PaymentStatus paymentStatus) {\n this.paymentRequestDTO = paymentRequestDTO;\n this.paymentStatus = paymentStatus;\n }\n}"
},
{
"identifier": "PaymentService",
"path": "payment-service/src/main/java/com/example/paymentservice/service/PaymentService.java",
"snippet": "@Service\n@RequiredArgsConstructor\npublic class PaymentService {\n private final UserBalanceRepository userBalanceRepository;\n private final UserTransactionRepository userTransactionRepository;\n\n @PostConstruct\n public void initUserBalanceInDB() {\n userBalanceRepository.saveAll(Stream.of(new UserBalance(101, 5000),\n new UserBalance(102, 3000),\n new UserBalance(103, 4200),\n new UserBalance(104, 20000),\n new UserBalance(105, 999)).collect(Collectors.toList()));\n }\n\n // Saga Transaction\n @Transactional\n public PaymentEvent newOrderEvent(OrderEvent orderEvent) {\n OrderRequestDTO orderRequestDTO = orderEvent.getOrderRequestDTO();\n PaymentRequestDTO paymentRequestDTO = new PaymentRequestDTO(\n orderRequestDTO.getOrderId(),\n orderRequestDTO.getUserId(),\n orderRequestDTO.getAmount()\n );\n return userBalanceRepository.findById(paymentRequestDTO.getUserId())\n .filter(userBalance -> userBalance.getPrice() >= paymentRequestDTO.getAmount())\n .map(userBalance -> {\n userBalance.setPrice(userBalance.getPrice() - paymentRequestDTO.getAmount());\n userBalanceRepository.save(userBalance);\n return new PaymentEvent(paymentRequestDTO, PaymentStatus.PAYMENT_COMPLETED);\n })\n .orElse(new PaymentEvent(paymentRequestDTO, PaymentStatus.PAYMENT_FAILED));\n }\n\n // Compensating Transaction\n @Transactional\n public void cancelOrderEvent(OrderEvent orderEvent) {\n OrderRequestDTO orderRequestDTO = orderEvent.getOrderRequestDTO();\n PaymentRequestDTO paymentRequestDTO = new PaymentRequestDTO(\n orderRequestDTO.getOrderId(),\n orderRequestDTO.getUserId(),\n orderRequestDTO.getAmount()\n );\n userBalanceRepository.findById(paymentRequestDTO.getUserId())\n .ifPresent(userBalance -> {\n userBalance.setPrice(userBalance.getPrice() + paymentRequestDTO.getAmount());\n userBalanceRepository.save(userBalance);\n });\n }\n}"
}
] | import com.example.commondtos.enums.OrderStatus;
import com.example.commondtos.event.OrderEvent;
import com.example.commondtos.event.PaymentEvent;
import com.example.paymentservice.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.function.Function; | 868 | package com.example.paymentservice.config;
@Configuration
public class PaymentConsumerConfig {
@Autowired | package com.example.paymentservice.config;
@Configuration
public class PaymentConsumerConfig {
@Autowired | private PaymentService paymentService; | 3 | 2023-12-19 10:30:37+00:00 | 2k |
chulakasam/layered | src/main/java/com/example/layeredarchitecture/dao/custom/Impl/QueryDAOImpl.java | [
{
"identifier": "SQLUtil",
"path": "src/main/java/com/example/layeredarchitecture/dao/SQLUtil.java",
"snippet": "public class SQLUtil {\n public static <T>T test(String sql, Object...ob) throws SQLException, ClassNotFoundException {\n Connection connection = DBConnection.getDbConnection().getConnection();\n PreparedStatement pstm = connection.prepareStatement(sql);\n for(int i=0;i< ob.length;i++){\n pstm.setObject((i+1),ob[i]);\n }\n if(sql.startsWith(\"SELECT\")){\n return (T)pstm.executeQuery();\n }else{\n return (T)((Boolean)(pstm.executeUpdate()>0));\n }\n }\n\n}"
},
{
"identifier": "QueryDAO",
"path": "src/main/java/com/example/layeredarchitecture/dao/custom/QueryDAO.java",
"snippet": "public interface QueryDAO extends SuperDAO {\n\n ArrayList<SearchDto> search(String id) throws SQLException, ClassNotFoundException;\n\n\n ArrayList <TableDTO>LoadToTable(String id) throws SQLException, ClassNotFoundException;\n}"
},
{
"identifier": "SearchDto",
"path": "src/main/java/com/example/layeredarchitecture/model/SearchDto.java",
"snippet": "public class SearchDto {\n private String name;\n private String oid;\n private String date;\n\n public SearchDto() {\n }\n\n public SearchDto(String name, String oid, String date) {\n this.name = name;\n this.oid = oid;\n this.date = date;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n @Override\n public String toString() {\n return \"SearchDto{\" +\n \"name='\" + name + '\\'' +\n \", oid='\" + oid + '\\'' +\n \", date='\" + date + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "TableDTO",
"path": "src/main/java/com/example/layeredarchitecture/model/TableDTO.java",
"snippet": "public class TableDTO {private String oid;\n private String date;\n private String itemcode;\n private String description;\n private String qty;\n private String unitprice;\n\n public TableDTO() {\n }\n\n public TableDTO(String oid, String date, String itemcode, String description, String qty, String unitprice) {\n this.oid = oid;\n this.date = date;\n this.itemcode = itemcode;\n this.description = description;\n this.qty = qty;\n this.unitprice = unitprice;\n }\n\n public String getOid() {\n return oid;\n }\n\n public void setOid(String oid) {\n this.oid = oid;\n }\n\n public String getDate() {\n return date;\n }\n\n public void setDate(String date) {\n this.date = date;\n }\n\n public String getItemcode() {\n return itemcode;\n }\n\n public void setItemcode(String itemcode) {\n this.itemcode = itemcode;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getQty() {\n return qty;\n }\n\n public void setQty(String qty) {\n this.qty = qty;\n }\n\n public String getUnitprice() {\n return unitprice;\n }\n\n public void setUnitprice(String unitprice) {\n this.unitprice = unitprice;\n }\n\n @Override\n public String toString() {\n return \"TableDto{\" +\n \"oid='\" + oid + '\\'' +\n \", date='\" + date + '\\'' +\n \", itemcode='\" + itemcode + '\\'' +\n \", description='\" + description + '\\'' +\n \", qty='\" + qty + '\\'' +\n \", unitprice='\" + unitprice + '\\'' +\n '}';\n }\n}"
}
] | import com.example.layeredarchitecture.dao.SQLUtil;
import com.example.layeredarchitecture.dao.custom.QueryDAO;
import com.example.layeredarchitecture.model.SearchDto;
import com.example.layeredarchitecture.model.TableDTO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList; | 1,279 | package com.example.layeredarchitecture.dao.custom.Impl;
public class QueryDAOImpl implements QueryDAO {
@Override
public ArrayList<SearchDto> search(String id) throws SQLException, ClassNotFoundException {
ResultSet rst = SQLUtil.test("SELECT c.name, o.oid, o.date FROM Customer c JOIN Orders o on c.id = o.customerID WHERE c.id = ?",id);
ArrayList<SearchDto> getAllsearch = new ArrayList<>();
while (rst.next()) {
SearchDto searchDto = new SearchDto(rst.getString(1), rst.getString(2), rst.getString(3));
getAllsearch.add(searchDto);
}
return getAllsearch;
}
@Override
public ArrayList LoadToTable(String id) throws SQLException, ClassNotFoundException {
ResultSet rst=SQLUtil.test("SELECT od.oid, o.date, od.itemCode, i.description, od.qty, od.unitPrice FROM OrderDetails od JOIN Item i on od.itemCode = i.code join Orders o on od.oid = o.oid WHERE o.oid = ?",id); | package com.example.layeredarchitecture.dao.custom.Impl;
public class QueryDAOImpl implements QueryDAO {
@Override
public ArrayList<SearchDto> search(String id) throws SQLException, ClassNotFoundException {
ResultSet rst = SQLUtil.test("SELECT c.name, o.oid, o.date FROM Customer c JOIN Orders o on c.id = o.customerID WHERE c.id = ?",id);
ArrayList<SearchDto> getAllsearch = new ArrayList<>();
while (rst.next()) {
SearchDto searchDto = new SearchDto(rst.getString(1), rst.getString(2), rst.getString(3));
getAllsearch.add(searchDto);
}
return getAllsearch;
}
@Override
public ArrayList LoadToTable(String id) throws SQLException, ClassNotFoundException {
ResultSet rst=SQLUtil.test("SELECT od.oid, o.date, od.itemCode, i.description, od.qty, od.unitPrice FROM OrderDetails od JOIN Item i on od.itemCode = i.code join Orders o on od.oid = o.oid WHERE o.oid = ?",id); | ArrayList<TableDTO> getAlldetails = new ArrayList<>(); | 3 | 2023-12-15 04:45:10+00:00 | 2k |
pan2013e/ppt4j | framework/src/main/java/ppt4j/analysis/bytecode/InstControlFlowAnalyzer.java | [
{
"identifier": "InsnBlock",
"path": "framework/src/main/java/ppt4j/analysis/bytecode/graph/InsnBlock.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic final class InsnBlock {\n\n public final List<String> lines = new ArrayList<>();\n\n public final List<InsnBlock> nextBlockList = new ArrayList<>();\n public final List<InsnBlock> jumpBlockList = new ArrayList<>();\n\n public void addLines(List<String> list) {\n lines.addAll(list);\n }\n\n public void addNext(InsnBlock item) {\n nextBlockList.add(item);\n }\n\n public void addJump(InsnBlock item) {\n jumpBlockList.add(item);\n }\n\n}"
},
{
"identifier": "InsnText",
"path": "framework/src/main/java/ppt4j/analysis/bytecode/graph/InsnText.java",
"snippet": "@SuppressWarnings(\"unused\")\npublic final class InsnText {\n\n @Property(\"ppt4j.analysis.bytecode.print_length_limit\")\n private static int PRINT_LENGTH_LIMIT;\n\n Printer printer = new Textifier();\n\n public List<String> toLines(AbstractInsnNode[] array) {\n List<String> resultList = new ArrayList<>();\n if (array == null || array.length < 1) {\n return resultList;\n }\n\n for (AbstractInsnNode node : array) {\n List<String> lines = toLines(node);\n resultList.addAll(lines);\n }\n return resultList;\n }\n\n public List<String> toLines(AbstractInsnNode node) {\n List<String> resultList = new ArrayList<>();\n node.accept(new TraceMethodVisitor(printer));\n for(Object o: printer.getText()) {\n String s = o.toString().trim();\n if(s.length() > PRINT_LENGTH_LIMIT) {\n s = s.substring(0, PRINT_LENGTH_LIMIT - 3) + \"...\";\n }\n resultList.add(s);\n }\n printer.getText().clear();\n return resultList;\n }\n\n}"
}
] | import ppt4j.analysis.bytecode.graph.InsnBlock;
import ppt4j.analysis.bytecode.graph.InsnText;
import lombok.Getter;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.analysis.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | 713 | package ppt4j.analysis.bytecode;
public class InstControlFlowAnalyzer<V extends Value> extends Analyzer<V> {
@Getter
private AbstractInsnNode[] nodeArray;
private InsnBlock[] blocks;
public final Map<AbstractInsnNode, InsnBlock>
nodeToBlockMap = new HashMap<>();
public final Map<AbstractInsnNode, InsnBlock>
nodeToJumpBlockMap = new HashMap<>();
public final Map<InsnBlock, Integer>
blockToIndexMap = new HashMap<>();
public InstControlFlowAnalyzer(Interpreter<V> interpreter) {
super(interpreter);
}
@Override
public Frame<V>[] analyze(String owner, MethodNode method)
throws AnalyzerException {
nodeArray = method.instructions.toArray();
int length = nodeArray.length;
blocks = new InsnBlock[length]; | package ppt4j.analysis.bytecode;
public class InstControlFlowAnalyzer<V extends Value> extends Analyzer<V> {
@Getter
private AbstractInsnNode[] nodeArray;
private InsnBlock[] blocks;
public final Map<AbstractInsnNode, InsnBlock>
nodeToBlockMap = new HashMap<>();
public final Map<AbstractInsnNode, InsnBlock>
nodeToJumpBlockMap = new HashMap<>();
public final Map<InsnBlock, Integer>
blockToIndexMap = new HashMap<>();
public InstControlFlowAnalyzer(Interpreter<V> interpreter) {
super(interpreter);
}
@Override
public Frame<V>[] analyze(String owner, MethodNode method)
throws AnalyzerException {
nodeArray = method.instructions.toArray();
int length = nodeArray.length;
blocks = new InsnBlock[length]; | InsnText insnText = new InsnText(); | 1 | 2023-12-14 15:33:50+00:00 | 2k |