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
Ethylene9160/Chess
src/chess/panels/WebPanel.java
[ { "identifier": "Chess", "path": "src/chess/pieces/Chess.java", "snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DE...
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.Socket; import chess.pieces.Chess; import chess.recorder.Record; import chess.shop.MoneyShop; import chess.shop.ShengwangShop; import chess.shop.Shop; import chess.style.Style; import chess.threads.OpponentEmoThread; import chess.threads.YourEmoThread; import chess.util.Constants; import chess.util.ImagePath; import chess.web.ChessChannel; import chess.web.Receiver; import chess.web.Sender;
11,112
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456");
package chess.panels; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456");
private Sender sender;
12
2023-12-01 02:33:32+00:00
16k
tuxiaobei-scu/Draw-and-guess
entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java
[ { "identifier": "MainAbility", "path": "entry/src/main/java/com/tuxiaobei/drawandguess/MainAbility.java", "snippet": "public class MainAbility extends Ability {\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n super.setMainRoute(MainAbilitySlice.class.get...
import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT; import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; import com.tuxiaobei.drawandguess.MainAbility; import com.tuxiaobei.drawandguess.ResourceTable; import com.tuxiaobei.drawandguess.bean.AnswerItem; import com.tuxiaobei.drawandguess.bean.MyPoint; import com.tuxiaobei.drawandguess.component.ChangeName; import com.tuxiaobei.drawandguess.component.DeviceSelectDialog; import com.tuxiaobei.drawandguess.component.DrawPoint; import com.tuxiaobei.drawandguess.component.WordSelectDialog; import com.tuxiaobei.drawandguess.game.Guesser; import com.tuxiaobei.drawandguess.game.MainGame; import com.tuxiaobei.drawandguess.provider.AnswerItemProvider; import com.tuxiaobei.drawandguess.util.GsonUtil; import com.tuxiaobei.drawandguess.util.LogUtils; import com.tuxiaobei.drawandguess.util.Tools; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; import ohos.bundle.IBundleManager; import ohos.data.distributed.common.*; import ohos.data.distributed.user.SingleKvStore; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; import java.io.IOException; import java.util.ArrayList; import java.util.List;
11,187
if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> { DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this); dialog.setListener(deviceIds -> { if (deviceIds != null && !deviceIds.isEmpty()) { // 启动远程页面 startRemoteFas(deviceIds); // 同步远程数据库 pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); } dialog.hide(); }); dialog.show(); }); play.setClickedListener(component -> { WordSelectDialog dialog = new WordSelectDialog(MainAbilitySlice.this, main_game.getWords()); dialog.setListener(word -> { if (!word.isEmpty()) { newGame(word); } dialog.hide(); }); dialog.show(); }); change_name.setClickedListener(component -> { ChangeName dialog = new ChangeName(MainAbilitySlice.this, local_name); dialog.setListener(name -> { if (!name.isEmpty()) { setName(name); } dialog.hide(); }); dialog.show(); }); } /** * Initialize art boards * * @param intent Intent */ private void initDraw(Intent intent) { boolean isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); //int colorIndex = switchcolor.getColorIndex(); drawl.setWidth(MATCH_PARENT); drawl.setWidth(MATCH_PARENT); canvas.addComponent(drawl); drawPoints(); drawl.setOnDrawBack(points -> { if (points != null && points.size() > 1) { String pointsString = GsonUtil.objectToString(points);
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tuxiaobei.drawandguess.slice; /** * MainAbilitySlice * * @since 2021-04-06 */ public class MainAbilitySlice extends AbilitySlice { private static final String TAG = MainAbilitySlice.class.getName(); private static final int PERMISSION_CODE = 20201203; private static final int DELAY_TIME = 10; private static final String STORE_ID_KEY = "storeId"; private static final String POINTS_KEY = "points"; private static final String ANS_KEY = "ans"; private static final String COLOR_INDEX_KEY = "colorIndex"; private static final String IS_FORM_LOCAL_KEY = "isFormLocal"; private static String storeId; private DependentLayout canvas; private Image transform; private Image change_name; private KvManager kvManager; private SingleKvStore pointsSingleKvStore; private SingleKvStore ansSingleKvStore; private SingleKvStore nameSingleKvStore; private Text title; private DrawPoint drawl; private Image play; private Button back; private Text show_score; private Guesser guesser; private Text tip; private Button submit; private TextField ans; private MainGame main_game; private ListContainer ans_list; private final List<AnswerItem> ansData = new ArrayList<>(); private AnswerItemProvider answerItemProvider; private String deviceId; private String local_name; private boolean isLocal; @Override public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_main); storeId = STORE_ID_KEY + Tools.getRandom(); isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); drawl = new DrawPoint(this, isLocal); findComponentById(isLocal); requestPermission(); initView(intent); initDatabase(); if (isLocal) { nameSingleKvStore.putString(Tools.getDeviceId(this), "系统"); } initDraw(intent); ohos.global.resource.ResourceManager resManager = getResourceManager(); String[] words = null; try { words = resManager.getElement(ResourceTable.Strarray_words).getStringArray(); } catch (IOException e) { e.printStackTrace(); } catch (NotExistException e) { e.printStackTrace(); } catch (WrongTypeException e) { e.printStackTrace(); } main_game = new MainGame(this, words); initListContainer(); } private void initListContainer() { answerItemProvider = new AnswerItemProvider(ansData, this, isLocal); ans_list.setItemProvider(answerItemProvider); } private void initView(Intent intent) { if (!isLocal) { local_name = Tools.getDeviceId(this).substring(0, 6); storeId = intent.getStringParam(STORE_ID_KEY); } title.setText(isLocal ? "本地端" : local_name); transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE); } private void requestPermission() { if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { if (canRequestPermission(DISTRIBUTED_DATASYNC)) { requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE); } } } private void findComponentById(Boolean isLocal) { if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) { canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas); } if (findComponentById(ResourceTable.Id_transform) instanceof Image) { transform = (Image) findComponentById(ResourceTable.Id_transform); } if (findComponentById(ResourceTable.Id_change_name) instanceof Image) { change_name = (Image) findComponentById(ResourceTable.Id_change_name); } if (findComponentById(ResourceTable.Id_play) instanceof Image) { play = (Image) findComponentById(ResourceTable.Id_play); } if (findComponentById(ResourceTable.Id_title) instanceof Text) { title = (Text) findComponentById(ResourceTable.Id_title); } if (findComponentById(ResourceTable.Id_back) instanceof Button) { back = (Button) findComponentById(ResourceTable.Id_back); } if (findComponentById(ResourceTable.Id_ans) instanceof TextField) { ans = (TextField) findComponentById(ResourceTable.Id_ans); } if (findComponentById(ResourceTable.Id_submit) instanceof Button) { submit = (Button) findComponentById(ResourceTable.Id_submit); } if (findComponentById(ResourceTable.Id_tip) instanceof Text) { tip = (Text) findComponentById(ResourceTable.Id_tip); } if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) { ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers); } if (findComponentById(ResourceTable.Id_show_score) instanceof Text) { show_score = (Text) findComponentById(ResourceTable.Id_show_score); } if (isLocal) { if (findComponentById(ResourceTable.Id_red) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_red)); } if (findComponentById(ResourceTable.Id_green) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_green)); } if (findComponentById(ResourceTable.Id_blue) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_blue)); } if (findComponentById(ResourceTable.Id_yellow) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow)); } if (findComponentById(ResourceTable.Id_pink) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_pink)); } if (findComponentById(ResourceTable.Id_cyan) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan)); } if (findComponentById(ResourceTable.Id_black) instanceof Button) { drawl.addButton((Button) findComponentById(ResourceTable.Id_black)); } ans.setVisibility(Component.HIDE); submit.setVisibility(Component.HIDE); } else { back.setVisibility(Component.HIDE); play.setVisibility(Component.HIDE); show_score.setVisibility(Component.VISIBLE); change_name.setVisibility(Component.VISIBLE); guesser = new Guesser(submit, ans, tip, show_score, this); } transform.setClickedListener(component -> { DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this); dialog.setListener(deviceIds -> { if (deviceIds != null && !deviceIds.isEmpty()) { // 启动远程页面 startRemoteFas(deviceIds); // 同步远程数据库 pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY); } dialog.hide(); }); dialog.show(); }); play.setClickedListener(component -> { WordSelectDialog dialog = new WordSelectDialog(MainAbilitySlice.this, main_game.getWords()); dialog.setListener(word -> { if (!word.isEmpty()) { newGame(word); } dialog.hide(); }); dialog.show(); }); change_name.setClickedListener(component -> { ChangeName dialog = new ChangeName(MainAbilitySlice.this, local_name); dialog.setListener(name -> { if (!name.isEmpty()) { setName(name); } dialog.hide(); }); dialog.show(); }); } /** * Initialize art boards * * @param intent Intent */ private void initDraw(Intent intent) { boolean isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false); //int colorIndex = switchcolor.getColorIndex(); drawl.setWidth(MATCH_PARENT); drawl.setWidth(MATCH_PARENT); canvas.addComponent(drawl); drawPoints(); drawl.setOnDrawBack(points -> { if (points != null && points.size() > 1) { String pointsString = GsonUtil.objectToString(points);
LogUtils.info(TAG, "pointsString::" + pointsString);
12
2023-12-03 13:36:00+00:00
16k
godheaven/klib-data-jdbc
src/main/java/cl/kanopus/jdbc/impl/AbstractDAO.java
[ { "identifier": "DAOInterface", "path": "src/main/java/cl/kanopus/jdbc/DAOInterface.java", "snippet": "public interface DAOInterface<T, I> {\r\n\r\n long generateID() throws DataException;\r\n\r\n void persist(T entity) throws DataException;\r\n\r\n int update(T entity) throws DataException;\r\...
import cl.kanopus.common.data.Paginator; import cl.kanopus.common.data.enums.SortOrder; import cl.kanopus.common.enums.EnumIdentifiable; import cl.kanopus.common.util.CryptographyUtils; import cl.kanopus.common.util.GsonUtils; import cl.kanopus.common.util.Utils; import cl.kanopus.jdbc.DAOInterface; import cl.kanopus.jdbc.entity.Mapping; import cl.kanopus.jdbc.entity.annotation.Column; import cl.kanopus.jdbc.entity.annotation.ColumnGroup; import cl.kanopus.jdbc.entity.annotation.JoinTable; import cl.kanopus.jdbc.entity.annotation.Table; import cl.kanopus.jdbc.entity.mapper.AbstractRowMapper; import cl.kanopus.jdbc.exception.DataException; import cl.kanopus.jdbc.impl.engine.CustomEngine; import cl.kanopus.jdbc.impl.engine.Engine; import cl.kanopus.jdbc.impl.engine.OracleEngine; import cl.kanopus.jdbc.impl.engine.PostgresEngine; import cl.kanopus.jdbc.impl.engine.SQLServerEngine; import cl.kanopus.jdbc.util.JdbcCache; import cl.kanopus.jdbc.util.QueryIterator; import cl.kanopus.jdbc.util.SQLQueryDynamic; import cl.kanopus.jdbc.util.parser.ByteaJsonListParser; import cl.kanopus.jdbc.util.parser.ByteaJsonParser; import cl.kanopus.jdbc.util.parser.EnumParser; import cl.kanopus.jdbc.util.parser.JsonListParser; import cl.kanopus.jdbc.util.parser.JsonParser; import java.io.StringWriter; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.postgresql.util.PGobject; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.SqlParameter; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcCall;
14,233
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine(); private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) { String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL()); if (sqlQuery.isLimited()) { return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString(); } else { return sql; } } private String createSqlPagination(String sql, int limit, int offset) { return getCustom().createSqlPagination(sql, limit, offset).toString(); } @Override public int deleteByID(ID id) throws DataException { return deleteByID(getGenericTypeClass(), id); } protected int deleteByID(Class clazz, ID key) throws DataException { return deleteByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected int deleteByID(Class clazz, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same amount keys to remove the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM ").append(table.name()).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return update(sql.toString(), params); } protected <T> List<T> executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); Map<String, Object> out = sjc.execute(in); Map.Entry<String, Object> entry = out.entrySet().iterator().next(); if (entry.getValue() instanceof List<?>) { List<?> tempList = (List<?>) entry.getValue(); if (!tempList.isEmpty() && tempList.get(0).getClass().equals(returnType)) { return (List<T>) entry.getValue(); } } return new ArrayList<>(); } protected void executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); sjc.execute(in); } protected T executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); return sjc.executeFunction(returnType, params); } protected void executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); sjc.execute(params); } protected Map<String, Object> executeProcedureOut(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); Map<String, Object> out = sjc.execute(params); return out; } @Override public List<T> findAll() throws DataException { Table table = getTableName(getGenericTypeClass()); SQLQueryDynamic sqlQuery = new SQLQueryDynamic(getGenericTypeClass()); if (!"[unassigned]".equals(table.defaultOrderBy())) { sqlQuery.setOrderBy(table.defaultOrderBy(), SortOrder.ASCENDING); } return (List<T>) AbstractDAO.this.find(sqlQuery); } public List findAll(Class<? extends Mapping> aClass) throws DataException { return findAll(aClass, false); } public List findAll(Class<? extends Mapping> aClass, boolean loadAll) throws DataException { //@TODO: implementar defaultOrderBy List list; try {
package cl.kanopus.jdbc.impl; /** * This abstract class defines methods for data access that are common, * generally, all kinds of data access DAO must implement this class.Thus it is * given safely access the Connection database. The JdbcTemplate property is * kept private and gives access to the database through the methods implemented * in this AbstractDAO. * * @param <T> * @param <ID> * @author Pablo Diaz Saavedra * @email pabloandres.diazsaavedra@gmail.com * */ @SuppressWarnings("all") public abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> { enum Operation { UPDATE, PERSIST } private final Class<T> genericTypeClass; protected AbstractDAO() { Type type = getClass().getGenericSuperclass(); ParameterizedType paramType = (ParameterizedType) type; genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0]; } protected abstract NamedParameterJdbcTemplate getJdbcTemplate(); private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; protected abstract Engine getEngine(); private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) { String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL()); if (sqlQuery.isLimited()) { return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString(); } else { return sql; } } private String createSqlPagination(String sql, int limit, int offset) { return getCustom().createSqlPagination(sql, limit, offset).toString(); } @Override public int deleteByID(ID id) throws DataException { return deleteByID(getGenericTypeClass(), id); } protected int deleteByID(Class clazz, ID key) throws DataException { return deleteByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key}); } protected int deleteByID(Class clazz, Object... keys) throws DataException { Table table = getTableName(clazz); if (table.keys() == null || table.keys().length == 0) { throw new DataException("It is necessary to specify the primary keys for the entity: " + table.getClass().getCanonicalName()); } if (table.keys().length != keys.length) { throw new DataException("It is necessary to specify the same amount keys to remove the entity: " + table.getClass().getCanonicalName()); } StringBuilder sql = new StringBuilder(); sql.append("DELETE FROM ").append(table.name()).append(" WHERE "); HashMap<String, Object> params = new HashMap<>(); for (int i = 0; i < keys.length; i++) { params.put(table.keys()[i], keys[i]); sql.append(i == 0 ? "" : " AND "); sql.append(table.keys()[i]).append("=:").append(table.keys()[i]); } return update(sql.toString(), params); } protected <T> List<T> executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); Map<String, Object> out = sjc.execute(in); Map.Entry<String, Object> entry = out.entrySet().iterator().next(); if (entry.getValue() instanceof List<?>) { List<?> tempList = (List<?>) entry.getValue(); if (!tempList.isEmpty() && tempList.get(0).getClass().equals(returnType)) { return (List<T>) entry.getValue(); } } return new ArrayList<>(); } protected void executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters); SqlParameterSource in = new MapSqlParameterSource().addValues(params); sjc.execute(in); } protected T executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params, Class<T> returnType) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); return sjc.executeFunction(returnType, params); } protected void executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); sjc.execute(params); } protected Map<String, Object> executeProcedureOut(String name, SqlParameter[] parameters, MapSqlParameterSource params) { SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()); sjc.withProcedureName(name); sjc.withoutProcedureColumnMetaDataAccess(); sjc.declareParameters(parameters); Map<String, Object> out = sjc.execute(params); return out; } @Override public List<T> findAll() throws DataException { Table table = getTableName(getGenericTypeClass()); SQLQueryDynamic sqlQuery = new SQLQueryDynamic(getGenericTypeClass()); if (!"[unassigned]".equals(table.defaultOrderBy())) { sqlQuery.setOrderBy(table.defaultOrderBy(), SortOrder.ASCENDING); } return (List<T>) AbstractDAO.this.find(sqlQuery); } public List findAll(Class<? extends Mapping> aClass) throws DataException { return findAll(aClass, false); } public List findAll(Class<? extends Mapping> aClass, boolean loadAll) throws DataException { //@TODO: implementar defaultOrderBy List list; try {
String sql = JdbcCache.sqlBase(aClass, loadAll);
9
2023-11-27 18:25:00+00:00
16k
andre111/voxedit
src/client/java/me/andre111/voxedit/client/VoxEditClient.java
[ { "identifier": "Presets", "path": "src/main/java/me/andre111/voxedit/Presets.java", "snippet": "public class Presets {\n\tpublic static final ToolItem.Data andre111;\n\tpublic static final ItemStack andre111Stack;\n\tstatic {\n\t\tandre111 = new ToolItem.Data(Util.make(new ArrayList<>(), list -> {\n\t\...
import org.lwjgl.glfw.GLFW; import org.spongepowered.include.com.google.common.base.Objects; import me.andre111.voxedit.Presets; import me.andre111.voxedit.VoxEdit; import me.andre111.voxedit.client.gui.screen.ToolSelectionScreen; import me.andre111.voxedit.client.network.ClientNetworking; import me.andre111.voxedit.client.renderer.EditorRenderer; import me.andre111.voxedit.client.renderer.HudRenderer; import me.andre111.voxedit.client.renderer.SelectionRenderer; import me.andre111.voxedit.client.renderer.ToolRenderer; import me.andre111.voxedit.item.ToolItem; import me.andre111.voxedit.item.VoxEditItem; import me.andre111.voxedit.network.Command; import me.andre111.voxedit.tool.ConfiguredTool; import me.andre111.voxedit.tool.Tool; import me.andre111.voxedit.tool.config.ToolConfig; import me.andre111.voxedit.tool.data.Selection; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper; import net.fabricmc.fabric.api.client.rendering.v1.BuiltinItemRendererRegistry; import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents; import net.fabricmc.fabric.api.event.client.player.ClientPreAttackCallback; import net.fabricmc.fabric.api.itemgroup.v1.ItemGroupEvents; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.option.KeyBinding; import net.minecraft.client.util.InputUtil; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.text.Text; import net.minecraft.util.hit.BlockHitResult;
11,248
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE);
/* * Copyright (c) 2023 André Schweiger * * 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 me.andre111.voxedit.client; @Environment(value=EnvType.CLIENT) public class VoxEditClient implements ClientModInitializer { public static final KeyBinding INCREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_UP, "key.category.voxedit")); public static final KeyBinding DECREASE_RADIUS = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseRadius", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_PAGE_DOWN, "key.category.voxedit")); public static final KeyBinding INCREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.increaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_ADD, "key.category.voxedit")); public static final KeyBinding DECREASE_SPEED = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.decreaseSpeed", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_KP_SUBTRACT, "key.category.voxedit")); public static final KeyBinding UNDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.undo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Z, "key.category.voxedit")); public static final KeyBinding REDO = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.redo", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_Y, "key.category.voxedit")); public static final KeyBinding OPEN_MENU = KeyBindingHelper.registerKeyBinding(new KeyBinding("key.voxedit.openMenu", InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_V, "key.category.voxedit")); public static int retargetCooldown; @SuppressWarnings({ "rawtypes", "unchecked" }) @Override public void onInitializeClient() { ClientNetworking.init(); BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_TOOL, ToolRenderer.INSTANCE);
BuiltinItemRendererRegistry.INSTANCE.register(VoxEdit.ITEM_EDITOR, EditorRenderer.INSTANCE);
4
2023-12-01 15:12:26+00:00
16k
bioastroiner/Minetweaker-Gregtech6-Addon
src/main/java/mods/bio/gttweaker/core/GTTweaker.java
[ { "identifier": "IMaterial", "path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterial.java", "snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterial\")\npublic interface IMaterial {\n\tOreDictMaterial getMaterial();\n\n\t@ZenOperator(OperatorType.MUL)\n\tIMaterialStack multiply(long...
import cpw.mods.fml.common.event.FMLInitializationEvent; import gregapi.recipes.Recipe; import minetweaker.MineTweakerAPI; import minetweaker.MineTweakerImplementationAPI; import minetweaker.api.item.IIngredient; import minetweaker.util.IEventHandler; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterial; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData; import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialStack; import mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipe; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeFactory; import mods.bio.gttweaker.api.mods.gregtech.recipe.IRecipeMap; import mods.bio.gttweaker.core.command.GTCommand; import mods.bio.gttweaker.core.json.OreDictMaterial_Serializable; import mods.bio.gttweaker.mods.gregtech.oredict.*; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipe; import mods.bio.gttweaker.mods.gregtech.recipe.CTRecipeMaps; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTMaterialBracketHandler; import mods.bio.gttweaker.mods.gregtech.oredict.bracket.CTPrefixBracketHandler; import mods.bio.gttweaker.mods.gregtech.recipe.bracket.CTRecipeMapBracketHandler; import mods.bio.gttweaker.mods.minetweaker.CTIItemStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTILiquidStackExpansion; import mods.bio.gttweaker.mods.minetweaker.CTIOreDictExpansion; import net.minecraft.item.ItemStack; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.oredict.OreDictionary; import java.util.Objects;
11,217
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE();
package mods.bio.gttweaker.core; @cpw.mods.fml.common.Mod(modid = GTTweaker.MOD_ID, name = GTTweaker.MOD_NAME, version = GTTweaker.VERSION) public final class GTTweaker extends gregapi.api.Abstract_Mod { // https://github.com/GTNewHorizons/Minetweaker-Gregtech-5-Addon/blob/master/src/main/java/gttweaker/GTTweaker.java public static final String MOD_ID = "GRADLETOKEN_MODID"; public static final String MOD_NAME = "GRADLETOKEN_MODNAME"; public static final String VERSION = "GRADLETOKEN_VERSION"; public static final String GROUPNAME = "GRADLETOKEN_GROUPNAME"; public static gregapi.code.ModData MOD_DATA = new gregapi.code.ModData(MOD_ID, MOD_NAME); //@cpw.mods.fml.common.SidedProxy(modId = MOD_ID, clientSide = "gregapi.api.example.Example_Proxy_Client", serverSide = "gregapi.api.example.Example_Proxy_Server") public static gregapi.api.Abstract_Proxy PROXY; public static String FORMAT_RECIPE_MAP(Recipe.RecipeMap map){ String[] tmp = map.toString().split("\\."); return tmp[tmp.length-1]; } public static Recipe.RecipeMap FORMAT_RECIPE_MAP(String name){ Recipe.RecipeMap out = null; if(Recipe.RecipeMap.RECIPE_MAPS.containsKey(name)){ out = Recipe.RecipeMap.RECIPE_MAPS.get(name); } if(out == null) for (Recipe.RecipeMap map: Recipe.RecipeMap.RECIPE_MAP_LIST) { String[] tmp = map.toString().split("\\."); String sName = tmp[tmp.length-1]; if(Objects.equals(sName.toLowerCase(),name.toLowerCase())){ out = map; } } if(out!=null){ return out; } else { MineTweakerAPI.logError(name + " is not a valid recipemap name!"); } return out; } public GTTweaker() { } @Override public String getModID() { return MOD_ID; } @Override public String getModName() { return MOD_NAME; } @Override public String getModNameForLog() { return "GTTWEAKER"; } @Override public gregapi.api.Abstract_Proxy getProxy() { return PROXY; } // Do not change these 7 Functions. Just keep them this way. @cpw.mods.fml.common.Mod.EventHandler public final void onPreLoad(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { onModPreInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onLoad(cpw.mods.fml.common.event.FMLInitializationEvent aEvent) { onModInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onPostLoad(cpw.mods.fml.common.event.FMLPostInitializationEvent aEvent) { onModPostInit(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarting(cpw.mods.fml.common.event.FMLServerStartingEvent aEvent) { onModServerStarting(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStarted(cpw.mods.fml.common.event.FMLServerStartedEvent aEvent) { onModServerStarted(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopping(cpw.mods.fml.common.event.FMLServerStoppingEvent aEvent) { onModServerStopping(aEvent); } @cpw.mods.fml.common.Mod.EventHandler public final void onServerStopped(cpw.mods.fml.common.event.FMLServerStoppedEvent aEvent) { onModServerStopped(aEvent); } @Override public void onModPreInit2(cpw.mods.fml.common.event.FMLPreInitializationEvent aEvent) { } @Override public void onModInit2(FMLInitializationEvent aEvent) { OreDictMaterial_Serializable._INITLIZE();
MineTweakerAPI.registerClass(IRecipe.class);
4
2023-12-03 11:55:49+00:00
16k
tuxiaobei-scu/SCU-CCSOJ-Backend
DataBackup/src/main/java/top/hcode/hoj/manager/oj/BeforeDispatchInitManager.java
[ { "identifier": "GroupValidator", "path": "DataBackup/src/main/java/top/hcode/hoj/validator/GroupValidator.java", "snippet": "@Component\npublic class GroupValidator {\n\n @Autowired\n private GroupMemberEntityService groupMemberEntityService;\n\n @Autowired\n private GroupEntityService grou...
import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import top.hcode.hoj.validator.GroupValidator; import top.hcode.hoj.validator.TrainingValidator; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import top.hcode.hoj.common.exception.StatusAccessDeniedException; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.common.exception.StatusNotFoundException; import top.hcode.hoj.pojo.entity.contest.Contest; import top.hcode.hoj.pojo.entity.contest.ContestProblem; import top.hcode.hoj.pojo.entity.contest.ContestRecord; import top.hcode.hoj.pojo.entity.judge.Judge; import top.hcode.hoj.pojo.entity.problem.Problem; import top.hcode.hoj.pojo.entity.training.Training; import top.hcode.hoj.pojo.entity.training.TrainingProblem; import top.hcode.hoj.pojo.entity.training.TrainingRecord; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.dao.contest.ContestEntityService; import top.hcode.hoj.dao.contest.ContestProblemEntityService; import top.hcode.hoj.dao.contest.ContestRecordEntityService; import top.hcode.hoj.dao.judge.JudgeEntityService; import top.hcode.hoj.dao.problem.ProblemEntityService; import top.hcode.hoj.dao.training.TrainingEntityService; import top.hcode.hoj.dao.training.TrainingProblemEntityService; import top.hcode.hoj.dao.training.TrainingRecordEntityService; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.validator.ContestValidator; import javax.annotation.Resource;
12,866
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 14:29 * @Description: */ @Component public class BeforeDispatchInitManager { @Resource private ContestEntityService contestEntityService; @Resource private ContestRecordEntityService contestRecordEntityService; @Resource private ContestProblemEntityService contestProblemEntityService; @Resource private JudgeEntityService judgeEntityService; @Resource private ProblemEntityService problemEntityService; @Resource private TrainingEntityService trainingEntityService; @Resource private TrainingProblemEntityService trainingProblemEntityService; @Resource private TrainingRecordEntityService trainingRecordEntityService; @Resource private TrainingValidator trainingValidator; @Resource private ContestValidator contestValidator; @Autowired private GroupValidator groupValidator; public void initCommonSubmission(String problemId, Judge judge) throws StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); QueryWrapper<Problem> problemQueryWrapper = new QueryWrapper<>(); problemQueryWrapper.eq("problem_id", problemId); Problem problem = problemEntityService.getOne(problemQueryWrapper, false); if (problem.getAuth() == 2) { throw new StatusForbiddenException("错误!当前题目不可提交!"); } boolean isRoot = SecurityUtils.getSubject().hasRole("root"); if (problem.getIsGroup()) { if (!isRoot && !groupValidator.isGroupMember(userRolesVo.getUid(), problem.getGid())) { throw new StatusForbiddenException("对不起,您并非该题目所属的团队内成员,无权进行提交!"); } } judge.setCpid(0L) .setPid(problem.getId()) .setDisplayPid(problem.getProblemId()); // 将新提交数据插入数据库 judgeEntityService.save(judge); } @Transactional(rollbackFor = Exception.class)
package top.hcode.hoj.manager.oj; /** * @Author: Himit_ZH * @Date: 2022/3/11 14:29 * @Description: */ @Component public class BeforeDispatchInitManager { @Resource private ContestEntityService contestEntityService; @Resource private ContestRecordEntityService contestRecordEntityService; @Resource private ContestProblemEntityService contestProblemEntityService; @Resource private JudgeEntityService judgeEntityService; @Resource private ProblemEntityService problemEntityService; @Resource private TrainingEntityService trainingEntityService; @Resource private TrainingProblemEntityService trainingProblemEntityService; @Resource private TrainingRecordEntityService trainingRecordEntityService; @Resource private TrainingValidator trainingValidator; @Resource private ContestValidator contestValidator; @Autowired private GroupValidator groupValidator; public void initCommonSubmission(String problemId, Judge judge) throws StatusForbiddenException { Session session = SecurityUtils.getSubject().getSession(); UserRolesVo userRolesVo = (UserRolesVo) session.getAttribute("userInfo"); QueryWrapper<Problem> problemQueryWrapper = new QueryWrapper<>(); problemQueryWrapper.eq("problem_id", problemId); Problem problem = problemEntityService.getOne(problemQueryWrapper, false); if (problem.getAuth() == 2) { throw new StatusForbiddenException("错误!当前题目不可提交!"); } boolean isRoot = SecurityUtils.getSubject().hasRole("root"); if (problem.getIsGroup()) { if (!isRoot && !groupValidator.isGroupMember(userRolesVo.getUid(), problem.getGid())) { throw new StatusForbiddenException("对不起,您并非该题目所属的团队内成员,无权进行提交!"); } } judge.setCpid(0L) .setPid(problem.getId()) .setDisplayPid(problem.getProblemId()); // 将新提交数据插入数据库 judgeEntityService.save(judge); } @Transactional(rollbackFor = Exception.class)
public void initContestSubmission(Long cid, String displayId, UserRolesVo userRolesVo, Judge judge) throws StatusNotFoundException, StatusForbiddenException {
5
2023-12-03 14:15:51+00:00
16k
yichenhsiaonz/EscAIpe-room-final
src/main/java/nz/ac/auckland/se206/controllers/KitchenController.java
[ { "identifier": "App", "path": "src/main/java/nz/ac/auckland/se206/App.java", "snippet": "public class App extends Application {\n\n private static Scene scene;\n public static ControlRoomController controlRoomController;\n public static LabController labController;\n public static KitchenController...
import java.io.IOException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.shape.Circle; import nz.ac.auckland.se206.App; import nz.ac.auckland.se206.GameState; import nz.ac.auckland.se206.SceneManager.AppUi; import nz.ac.auckland.se206.TextToSpeechManager;
12,401
String message = "Looks like the toaster is toast."; SharedElements.appendChat(message); SharedElements.chatBubbleSpeak(message); }; GameState.setOnMovementComplete(toasterRunnable); GameState.startMoving(); } else { Runnable toasterRunnable = () -> { System.out.println("toaster clicked"); // put notification in chat box String message = "This toaster looks like it has been modified"; SharedElements.appendChat(message); SharedElements.chatBubbleSpeak(message); }; GameState.setOnMovementComplete(toasterRunnable); GameState.startMoving(); } } @FXML public void onToasterHovered(MouseEvent event) { toasterGlow.setVisible(true); } @FXML public void onToasterUnhovered(MouseEvent event) { toasterGlow.setVisible(false); } /** * Handles the click event on the open fridge. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onFridgeOpenClicked(MouseEvent event) { // move character to fridge marker position GameState.goTo(fridgeMarker.getLayoutX(), fridgeMarker.getLayoutY(), character, running); Runnable openFridgeRunnable = () -> { System.out.println("open fridge clicked"); // put notification in chat box SharedElements.appendChat("There's nothing left in the fridge."); }; GameState.setOnMovementComplete(openFridgeRunnable); GameState.startMoving(); } @FXML public void onFridgeOpenHovered(MouseEvent event) { fridgeOpenGlow.setVisible(true); } @FXML public void onFridgeOpenUnhovered(MouseEvent event) { fridgeOpenGlow.setVisible(false); } /** * Handles the click event on the closed fridge. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onFridgeClosedClicked(MouseEvent event) { try { // move character to fridge marker position GameState.goTo(fridgeMarker.getLayoutX(), fridgeMarker.getLayoutY(), character, running); // flag that the current puzzle is the toast puzzle GameState.setPuzzleToast(); Runnable closedFridgeRunnable = () -> { GameState.playSound("/sounds/pick-up-item.m4a"); // change fridge image to open fridge fridgeClosed.setVisible(false); fridgeOpen.setVisible(true); // change floor hitbox to account for open fridge floor.setImage(new Image("images/Kitchen/floorfridgeopen.png")); // put notification in chat box SharedElements.appendChat("You find a stale loaf of bread in the fridge."); // flag that the user has bread GameState.hasBread = true; // add bread to inventory GameState.addItem(GameState.Items.BREAD_UNTOASTED); System.out.println("closed fridge clicked"); }; GameState.setOnMovementComplete(closedFridgeRunnable); GameState.startMoving(); } catch (Exception e) { System.out.println("get bread error"); e.printStackTrace(); } } @FXML public void onFridgeClosedHovered(MouseEvent event) { fridgeClosedGlow.setVisible(true); } @FXML public void onFridgeClosedUnhovered(MouseEvent event) { fridgeClosedGlow.setVisible(false); } // get image of loading AI public ImageView getLoadingAi() { return loadingAi; } // get image of talking AI public ImageView getTalkingAi() { return talkingAi; } @FXML private void onBackToMenu(ActionEvent event) throws IOException {
package nz.ac.auckland.se206.controllers; /** Controller class for the room view. */ public class KitchenController { public static KitchenController instance; @FXML private AnchorPane contentPane; @FXML private ImageView floor; @FXML private ImageView character; @FXML private ImageView running; @FXML private ImageView doorGlow; @FXML private ImageView toasterGlow; @FXML private ImageView fridgeClosedGlow; @FXML private ImageView fridgeOpenGlow; @FXML private ImageView fridgeClosed; @FXML private ImageView fridgeOpen; @FXML private HBox dialogueHorizontalBox; @FXML private VBox bottomVerticalBox; @FXML private VBox hintVerticalBox; @FXML private Pane inventoryPane; @FXML private Circle doorMarker; @FXML private Circle toasterMarker; @FXML private Circle fridgeMarker; @FXML private AnchorPane room; @FXML private ImageView neutralAi; @FXML private ImageView loadingAi; @FXML private ImageView talkingAi; @FXML private Button muteButton; /** Initializes the room view, it is called when the room loads. */ public void initialize() { SharedElements.initialize( room, bottomVerticalBox, inventoryPane, dialogueHorizontalBox, muteButton, contentPane); // get door marker position int doorMarkerX = (int) doorMarker.getLayoutX(); int doorMarkerY = (int) doorMarker.getLayoutY(); // move character to door marker position GameState.goToInstant(doorMarkerX, doorMarkerY, character, running); room.setOpacity(0); instance = this; } /** * Handles the key pressed event. * * @param event the key event */ @FXML public void onKeyPressed(KeyEvent event) { System.out.println("key " + event.getCode() + " pressed"); } /** * Handles the key released event. * * @param event the key event */ @FXML public void onKeyReleased(KeyEvent event) { System.out.println("key " + event.getCode() + " released"); } /** * 'Consumes' the mouse event, preventing it from being registered. * * @param event the mouse event */ @FXML public void consumeMouseEvent(MouseEvent event) { System.out.println("mouse event consumed"); System.out.println(event.getSource()); event.consume(); } /** * Handles the mouse click event on the room, moving the character to the clicked location. * * @param event the mouse event */ @FXML public void onMoveCharacter(MouseEvent event) { // create click indicator GameState.onCharacterMovementClick(event, room); // get mouse position double mouseX = event.getX(); double mouseY = event.getY(); // move character to mouse position GameState.goTo(mouseX, mouseY, character, running); GameState.startMoving(); } /** * Handles the click event on the door. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onDoorClicked(MouseEvent event) throws IOException { // move character to door marker position GameState.goTo(doorMarker.getLayoutX(), doorMarker.getLayoutY(), character, running); // load the control room scene after movement animation is finished Runnable leaveRoom = () -> { GameState.playSound("/sounds/door-opening.m4a"); GameState.fadeOut(room); Runnable loadControlRoom = () -> { try { App.setRoot(AppUi.CONTROL_ROOM); ControlRoomController.instance.fadeIn(); } catch (IOException e) { e.printStackTrace(); } }; GameState.delayRun(loadControlRoom, 1); }; GameState.setOnMovementComplete(leaveRoom); GameState.startMoving(); } // add glow highlight to door when hover @FXML public void onDoorHovered(MouseEvent event) { doorGlow.setVisible(true); } @FXML public void onDoorUnhovered(MouseEvent event) { doorGlow.setVisible(false); } /** * Handles the click event on the toaster. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onToasterClicked(MouseEvent event) { // move character to toaster marker position GameState.goTo(toasterMarker.getLayoutX(), toasterMarker.getLayoutY(), character, running); // set active puzzle to toaster puzzle GameState.setPuzzleToast(); if (GameState.hasBread && !GameState.hasToast) { // run if the user has bread and doesn't have toast Runnable toastFinish = () -> { GameState.playSound("/sounds/toaster.mp3"); System.out.println("toaster clicked"); // put notification in chat box SharedElements.appendChat("A charred slice of toast pops out of the toaster"); // add toasted bread to inventory GameState.addItem(GameState.Items.BREAD_TOASTED); // flag that the user has toast GameState.hasToast = true; // flag that the toaster puzzle has been completed // so that no more hints are given for this puzzle GameState.toasterPuzzleHints = false; }; Runnable waitForToast = () -> { GameState.playSound("/sounds/timer.mp3"); SharedElements.appendChat("Sparks fly out of the toaster as it toasts the bread"); GameState.delayRun(toastFinish, 4); }; Runnable putInToast = () -> { GameState.playSound("/sounds/timer.mp3"); System.out.println("toaster clicked"); // remove bread from inventory GameState.removeItem(GameState.Items.BREAD_UNTOASTED); // put notification in chat box SharedElements.appendChat("You put a slice of bread in the toaster"); // flag that the user has no bread GameState.hasBread = false; GameState.delayRun(waitForToast, 2); }; GameState.setOnMovementComplete(putInToast); GameState.startMoving(); } else if (GameState.hasToast) { // run if the user has toast already Runnable toasterRunnable = () -> { System.out.println("toaster clicked"); // put notification in chat box String message = "Looks like the toaster is toast."; SharedElements.appendChat(message); SharedElements.chatBubbleSpeak(message); }; GameState.setOnMovementComplete(toasterRunnable); GameState.startMoving(); } else { Runnable toasterRunnable = () -> { System.out.println("toaster clicked"); // put notification in chat box String message = "This toaster looks like it has been modified"; SharedElements.appendChat(message); SharedElements.chatBubbleSpeak(message); }; GameState.setOnMovementComplete(toasterRunnable); GameState.startMoving(); } } @FXML public void onToasterHovered(MouseEvent event) { toasterGlow.setVisible(true); } @FXML public void onToasterUnhovered(MouseEvent event) { toasterGlow.setVisible(false); } /** * Handles the click event on the open fridge. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onFridgeOpenClicked(MouseEvent event) { // move character to fridge marker position GameState.goTo(fridgeMarker.getLayoutX(), fridgeMarker.getLayoutY(), character, running); Runnable openFridgeRunnable = () -> { System.out.println("open fridge clicked"); // put notification in chat box SharedElements.appendChat("There's nothing left in the fridge."); }; GameState.setOnMovementComplete(openFridgeRunnable); GameState.startMoving(); } @FXML public void onFridgeOpenHovered(MouseEvent event) { fridgeOpenGlow.setVisible(true); } @FXML public void onFridgeOpenUnhovered(MouseEvent event) { fridgeOpenGlow.setVisible(false); } /** * Handles the click event on the closed fridge. * * @param event the mouse event * @throws IOException if there is an error loading the chat view */ @FXML public void onFridgeClosedClicked(MouseEvent event) { try { // move character to fridge marker position GameState.goTo(fridgeMarker.getLayoutX(), fridgeMarker.getLayoutY(), character, running); // flag that the current puzzle is the toast puzzle GameState.setPuzzleToast(); Runnable closedFridgeRunnable = () -> { GameState.playSound("/sounds/pick-up-item.m4a"); // change fridge image to open fridge fridgeClosed.setVisible(false); fridgeOpen.setVisible(true); // change floor hitbox to account for open fridge floor.setImage(new Image("images/Kitchen/floorfridgeopen.png")); // put notification in chat box SharedElements.appendChat("You find a stale loaf of bread in the fridge."); // flag that the user has bread GameState.hasBread = true; // add bread to inventory GameState.addItem(GameState.Items.BREAD_UNTOASTED); System.out.println("closed fridge clicked"); }; GameState.setOnMovementComplete(closedFridgeRunnable); GameState.startMoving(); } catch (Exception e) { System.out.println("get bread error"); e.printStackTrace(); } } @FXML public void onFridgeClosedHovered(MouseEvent event) { fridgeClosedGlow.setVisible(true); } @FXML public void onFridgeClosedUnhovered(MouseEvent event) { fridgeClosedGlow.setVisible(false); } // get image of loading AI public ImageView getLoadingAi() { return loadingAi; } // get image of talking AI public ImageView getTalkingAi() { return talkingAi; } @FXML private void onBackToMenu(ActionEvent event) throws IOException {
TextToSpeechManager.cutOff();
3
2023-12-02 04:57:43+00:00
16k
nageoffer/shortlink
project/src/main/java/com/nageoffer/shortlink/project/service/impl/ShortLinkStatsServiceImpl.java
[ { "identifier": "LinkAccessLogsDO", "path": "project/src/main/java/com/nageoffer/shortlink/project/dao/entity/LinkAccessLogsDO.java", "snippet": "@Data\n@TableName(\"t_link_access_logs\")\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class LinkAccessLogsDO extends BaseDO {\n\n /**\n ...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.nageoffer.shortlink.project.dao.entity.LinkAccessLogsDO; import com.nageoffer.shortlink.project.dao.entity.LinkAccessStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkDeviceStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkLocaleStatsDO; import com.nageoffer.shortlink.project.dao.entity.LinkNetworkStatsDO; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessLogsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkAccessStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkBrowserStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkDeviceStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkLocaleStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkNetworkStatsMapper; import com.nageoffer.shortlink.project.dao.mapper.LinkOsStatsMapper; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsAccessRecordReqDTO; import com.nageoffer.shortlink.project.dto.req.ShortLinkStatsReqDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessDailyRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsAccessRecordRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsBrowserRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsDeviceRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsLocaleCNRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsNetworkRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsOsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsTopIpRespDTO; import com.nageoffer.shortlink.project.dto.resp.ShortLinkStatsUvRespDTO; import com.nageoffer.shortlink.project.service.ShortLinkStatsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger;
12,070
.uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByShortLink = linkLocaleStatsMapper.listLocaleByShortLink(requestParam); int localeCnSum = listedLocaleByShortLink.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>();
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nageoffer.shortlink.project.service.impl; /** * 短链接监控接口实现层 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Service @RequiredArgsConstructor public class ShortLinkStatsServiceImpl implements ShortLinkStatsService { private final LinkAccessStatsMapper linkAccessStatsMapper; private final LinkLocaleStatsMapper linkLocaleStatsMapper; private final LinkAccessLogsMapper linkAccessLogsMapper; private final LinkBrowserStatsMapper linkBrowserStatsMapper; private final LinkOsStatsMapper linkOsStatsMapper; private final LinkDeviceStatsMapper linkDeviceStatsMapper; private final LinkNetworkStatsMapper linkNetworkStatsMapper; @Override public ShortLinkStatsRespDTO oneShortLinkStats(ShortLinkStatsReqDTO requestParam) { List<LinkAccessStatsDO> listStatsByShortLink = linkAccessStatsMapper.listStatsByShortLink(requestParam); if (CollUtil.isEmpty(listStatsByShortLink)) { return null; } // 基础访问数据 LinkAccessStatsDO pvUvUidStatsByShortLink = linkAccessLogsMapper.findPvUvUidStatsByShortLink(requestParam); // 基础访问详情 List<ShortLinkStatsAccessDailyRespDTO> daily = new ArrayList<>(); List<String> rangeDates = DateUtil.rangeToList(DateUtil.parse(requestParam.getStartDate()), DateUtil.parse(requestParam.getEndDate()), DateField.DAY_OF_MONTH).stream() .map(DateUtil::formatDate) .toList(); rangeDates.forEach(each -> listStatsByShortLink.stream() .filter(item -> Objects.equals(each, DateUtil.formatDate(item.getDate()))) .findFirst() .ifPresentOrElse(item -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(item.getPv()) .uv(item.getUv()) .uip(item.getUip()) .build(); daily.add(accessDailyRespDTO); }, () -> { ShortLinkStatsAccessDailyRespDTO accessDailyRespDTO = ShortLinkStatsAccessDailyRespDTO.builder() .date(each) .pv(0) .uv(0) .uip(0) .build(); daily.add(accessDailyRespDTO); })); // 地区访问详情(仅国内) List<ShortLinkStatsLocaleCNRespDTO> localeCnStats = new ArrayList<>(); List<LinkLocaleStatsDO> listedLocaleByShortLink = linkLocaleStatsMapper.listLocaleByShortLink(requestParam); int localeCnSum = listedLocaleByShortLink.stream() .mapToInt(LinkLocaleStatsDO::getCnt) .sum(); listedLocaleByShortLink.forEach(each -> { double ratio = (double) each.getCnt() / localeCnSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsLocaleCNRespDTO localeCNRespDTO = ShortLinkStatsLocaleCNRespDTO.builder() .cnt(each.getCnt()) .locale(each.getProvince()) .ratio(actualRatio) .build(); localeCnStats.add(localeCNRespDTO); }); // 小时访问详情 List<Integer> hourStats = new ArrayList<>(); List<LinkAccessStatsDO> listHourStatsByShortLink = linkAccessStatsMapper.listHourStatsByShortLink(requestParam); for (int i = 0; i < 24; i++) { AtomicInteger hour = new AtomicInteger(i); int hourCnt = listHourStatsByShortLink.stream() .filter(each -> Objects.equals(each.getHour(), hour.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); hourStats.add(hourCnt); } // 高频访问IP详情 List<ShortLinkStatsTopIpRespDTO> topIpStats = new ArrayList<>(); List<HashMap<String, Object>> listTopIpByShortLink = linkAccessLogsMapper.listTopIpByShortLink(requestParam); listTopIpByShortLink.forEach(each -> { ShortLinkStatsTopIpRespDTO statsTopIpRespDTO = ShortLinkStatsTopIpRespDTO.builder() .ip(each.get("ip").toString()) .cnt(Integer.parseInt(each.get("count").toString())) .build(); topIpStats.add(statsTopIpRespDTO); }); // 一周访问详情 List<Integer> weekdayStats = new ArrayList<>(); List<LinkAccessStatsDO> listWeekdayStatsByShortLink = linkAccessStatsMapper.listWeekdayStatsByShortLink(requestParam); for (int i = 1; i < 8; i++) { AtomicInteger weekday = new AtomicInteger(i); int weekdayCnt = listWeekdayStatsByShortLink.stream() .filter(each -> Objects.equals(each.getWeekday(), weekday.get())) .findFirst() .map(LinkAccessStatsDO::getPv) .orElse(0); weekdayStats.add(weekdayCnt); } // 浏览器访问详情 List<ShortLinkStatsBrowserRespDTO> browserStats = new ArrayList<>(); List<HashMap<String, Object>> listBrowserStatsByShortLink = linkBrowserStatsMapper.listBrowserStatsByShortLink(requestParam); int browserSum = listBrowserStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listBrowserStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / browserSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsBrowserRespDTO browserRespDTO = ShortLinkStatsBrowserRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .browser(each.get("browser").toString()) .ratio(actualRatio) .build(); browserStats.add(browserRespDTO); }); // 操作系统访问详情 List<ShortLinkStatsOsRespDTO> osStats = new ArrayList<>(); List<HashMap<String, Object>> listOsStatsByShortLink = linkOsStatsMapper.listOsStatsByShortLink(requestParam); int osSum = listOsStatsByShortLink.stream() .mapToInt(each -> Integer.parseInt(each.get("count").toString())) .sum(); listOsStatsByShortLink.forEach(each -> { double ratio = (double) Integer.parseInt(each.get("count").toString()) / osSum; double actualRatio = Math.round(ratio * 100.0) / 100.0; ShortLinkStatsOsRespDTO osRespDTO = ShortLinkStatsOsRespDTO.builder() .cnt(Integer.parseInt(each.get("count").toString())) .os(each.get("os").toString()) .ratio(actualRatio) .build(); osStats.add(osRespDTO); }); // 访客访问类型详情 List<ShortLinkStatsUvRespDTO> uvTypeStats = new ArrayList<>(); HashMap<String, Object> findUvTypeByShortLink = linkAccessLogsMapper.findUvTypeCntByShortLink(requestParam); int oldUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("oldUserCnt")) .map(Object::toString) .orElse("0") ); int newUserCnt = Integer.parseInt( Optional.ofNullable(findUvTypeByShortLink) .map(each -> each.get("newUserCnt")) .map(Object::toString) .orElse("0") ); int uvSum = oldUserCnt + newUserCnt; double oldRatio = (double) oldUserCnt / uvSum; double actualOldRatio = Math.round(oldRatio * 100.0) / 100.0; double newRatio = (double) newUserCnt / uvSum; double actualNewRatio = Math.round(newRatio * 100.0) / 100.0; ShortLinkStatsUvRespDTO newUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("newUser") .cnt(newUserCnt) .ratio(actualNewRatio) .build(); uvTypeStats.add(newUvRespDTO); ShortLinkStatsUvRespDTO oldUvRespDTO = ShortLinkStatsUvRespDTO.builder() .uvType("oldUser") .cnt(oldUserCnt) .ratio(actualOldRatio) .build(); uvTypeStats.add(oldUvRespDTO); // 访问设备类型详情 List<ShortLinkStatsDeviceRespDTO> deviceStats = new ArrayList<>();
List<LinkDeviceStatsDO> listDeviceStatsByShortLink = linkDeviceStatsMapper.listDeviceStatsByShortLink(requestParam);
2
2023-11-19 16:04:32+00:00
16k
TongchengOpenSource/ckibana
src/main/java/com/ly/ckibana/strategy/aggs/Aggregation.java
[ { "identifier": "Constants", "path": "src/main/java/com/ly/ckibana/constants/Constants.java", "snippet": "public class Constants {\n\n public static final String HEADER_ELASTICSEARCH = \"Elasticsearch\";\n\n public static final String HEADER_X_ELASTIC_PRODUCT = \"X-elastic-product\";\n\n public...
import com.alibaba.fastjson2.JSONObject; import com.ly.ckibana.constants.Constants; import com.ly.ckibana.constants.SqlConstants; import com.ly.ckibana.model.compute.Range; import com.ly.ckibana.model.compute.aggregation.AggsParam; import com.ly.ckibana.model.compute.aggregation.bucket.Bucket; import com.ly.ckibana.model.enums.AggBucketsName; import com.ly.ckibana.model.enums.AggCategory; import com.ly.ckibana.model.enums.AggType; import com.ly.ckibana.model.request.CkRequest; import com.ly.ckibana.model.request.CkRequestContext; import com.ly.ckibana.model.request.CkRequestContext.SampleParam; import com.ly.ckibana.strategy.aggs.converter.SqlConverter; import com.ly.ckibana.util.ProxyUtils; import lombok.Data; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors;
11,153
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * 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.ly.ckibana.strategy.aggs; /** * 聚合策略. * * @author zl */ @Data public class Aggregation { private AggType aggType; private String aggName; /** * query_string中的查询条件. */ private String commonQuery; /** * true返回hash map格式,否则返回list格式. */ private boolean keyed; /** * 用于agg数据内存计算. */ private int aggDepth; /** * 下一层aggs. */ private List<Aggregation> subAggs; /** * 同一层aggs. */ private List<Aggregation> peerAggs; private Integer size; /** * 聚合的列. */ private String field; /** * 聚合的列的ck类型. */ private String fieldType; /** * 聚合所属的大类,用于计算区分. */ private AggCategory aggCategory = AggCategory.NOT_MATH; /** * 聚合结果返回map的字段名. */ private AggBucketsName aggBucketsName; public Aggregation() { } public Aggregation(AggType aggType, String aggName, String commonQuery, boolean keyed, int aggDepth, String field, String fieldType, AggBucketsName aggBucketsName) { this.aggType = aggType; this.aggName = aggName; this.commonQuery = commonQuery; this.keyed = keyed; this.aggDepth = aggDepth; this.field = field; this.fieldType = fieldType; this.aggBucketsName = aggBucketsName; } /** * 从agg配置构建aggStrategy. */ public Aggregation(AggsParam aggsParam) { this(aggsParam.getAggType(), aggsParam.getAggName(), aggsParam.getCommonQuery(), aggsParam.isKeyed(), aggsParam.getDepth(), aggsParam.getField(), aggsParam.getFieldType(), aggsParam.getAggBucketsName()); } public Aggregation generate(AggsParam aggsParam) { return new Aggregation(aggsParam); } /** * 聚合中field对应的alias. * * @return String */ public String queryFieldName() { return getAggName() + SqlConstants.QUERY_NAME_SEPARATOR + getField(); } /** * 聚合中count对应的alias. * * @return String */ public String queryAggCountName() { return getAggName() + SqlConstants.QUERY_NAME_SEPARATOR + SqlConstants.CK_COUNT_NAME; } /** * 解析对应agg对应的bucket结构. * * @param obj obj * @return bucket */ public Bucket buildResultBucket(JSONObject obj) { return null; } /** * 解析用于拼接ck sql的各部分sql part. * * @param ckRequestContext ckRequestContext * @return CkRequest */ public CkRequest buildCkRequest(CkRequestContext ckRequestContext) { CkRequest result = ProxyUtils.buildCkRequest(ckRequestContext); buildGroupSql(result); buildOrderBySql(result); double sample = getSample(ckRequestContext.getSampleParam()); buildSelectSql(sample, result, ckRequestContext); buildWhereSql(result, ckRequestContext, sample); //按代理配置设置默认limit if (StringUtils.isEmpty(result.getLimit()) && ckRequestContext.getMaxResultRow() > 0) { result.limit(ckRequestContext.getMaxResultRow()); } return result; } /** * 获取采样率. */ private double getSample(SampleParam sampleParam) { double sample = Constants.DEFAULT_NO_SAMPLE; if (sampleParam != null && sampleParam.getSampleTotalCount() > sampleParam.getSampleCountMaxThreshold()) { sample = Math.max(0.01, Double.parseDouble(String.format("%.5f", sampleParam.getSampleCountMaxThreshold() * 1.00 / sampleParam.getSampleTotalCount()))); } return sample; } /** * 计算group sql. * * @param ckRequest ckRequest */ private void buildGroupSql(CkRequest ckRequest) { List<String> groupBy = collectGroupBy(); ckRequest.initGroupBy(String.join(",", groupBy)); } /** * 解析group by. * * @return List */ public List<String> collectGroupBy() { List<String> result = new ArrayList<>(buildGroupBySql()); if (CollectionUtils.isNotEmpty(getPeerAggs())) { for (Aggregation each : getPeerAggs()) { result.addAll(each.collectGroupBy()); } } if (CollectionUtils.isNotEmpty(getSubAggs()) && !isIgnoreSubAggCondition()) { for (Aggregation each : getSubAggs()) { result.addAll(each.collectGroupBy()); } } return result; } /** * 目前仅针对range+子terms,terms+子terms. * * @return boolean */ public boolean isIgnoreSubAggCondition() { return (AggType.RANGE.equals(this.aggType) || AggType.TERMS.equals(this.aggType)) && CollectionUtils.isNotEmpty(getSubAggs()) && getSubAggs().stream().filter(v -> AggType.TERMS.equals(v.getAggType())).count() > 0; } public List<String> buildGroupBySql() { return new ArrayList<>(); } /** * 计算select. * * @param ckRequest ckRequest * @param ckRequestContext ckRequestContext */ private void buildSelectSql(double sample, CkRequest ckRequest, CkRequestContext ckRequestContext) {
/* * Copyright (c) 2023 LY.com All Rights Reserved. * * 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.ly.ckibana.strategy.aggs; /** * 聚合策略. * * @author zl */ @Data public class Aggregation { private AggType aggType; private String aggName; /** * query_string中的查询条件. */ private String commonQuery; /** * true返回hash map格式,否则返回list格式. */ private boolean keyed; /** * 用于agg数据内存计算. */ private int aggDepth; /** * 下一层aggs. */ private List<Aggregation> subAggs; /** * 同一层aggs. */ private List<Aggregation> peerAggs; private Integer size; /** * 聚合的列. */ private String field; /** * 聚合的列的ck类型. */ private String fieldType; /** * 聚合所属的大类,用于计算区分. */ private AggCategory aggCategory = AggCategory.NOT_MATH; /** * 聚合结果返回map的字段名. */ private AggBucketsName aggBucketsName; public Aggregation() { } public Aggregation(AggType aggType, String aggName, String commonQuery, boolean keyed, int aggDepth, String field, String fieldType, AggBucketsName aggBucketsName) { this.aggType = aggType; this.aggName = aggName; this.commonQuery = commonQuery; this.keyed = keyed; this.aggDepth = aggDepth; this.field = field; this.fieldType = fieldType; this.aggBucketsName = aggBucketsName; } /** * 从agg配置构建aggStrategy. */ public Aggregation(AggsParam aggsParam) { this(aggsParam.getAggType(), aggsParam.getAggName(), aggsParam.getCommonQuery(), aggsParam.isKeyed(), aggsParam.getDepth(), aggsParam.getField(), aggsParam.getFieldType(), aggsParam.getAggBucketsName()); } public Aggregation generate(AggsParam aggsParam) { return new Aggregation(aggsParam); } /** * 聚合中field对应的alias. * * @return String */ public String queryFieldName() { return getAggName() + SqlConstants.QUERY_NAME_SEPARATOR + getField(); } /** * 聚合中count对应的alias. * * @return String */ public String queryAggCountName() { return getAggName() + SqlConstants.QUERY_NAME_SEPARATOR + SqlConstants.CK_COUNT_NAME; } /** * 解析对应agg对应的bucket结构. * * @param obj obj * @return bucket */ public Bucket buildResultBucket(JSONObject obj) { return null; } /** * 解析用于拼接ck sql的各部分sql part. * * @param ckRequestContext ckRequestContext * @return CkRequest */ public CkRequest buildCkRequest(CkRequestContext ckRequestContext) { CkRequest result = ProxyUtils.buildCkRequest(ckRequestContext); buildGroupSql(result); buildOrderBySql(result); double sample = getSample(ckRequestContext.getSampleParam()); buildSelectSql(sample, result, ckRequestContext); buildWhereSql(result, ckRequestContext, sample); //按代理配置设置默认limit if (StringUtils.isEmpty(result.getLimit()) && ckRequestContext.getMaxResultRow() > 0) { result.limit(ckRequestContext.getMaxResultRow()); } return result; } /** * 获取采样率. */ private double getSample(SampleParam sampleParam) { double sample = Constants.DEFAULT_NO_SAMPLE; if (sampleParam != null && sampleParam.getSampleTotalCount() > sampleParam.getSampleCountMaxThreshold()) { sample = Math.max(0.01, Double.parseDouble(String.format("%.5f", sampleParam.getSampleCountMaxThreshold() * 1.00 / sampleParam.getSampleTotalCount()))); } return sample; } /** * 计算group sql. * * @param ckRequest ckRequest */ private void buildGroupSql(CkRequest ckRequest) { List<String> groupBy = collectGroupBy(); ckRequest.initGroupBy(String.join(",", groupBy)); } /** * 解析group by. * * @return List */ public List<String> collectGroupBy() { List<String> result = new ArrayList<>(buildGroupBySql()); if (CollectionUtils.isNotEmpty(getPeerAggs())) { for (Aggregation each : getPeerAggs()) { result.addAll(each.collectGroupBy()); } } if (CollectionUtils.isNotEmpty(getSubAggs()) && !isIgnoreSubAggCondition()) { for (Aggregation each : getSubAggs()) { result.addAll(each.collectGroupBy()); } } return result; } /** * 目前仅针对range+子terms,terms+子terms. * * @return boolean */ public boolean isIgnoreSubAggCondition() { return (AggType.RANGE.equals(this.aggType) || AggType.TERMS.equals(this.aggType)) && CollectionUtils.isNotEmpty(getSubAggs()) && getSubAggs().stream().filter(v -> AggType.TERMS.equals(v.getAggType())).count() > 0; } public List<String> buildGroupBySql() { return new ArrayList<>(); } /** * 计算select. * * @param ckRequest ckRequest * @param ckRequestContext ckRequestContext */ private void buildSelectSql(double sample, CkRequest ckRequest, CkRequestContext ckRequestContext) {
List<SqlConverter> convertors = new ArrayList<>();
11
2023-11-21 09:12:07+00:00
16k
libgdx/gdx-particle-editor
core/src/main/java/com/ray3k/gdxparticleeditor/runnables/OpenRunnable.java
[ { "identifier": "FileDialogs", "path": "core/src/main/java/com/ray3k/gdxparticleeditor/FileDialogs.java", "snippet": "public class FileDialogs {\n public static Array<FileHandle> openMultipleDialog(String title, String defaultPath, String[] filterPatterns, String filterDescription) {\n //fix f...
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.scenes.scene2d.Touchable; import com.ray3k.gdxparticleeditor.FileDialogs; import com.ray3k.gdxparticleeditor.Settings; import com.ray3k.gdxparticleeditor.Utils; import com.ray3k.gdxparticleeditor.undo.UndoManager; import com.ray3k.gdxparticleeditor.widgets.poptables.PopConfirmLoad; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.ray3k.gdxparticleeditor.Core.*; import static com.ray3k.gdxparticleeditor.Settings.*; import static com.ray3k.gdxparticleeditor.Utils.showToast; import static com.ray3k.gdxparticleeditor.widgets.panels.EffectEmittersPanel.effectEmittersPanel; import static com.ray3k.gdxparticleeditor.widgets.panels.EmitterPropertiesPanel.emitterPropertiesPanel;
13,547
package com.ray3k.gdxparticleeditor.runnables; public class OpenRunnable implements Runnable { private static boolean open; @Override public void run () { if (open) return; if (unsavedChangesMade) { var saveFirstRunnable = new SaveRunnable(); var saveAsFirstRunnable = new SaveAsRunnable(); saveFirstRunnable.setSaveAsRunnable(saveAsFirstRunnable); saveAsFirstRunnable.setSaveRunnable(saveFirstRunnable); saveFirstRunnable.setOnCompletionRunnable(this); var pop = new PopConfirmLoad(saveFirstRunnable, () -> { unsavedChangesMade = false; OpenRunnable.this.run(); }); pop.show(foregroundStage); return; } ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -> { open = true; stage.getRoot().setTouchable(Touchable.disabled); if (effectEmittersPanel == null || emitterPropertiesPanel == null) return; var useFileExtension = preferences.getBoolean(NAME_PRESUME_FILE_EXTENSION, DEFAULT_PRESUME_FILE_EXTENSION); var filterPatterns = useFileExtension ? new String[] {"p"} : null; var fileHandle = FileDialogs.openDialog("Open", getDefaultSavePath(), filterPatterns, "Particle files (*.p)"); if (fileHandle != null) { defaultFileName = fileHandle.name();
package com.ray3k.gdxparticleeditor.runnables; public class OpenRunnable implements Runnable { private static boolean open; @Override public void run () { if (open) return; if (unsavedChangesMade) { var saveFirstRunnable = new SaveRunnable(); var saveAsFirstRunnable = new SaveAsRunnable(); saveFirstRunnable.setSaveAsRunnable(saveAsFirstRunnable); saveAsFirstRunnable.setSaveRunnable(saveFirstRunnable); saveFirstRunnable.setOnCompletionRunnable(this); var pop = new PopConfirmLoad(saveFirstRunnable, () -> { unsavedChangesMade = false; OpenRunnable.this.run(); }); pop.show(foregroundStage); return; } ExecutorService service = Executors.newSingleThreadExecutor(); service.execute(() -> { open = true; stage.getRoot().setTouchable(Touchable.disabled); if (effectEmittersPanel == null || emitterPropertiesPanel == null) return; var useFileExtension = preferences.getBoolean(NAME_PRESUME_FILE_EXTENSION, DEFAULT_PRESUME_FILE_EXTENSION); var filterPatterns = useFileExtension ? new String[] {"p"} : null; var fileHandle = FileDialogs.openDialog("Open", getDefaultSavePath(), filterPatterns, "Particle files (*.p)"); if (fileHandle != null) { defaultFileName = fileHandle.name();
Settings.setDefaultSavePath(fileHandle.parent());
6
2023-11-24 15:58:20+00:00
16k
siam1026/siam-server
siam-system/system-provider/src/main/java/com/siam/system/modular/package_user/service_impl/MemberInviteRelationServiceImpl.java
[ { "identifier": "MemberSessionManager", "path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_user/auth/cache/MemberSessionManager.java", "snippet": "public interface MemberSessionManager {\n\n //缓存前缀\n String SESSION_PREFIX = \"LOGIN_USER:\";\n\n /**\n * 创建会话\n ...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.system.modular.package_user.auth.cache.MemberSessionManager; import com.siam.system.modular.package_user.entity.Member; import com.siam.system.modular.package_user.entity.MemberInviteRelation; import com.siam.system.modular.package_user.mapper.MemberInviteRelationMapper; import com.siam.system.modular.package_user.mapper.MemberMapper; import com.siam.system.modular.package_user.model.example.MemberInviteRelationExample; import com.siam.system.modular.package_user.model.param.MemberInviteRelationParam; import com.siam.system.modular.package_user.service.MemberBillingRecordService; import com.siam.system.modular.package_user.service.MemberInviteRelationService; import com.siam.system.modular.package_user.service.MemberService; import com.siam.system.util.TokenUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map;
11,722
package com.siam.system.modular.package_user.service_impl; @Service public class MemberInviteRelationServiceImpl implements MemberInviteRelationService { @Autowired private MemberInviteRelationMapper memberInviteRelationMapper; @Autowired private MemberMapper memberMapper; @Autowired private MemberService memberService; // @Autowired // private SettingService settingService; @Autowired private MemberBillingRecordService memberBillingRecordService; // @Autowired // private CouponsService couponsService; // // @Autowired // private CouponsMemberRelationService couponsMemberRelationService; @Autowired private MemberSessionManager memberSessionManager; @Override
package com.siam.system.modular.package_user.service_impl; @Service public class MemberInviteRelationServiceImpl implements MemberInviteRelationService { @Autowired private MemberInviteRelationMapper memberInviteRelationMapper; @Autowired private MemberMapper memberMapper; @Autowired private MemberService memberService; // @Autowired // private SettingService settingService; @Autowired private MemberBillingRecordService memberBillingRecordService; // @Autowired // private CouponsService couponsService; // // @Autowired // private CouponsMemberRelationService couponsMemberRelationService; @Autowired private MemberSessionManager memberSessionManager; @Override
public void insertSelective(MemberInviteRelation memberInviteRelation) {
2
2023-11-26 12:41:06+00:00
16k
3dcitydb/citydb-tool
citydb-cli/src/main/java/org/citydb/cli/exporter/ExportController.java
[ { "identifier": "ExecutionException", "path": "citydb-cli/src/main/java/org/citydb/cli/ExecutionException.java", "snippet": "public class ExecutionException extends Exception {\n\n public ExecutionException() {\n super();\n }\n\n public ExecutionException(String message) {\n super...
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Logger; import org.citydb.cli.ExecutionException; import org.citydb.cli.command.Command; import org.citydb.cli.option.ConfigOption; import org.citydb.cli.option.ConnectionOptions; import org.citydb.cli.option.OutputFileOptions; import org.citydb.cli.option.ThreadsOption; import org.citydb.cli.util.CommandHelper; import org.citydb.cli.util.QueryExecutor; import org.citydb.cli.util.QueryResult; import org.citydb.config.Config; import org.citydb.config.ConfigObject; import org.citydb.core.file.OutputFile; import org.citydb.database.DatabaseManager; import org.citydb.database.adapter.DatabaseAdapter; import org.citydb.io.IOAdapter; import org.citydb.io.IOAdapterManager; import org.citydb.io.OutputFileBuilder; import org.citydb.io.writer.FeatureWriter; import org.citydb.io.writer.WriteOptions; import org.citydb.io.writer.option.OutputFormatOptions; import org.citydb.io.writer.option.SpatialReference; import org.citydb.logging.LoggerManager; import org.citydb.model.feature.Feature; import org.citydb.operation.exporter.ExportOptions; import org.citydb.operation.exporter.Exporter; import org.citydb.operation.util.FeatureStatistics; import picocli.CommandLine; import java.util.concurrent.atomic.AtomicLong;
13,925
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * 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 org.citydb.cli.exporter; public abstract class ExportController implements Command { @CommandLine.Mixin protected OutputFileOptions outputFileOptions; @CommandLine.Option(names = "--fail-fast", description = "Fail fast on errors.") protected Boolean failFast; @CommandLine.Mixin protected ThreadsOption threadsOption; @CommandLine.Option(names = {"-q", "--query"}, paramLabel = "<select>", description = "SQL select statement to use as filter query.") private String query; @CommandLine.ArgGroup(exclusive = false, order = Integer.MAX_VALUE, heading = "Database connection options:%n") protected ConnectionOptions connectionOptions; @ConfigOption private Config config; protected final Logger logger = LoggerManager.getInstance().getLogger(ExportController.class); protected final CommandHelper helper = CommandHelper.newInstance(); private final Object lock = new Object(); private volatile boolean shouldRun = true; protected abstract IOAdapter getIOAdapter(IOAdapterManager ioManager) throws ExecutionException; protected abstract OutputFormatOptions getFormatOptions(ConfigObject<OutputFormatOptions> formatOptions) throws ExecutionException; protected void initialize(DatabaseManager databaseManager) throws ExecutionException {} @Override public Integer call() throws ExecutionException { return doExport() ? CommandLine.ExitCode.OK : CommandLine.ExitCode.SOFTWARE; } protected boolean doExport() throws ExecutionException { IOAdapterManager ioManager = helper.createIOAdapterManager(); IOAdapter ioAdapter = getIOAdapter(ioManager); OutputFileBuilder builder = OutputFileBuilder.newInstance() .defaultFileExtension(ioManager.getFileExtensions(ioAdapter).stream() .findFirst() .orElse(null)); DatabaseManager databaseManager = helper.connect(connectionOptions, config); QueryExecutor executor = QueryExecutor.of(databaseManager.getAdapter()); FeatureStatistics statistics = new FeatureStatistics(databaseManager.getAdapter()); helper.logIndexStatus(Level.INFO, databaseManager.getAdapter()); initialize(databaseManager); try (OutputFile outputFile = builder.newOutputFile(outputFileOptions.getFile()); FeatureWriter writer = ioAdapter.createWriter()) { Exporter exporter = Exporter.newInstance(); ExportOptions exportOptions = getExportOptions().setOutputFile(outputFile); WriteOptions writeOptions = getWriteOptions(databaseManager.getAdapter()); writeOptions.getFormatOptions().set(getFormatOptions(writeOptions.getFormatOptions())); AtomicLong counter = new AtomicLong(); logger.info("Exporting to " + ioManager.getFileFormat(ioAdapter) + " file " + outputFile.getFile() + "."); writer.initialize(outputFile, writeOptions); logger.info("Querying features matching the request..."); try (QueryResult result = executor.executeQuery(getQuery(databaseManager.getAdapter()))) { exporter.startSession(databaseManager.getAdapter(), exportOptions); while (shouldRun && result.hasNext()) { long id = result.getId(); exporter.exportFeature(id).whenComplete((feature, t) -> { if (feature != null) { try { writer.write(feature).whenComplete((success, e) -> { if (success == Boolean.TRUE) { statistics.add(feature); long count = counter.incrementAndGet(); if (count % 1000 == 0) { logger.info(count + " features exported."); } } else { abort(feature, id, e); } }); } catch (Throwable e) { abort(feature, id, e); } } else { abort(null, id, t); } }); } } finally { exporter.closeSession(); } } catch (Throwable e) { logger.warn("Database export aborted due to an error."); throw new ExecutionException("A fatal error has occurred during export.", e); } finally { databaseManager.disconnect(); if (!statistics.isEmpty()) { logger.info("Export summary:"); statistics.logFeatureSummary(Level.INFO); } else { logger.info("No features exported."); } } return shouldRun; }
/* * citydb-tool - Command-line tool for the 3D City Database * https://www.3dcitydb.org/ * * Copyright 2022-2023 * virtualcitysystems GmbH, Germany * https://vc.systems/ * * 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 org.citydb.cli.exporter; public abstract class ExportController implements Command { @CommandLine.Mixin protected OutputFileOptions outputFileOptions; @CommandLine.Option(names = "--fail-fast", description = "Fail fast on errors.") protected Boolean failFast; @CommandLine.Mixin protected ThreadsOption threadsOption; @CommandLine.Option(names = {"-q", "--query"}, paramLabel = "<select>", description = "SQL select statement to use as filter query.") private String query; @CommandLine.ArgGroup(exclusive = false, order = Integer.MAX_VALUE, heading = "Database connection options:%n") protected ConnectionOptions connectionOptions; @ConfigOption private Config config; protected final Logger logger = LoggerManager.getInstance().getLogger(ExportController.class); protected final CommandHelper helper = CommandHelper.newInstance(); private final Object lock = new Object(); private volatile boolean shouldRun = true; protected abstract IOAdapter getIOAdapter(IOAdapterManager ioManager) throws ExecutionException; protected abstract OutputFormatOptions getFormatOptions(ConfigObject<OutputFormatOptions> formatOptions) throws ExecutionException; protected void initialize(DatabaseManager databaseManager) throws ExecutionException {} @Override public Integer call() throws ExecutionException { return doExport() ? CommandLine.ExitCode.OK : CommandLine.ExitCode.SOFTWARE; } protected boolean doExport() throws ExecutionException { IOAdapterManager ioManager = helper.createIOAdapterManager(); IOAdapter ioAdapter = getIOAdapter(ioManager); OutputFileBuilder builder = OutputFileBuilder.newInstance() .defaultFileExtension(ioManager.getFileExtensions(ioAdapter).stream() .findFirst() .orElse(null)); DatabaseManager databaseManager = helper.connect(connectionOptions, config); QueryExecutor executor = QueryExecutor.of(databaseManager.getAdapter()); FeatureStatistics statistics = new FeatureStatistics(databaseManager.getAdapter()); helper.logIndexStatus(Level.INFO, databaseManager.getAdapter()); initialize(databaseManager); try (OutputFile outputFile = builder.newOutputFile(outputFileOptions.getFile()); FeatureWriter writer = ioAdapter.createWriter()) { Exporter exporter = Exporter.newInstance(); ExportOptions exportOptions = getExportOptions().setOutputFile(outputFile); WriteOptions writeOptions = getWriteOptions(databaseManager.getAdapter()); writeOptions.getFormatOptions().set(getFormatOptions(writeOptions.getFormatOptions())); AtomicLong counter = new AtomicLong(); logger.info("Exporting to " + ioManager.getFileFormat(ioAdapter) + " file " + outputFile.getFile() + "."); writer.initialize(outputFile, writeOptions); logger.info("Querying features matching the request..."); try (QueryResult result = executor.executeQuery(getQuery(databaseManager.getAdapter()))) { exporter.startSession(databaseManager.getAdapter(), exportOptions); while (shouldRun && result.hasNext()) { long id = result.getId(); exporter.exportFeature(id).whenComplete((feature, t) -> { if (feature != null) { try { writer.write(feature).whenComplete((success, e) -> { if (success == Boolean.TRUE) { statistics.add(feature); long count = counter.incrementAndGet(); if (count % 1000 == 0) { logger.info(count + " features exported."); } } else { abort(feature, id, e); } }); } catch (Throwable e) { abort(feature, id, e); } } else { abort(null, id, t); } }); } } finally { exporter.closeSession(); } } catch (Throwable e) { logger.warn("Database export aborted due to an error."); throw new ExecutionException("A fatal error has occurred during export.", e); } finally { databaseManager.disconnect(); if (!statistics.isEmpty()) { logger.info("Export summary:"); statistics.logFeatureSummary(Level.INFO); } else { logger.info("No features exported."); } } return shouldRun; }
protected String getQuery(DatabaseAdapter adapter) {
12
2023-11-19 12:29:54+00:00
16k
magmamaintained/Magma-1.12.2
src/main/java/com/destroystokyo/paper/event/profile/LookupProfileEvent.java
[ { "identifier": "PlayerProfile", "path": "src/main/java/com/destroystokyo/paper/profile/PlayerProfile.java", "snippet": "public interface PlayerProfile {\n\n /**\n * @return The players name, if set\n */\n @Nullable String getName();\n\n /**\n * Sets this profiles Name\n *\n ...
import com.destroystokyo.paper.profile.PlayerProfile; import com.mojang.authlib.GameProfile; import org.bukkit.Bukkit; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import javax.annotation.Nonnull;
12,813
package com.destroystokyo.paper.event.profile; /** * Allows a plugin to be notified anytime AFTER a Profile has been looked up from the Mojang API * This is an opportunity to view the response and potentially cache things. * * No guarantees are made about thread execution context for this event. If you need to know, check * event.isAsync() */ public class LookupProfileEvent extends Event { private static final HandlerList handlers = new HandlerList(); private final PlayerProfile profile; public LookupProfileEvent(@Nonnull PlayerProfile profile) {
package com.destroystokyo.paper.event.profile; /** * Allows a plugin to be notified anytime AFTER a Profile has been looked up from the Mojang API * This is an opportunity to view the response and potentially cache things. * * No guarantees are made about thread execution context for this event. If you need to know, check * event.isAsync() */ public class LookupProfileEvent extends Event { private static final HandlerList handlers = new HandlerList(); private final PlayerProfile profile; public LookupProfileEvent(@Nonnull PlayerProfile profile) {
super(!Bukkit.isPrimaryThread());
1
2023-11-22 11:25:51+00:00
16k
logaritex/assistant-api
src/test/java/com/logaritex/ai/api/samples/retrieval/KnowledgeRetrievalAssistant.java
[ { "identifier": "AssistantApi", "path": "src/main/java/com/logaritex/ai/api/AssistantApi.java", "snippet": "public class AssistantApi {\n\n\t/**\n\t * OpenAI assistant api beta marker.\n\t */\n\tpublic static final String OPEN_AI_BETA = \"OpenAI-Beta\";\n\n\t/**\n\t * OpenAI assistant api version.\n\t *...
import java.util.List; import java.util.Map; import com.logaritex.ai.api.AssistantApi; import com.logaritex.ai.api.Data; import com.logaritex.ai.api.Data.Message; import com.logaritex.ai.api.Data.Run; import com.logaritex.ai.api.FileApi; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.DefaultResourceLoader;
13,813
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.retrieval; /** * Knowledge Retrieval Tool - expends the knowledge of the Assistant: https://youtu.be/pq34V_V5j18?t=2014 * * This demo creates an Assistant instructed as a SpringBoot expert that can answer related question. The Retrieval Tool * is enabled to augment the Assistant with knowledge from outside its model, such as proprietary product information or * documents (e.g. the Spring Boot pdf docs). Once a doc files are uploaded and passed to the Assistant, OpenAI * automatically chunks the documents, index and store the embeddings, and implement vector search to retrieve relevant * content to answer user queries. * * The Retrieval Tool is likely a OpenAI, built-in, RAG solution with quite limited configuration options at the moment: * "Retrieval currently optimizes for quality by adding all relevant content to the context of model calls. We plan to * introduce other retrieval strategies to enable developers to choose a different tradeoff between retrieval quality * and model usage cost." * * @author Christian Tzolov */ public class KnowledgeRetrievalAssistant { private static final Log logger = LogFactory.getLog(KnowledgeRetrievalAssistant.class); public static void main(String[] args) throws InterruptedException { // Use your OpenAI api key to create the FileApi and the AssistantApi clients. logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY."); FileApi fileApi = new FileApi(System.getenv("OPENAI_API_KEY")); AssistantApi assistantApi = new AssistantApi(System.getenv("OPENAI_API_KEY")); logger.info("1. Upload the classpath:/spring-boot-reference.pdf file."); var resourceLoader = new DefaultResourceLoader();
/* * Copyright 2023-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.logaritex.ai.api.samples.retrieval; /** * Knowledge Retrieval Tool - expends the knowledge of the Assistant: https://youtu.be/pq34V_V5j18?t=2014 * * This demo creates an Assistant instructed as a SpringBoot expert that can answer related question. The Retrieval Tool * is enabled to augment the Assistant with knowledge from outside its model, such as proprietary product information or * documents (e.g. the Spring Boot pdf docs). Once a doc files are uploaded and passed to the Assistant, OpenAI * automatically chunks the documents, index and store the embeddings, and implement vector search to retrieve relevant * content to answer user queries. * * The Retrieval Tool is likely a OpenAI, built-in, RAG solution with quite limited configuration options at the moment: * "Retrieval currently optimizes for quality by adding all relevant content to the context of model calls. We plan to * introduce other retrieval strategies to enable developers to choose a different tradeoff between retrieval quality * and model usage cost." * * @author Christian Tzolov */ public class KnowledgeRetrievalAssistant { private static final Log logger = LogFactory.getLog(KnowledgeRetrievalAssistant.class); public static void main(String[] args) throws InterruptedException { // Use your OpenAI api key to create the FileApi and the AssistantApi clients. logger.info("Create FileApi and AssistantApi with your OPENAI_API_KEY."); FileApi fileApi = new FileApi(System.getenv("OPENAI_API_KEY")); AssistantApi assistantApi = new AssistantApi(System.getenv("OPENAI_API_KEY")); logger.info("1. Upload the classpath:/spring-boot-reference.pdf file."); var resourceLoader = new DefaultResourceLoader();
Data.File file = fileApi.uploadFile(
1
2023-11-25 18:52:37+00:00
16k
GregTech-Chinese-Community/EPCore
src/main/java/cn/gtcommunity/epimorphism/common/EPEventHandler.java
[ { "identifier": "Epimorphism", "path": "src/main/java/cn/gtcommunity/epimorphism/Epimorphism.java", "snippet": "@Mod(\n modid = \"epimorphism\",\n name = \"Epimorphism\",\n acceptedMinecraftVersions = \"[1.12.2,1.13)\",\n version = \"0.0.2-beta\",\n dependencies = \"re...
import cn.gtcommunity.epimorphism.Epimorphism; import cn.gtcommunity.epimorphism.api.capability.pollution.PollutionProvider; import cn.gtcommunity.epimorphism.api.fluids.EPMetaFluids; import cn.gtcommunity.epimorphism.api.unification.EPMaterials; import cn.gtcommunity.epimorphism.api.unification.OrePrefixAdditions; import cn.gtcommunity.epimorphism.common.items.EPToolItems; import gregtech.api.unification.material.event.MaterialEvent; import net.minecraft.util.ResourceLocation; import net.minecraft.world.chunk.Chunk; import net.minecraftforge.event.AttachCapabilitiesEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
11,309
package cn.gtcommunity.epimorphism.common; @Mod.EventBusSubscriber(modid = Epimorphism.MODID) public class EPEventHandler { @SubscribeEvent(priority = EventPriority.HIGH) public static void registerMaterials(MaterialEvent event) { EPMaterials.init(); EPMetaFluids.init(); OrePrefixAdditions.init(); EPToolItems.init(); } @SubscribeEvent public void attachChunkPollutionCapability(AttachCapabilitiesEvent<Chunk> event) {
package cn.gtcommunity.epimorphism.common; @Mod.EventBusSubscriber(modid = Epimorphism.MODID) public class EPEventHandler { @SubscribeEvent(priority = EventPriority.HIGH) public static void registerMaterials(MaterialEvent event) { EPMaterials.init(); EPMetaFluids.init(); OrePrefixAdditions.init(); EPToolItems.init(); } @SubscribeEvent public void attachChunkPollutionCapability(AttachCapabilitiesEvent<Chunk> event) {
event.addCapability(new ResourceLocation(Epimorphism.MODID, "pollution_cap"), new PollutionProvider());
1
2023-11-26 01:56:35+00:00
16k
ZayrexDev/ZPixiv
src/main/java/xyz/zcraft/zpixiv/ui/Main.java
[ { "identifier": "PixivClient", "path": "src/main/java/xyz/zcraft/zpixiv/api/PixivClient.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class PixivClient {\n private static final Logger LOG = LogManager.getLogger(PixivClient.class);\n private static final String userAgent = \"Mozilla/5.0 ...
import com.alibaba.fastjson2.JSONObject; import com.alibaba.fastjson2.JSONWriter; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.Pane; import javafx.stage.Stage; import javafx.stage.StageStyle; import lombok.Getter; import lombok.Setter; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import xyz.zcraft.zpixiv.api.PixivClient; import xyz.zcraft.zpixiv.ui.controller.InspectController; import xyz.zcraft.zpixiv.ui.controller.MainController; import xyz.zcraft.zpixiv.util.CachedImage; import xyz.zcraft.zpixiv.util.Config; import xyz.zcraft.zpixiv.util.ResourceLoader; import xyz.zcraft.zpixiv.util.SSLUtil; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Base64; import java.util.LinkedList; import java.util.Timer; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor;
11,447
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter public static final LinkedList<CachedImage> loginBackground = new LinkedList<>(); private static final Logger LOG = LogManager.getLogger(Main.class); @Getter private static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool(); @Getter private static final Timer timer = new Timer(); @Getter private static final Path dataPath = Path.of("data"); @Getter private static final Path configPath = dataPath.resolve("config.json"); @Getter private static final Path userPath = dataPath.resolve("user"); @Getter
package xyz.zcraft.zpixiv.ui; public class Main extends Application { @Getter public static final LinkedList<CachedImage> loginBackground = new LinkedList<>(); private static final Logger LOG = LogManager.getLogger(Main.class); @Getter private static final ThreadPoolExecutor tpe = (ThreadPoolExecutor) Executors.newCachedThreadPool(); @Getter private static final Timer timer = new Timer(); @Getter private static final Path dataPath = Path.of("data"); @Getter private static final Path configPath = dataPath.resolve("config.json"); @Getter private static final Path userPath = dataPath.resolve("user"); @Getter
private static Config config;
4
2023-11-23 15:08:16+00:00
16k
myzticbean/QSFindItemAddOn
src/main/java/io/myzticbean/finditemaddon/Handlers/CommandHandler/CmdExecutorHandler.java
[ { "identifier": "ConfigSetup", "path": "src/main/java/io/myzticbean/finditemaddon/ConfigUtil/ConfigSetup.java", "snippet": "public class ConfigSetup {\n\n private static File configFile;\n private static File sampleConfigFile;\n private static FileConfiguration configFileConfiguration;\n pri...
import io.myzticbean.finditemaddon.ConfigUtil.ConfigSetup; import io.myzticbean.finditemaddon.FindItemAddOn; import io.myzticbean.finditemaddon.Handlers.GUIHandler.Menus.FoundShopsMenu; import io.myzticbean.finditemaddon.Models.FoundShopItemModel; import io.myzticbean.finditemaddon.Utils.Defaults.PlayerPerms; import io.myzticbean.finditemaddon.Utils.JsonStorageUtils.HiddenShopStorageUtil; import io.myzticbean.finditemaddon.Utils.LoggerUtils; import io.myzticbean.finditemaddon.Utils.WarpUtils.WarpUtils; import me.kodysimpson.simpapi.colors.ColorTranslator; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.maxgamer.quickshop.api.shop.Shop; import java.util.List;
12,611
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_USE.value())) { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)); } boolean isBuying; if(StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE) || StringUtils.containsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE, " ")) { isBuying = buySellSubCommand.equalsIgnoreCase("to_buy"); } else { isBuying = buySellSubCommand.equalsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE); } if(itemArg.equalsIgnoreCase("*")) { List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().fetchAllItemsFromAllShops(isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> {
package io.myzticbean.finditemaddon.Handlers.CommandHandler; /** * Handler for different parameters of /finditem command * @author ronsane */ public class CmdExecutorHandler { /** * Handles the main shop search process * @param buySellSubCommand Whether player is buying or selling * @param commandSender Who is the command sender: console or player * @param itemArg Specifies Item ID or Item name */ public void handleShopSearch(String buySellSubCommand, CommandSender commandSender, String itemArg) { if (!(commandSender instanceof Player)) { LoggerUtils.logInfo("This command can only be run from in game"); } else { Player player = (Player) commandSender; if(player.hasPermission(PlayerPerms.FINDITEM_USE.value())) { if(!StringUtils.isEmpty(FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)) { player.sendMessage(ColorTranslator.translateColorCodes( FindItemAddOn.getConfigProvider().PLUGIN_PREFIX + FindItemAddOn.getConfigProvider().SHOP_SEARCH_LOADING_MSG)); } boolean isBuying; if(StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE) || StringUtils.containsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE, " ")) { isBuying = buySellSubCommand.equalsIgnoreCase("to_buy"); } else { isBuying = buySellSubCommand.equalsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_BUY_AUTOCOMPLETE); } if(itemArg.equalsIgnoreCase("*")) { List<FoundShopItemModel> searchResultList = FindItemAddOn.getQsApiInstance().fetchAllItemsFromAllShops(isBuying, player); if(searchResultList.size() > 0) { Bukkit.getScheduler().runTaskAsynchronously(FindItemAddOn.getInstance(), () -> {
FoundShopsMenu menu = new FoundShopsMenu(FindItemAddOn.getPlayerMenuUtility(player), searchResultList);
2
2023-11-22 11:36:01+00:00
16k
estkme-group/infineon-lpa-mirror
core/src/main/java/com/infineon/esim/lpa/core/worker/local/GetEuiccInfo2Worker.java
[ { "identifier": "EUICCInfo2", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/EUICCInfo2.java", "snippet": "public class EUICCInfo2 implements BerType, Serializable {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static class EuiccCiPKIdListForVerification implem...
import com.gsma.sgp.messages.rspdefinitions.EUICCInfo2; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.es10.Es10Interface; import com.infineon.esim.util.Log;
13,697
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.local; public class GetEuiccInfo2Worker { private static final String TAG = GetEuiccInfo2Worker.class.getName(); private final Es10Interface es10Interface; public GetEuiccInfo2Worker(Es10Interface es10Interface) { this.es10Interface = es10Interface; }
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.worker.local; public class GetEuiccInfo2Worker { private static final String TAG = GetEuiccInfo2Worker.class.getName(); private final Es10Interface es10Interface; public GetEuiccInfo2Worker(Es10Interface es10Interface) { this.es10Interface = es10Interface; }
public EuiccInfo getEuiccInfo2() throws Exception {
1
2023-11-22 07:46:30+00:00
16k
phamdung2209/FAP
src/main/java/com/func/StudentHandler/Add.java
[ { "identifier": "DateOfBirth", "path": "src/main/java/com/Date/DateOfBirth.java", "snippet": "public class DateOfBirth {\n private int day;\n private int month;\n private int year;\n\n public DateOfBirth() {\n }\n\n public DateOfBirth(int day, int month, int year) {\n this.day =...
import java.util.Scanner; import com.date.DateOfBirth; import com.persons.Administrator; import com.persons.Student;
11,332
package com.func.StudentHandler; public class Add { public Scanner scanner = new Scanner(System.in);
package com.func.StudentHandler; public class Add { public Scanner scanner = new Scanner(System.in);
public void aS(int option, Administrator admin) {
1
2023-11-23 18:42:19+00:00
16k
morihofi/acmeserver
src/main/java/de/morihofi/acmeserver/Main.java
[ { "identifier": "Config", "path": "src/main/java/de/morihofi/acmeserver/config/Config.java", "snippet": "public class Config implements Serializable {\n private List<ProvisionerConfig> provisioner;\n private KeyStoreParams keyStore;\n private ServerConfig server;\n private DatabaseConfig database;\n...
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import de.morihofi.acmeserver.config.Config; import de.morihofi.acmeserver.config.keyStoreHelpers.KeyStoreParams; import de.morihofi.acmeserver.config.certificateAlgorithms.AlgorithmParams; import de.morihofi.acmeserver.config.certificateAlgorithms.EcdsaAlgorithmParams; import de.morihofi.acmeserver.config.certificateAlgorithms.RSAAlgorithmParams; import de.morihofi.acmeserver.config.helper.AlgorithmParamsDeserializer; import de.morihofi.acmeserver.config.helper.KeyStoreParamsDeserializer; import de.morihofi.acmeserver.config.keyStoreHelpers.PKCS11KeyStoreParams; import de.morihofi.acmeserver.config.keyStoreHelpers.PKCS12KeyStoreParams; import de.morihofi.acmeserver.postsetup.PostSetup; import de.morihofi.acmeserver.tools.certificate.cryptoops.CryptoStoreManager; import de.morihofi.acmeserver.tools.certificate.cryptoops.ksconfig.PKCS11KeyStoreConfig; import de.morihofi.acmeserver.tools.certificate.cryptoops.ksconfig.PKCS12KeyStoreConfig; import de.morihofi.acmeserver.tools.certificate.generator.CertificateAuthorityGenerator; import de.morihofi.acmeserver.tools.certificate.generator.KeyPairGenerator; import de.morihofi.acmeserver.tools.cli.CLIArgument; import de.morihofi.acmeserver.tools.path.AppDirectoryHelper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider; import org.bouncycastle.operator.OperatorCreationException; import org.slf4j.bridge.SLF4JBridgeHandler; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Objects; import java.util.Properties;
13,714
private static void initializeCoreComponents() throws ClassNotFoundException, CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException { if (coreComponentsInitialized) { return; } initializeDatabaseDrivers(); { //Initialize KeyStore if (appConfig.getKeyStore() instanceof PKCS11KeyStoreParams pkcs11KeyStoreParams) { cryptoStoreManager = new CryptoStoreManager( new PKCS11KeyStoreConfig( Paths.get(pkcs11KeyStoreParams.getLibraryLocation()), pkcs11KeyStoreParams.getSlot(), pkcs11KeyStoreParams.getPassword() ) ); } if (appConfig.getKeyStore() instanceof PKCS12KeyStoreParams pkcs12KeyStoreParams) { cryptoStoreManager = new CryptoStoreManager( new PKCS12KeyStoreConfig( Paths.get(pkcs12KeyStoreParams.getLocation()), pkcs12KeyStoreParams.getPassword() ) ); } if (cryptoStoreManager == null) { throw new IllegalArgumentException("Could not create CryptoStoreManager, due to unsupported KeyStore configuration"); } coreComponentsInitialized = true; } } /** * Ensures that the necessary files directory and configuration file exist. * * @throws IOException If an I/O error occurs while creating directories or checking for the configuration file. */ private static void ensureFilesDirectoryExists(Path configPath) throws IOException { if (!Files.exists(FILES_DIR)) { log.info("First run detected, creating settings directory"); Files.createDirectories(FILES_DIR); } if (!Files.exists(configPath)) { log.fatal("No configuration was found. Please create a file called \"settings.json\" in \"{}\". Then try again", FILES_DIR.toAbsolutePath()); System.exit(1); } } /** * Loads build and Git metadata from resource files and populates corresponding variables. */ private static void loadBuildAndGitMetadata() { try (InputStream is = Main.class.getResourceAsStream("/build.properties")) { if (is != null) { Properties buildMetadataProperties = new Properties(); buildMetadataProperties.load(is); buildMetadataVersion = buildMetadataProperties.getProperty("build.version"); buildMetadataBuildTime = buildMetadataProperties.getProperty("build.date") + " UTC"; } else { log.warn("Unable to load build metadata"); } } catch (Exception e) { log.error("Unable to load build metadata", e); } try (InputStream is = Main.class.getResourceAsStream("/git.properties")) { if (is != null) { Properties gitMetadataProperties = new Properties(); gitMetadataProperties.load(is); buildMetadataGitCommit = gitMetadataProperties.getProperty("git.commit.id.full"); } else { log.warn("Unable to load git metadata"); } } catch (Exception e) { log.error("Unable to load git metadata", e); } } /** * Initializes database drivers for MariaDB and H2. * * @throws ClassNotFoundException If a database driver class is not found. */ private static void initializeDatabaseDrivers() throws ClassNotFoundException { log.info("Loading MariaDB JDBC driver"); Class.forName("org.mariadb.jdbc.Driver"); log.info("Loading H2 JDBC driver"); Class.forName("org.h2.Driver"); } /** * Initializes the Certificate Authority (CA) by generating or loading the CA certificate and key pair. * * @throws NoSuchAlgorithmException If the specified algorithm is not available. * @throws CertificateException If an issue occurs during certificate generation or loading. * @throws IOException If an I/O error occurs while creating directories or writing files. * @throws OperatorCreationException If there's an issue with operator creation during certificate generation. * @throws NoSuchProviderException If the specified security provider is not available. * @throws InvalidAlgorithmParameterException If there's an issue with algorithm parameters during key pair generation. */ static void initializeCA(CryptoStoreManager cryptoStoreManager) throws NoSuchAlgorithmException, CertificateException, IOException, OperatorCreationException, NoSuchProviderException, InvalidAlgorithmParameterException, KeyStoreException { KeyStore caKeyStore = cryptoStoreManager.getKeyStore(); if (!caKeyStore.containsAlias(CryptoStoreManager.KEYSTORE_ALIAS_ROOTCA)) { // Create CA KeyPair caKeyPair = null; if (appConfig.getRootCA().getAlgorithm() instanceof RSAAlgorithmParams rsaParams) { log.info("Using RSA algorithm"); log.info("Generating RSA {} bit Key Pair for Root CA", rsaParams.getKeySize());
package de.morihofi.acmeserver; public class Main { /** * Logger */ public static final Logger log = LogManager.getLogger(Main.class); /** * `serverdata` directory as an absolute path */ public static final Path FILES_DIR = Paths.get(Objects.requireNonNull(AppDirectoryHelper.getAppDirectory())).resolve("serverdata").toAbsolutePath(); public static CryptoStoreManager cryptoStoreManager; //Build Metadata public static String buildMetadataVersion; public static String buildMetadataBuildTime; public static String buildMetadataGitCommit; public static Config appConfig; public static enum MODE { NORMAL, POSTSETUP, KEYSTORE_MIGRATION_PEM2KS } public static MODE selectedMode = MODE.NORMAL; public static void main(String[] args) throws Exception { Gson configGson = new GsonBuilder() .registerTypeAdapter(AlgorithmParams.class, new AlgorithmParamsDeserializer()) .registerTypeAdapter(KeyStoreParams.class, new KeyStoreParamsDeserializer()) .create(); printBanner(); System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager"); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); //Register Bouncy Castle Provider log.info("Register Bouncy Castle Security Provider"); Security.addProvider(new BouncyCastleProvider()); log.info("Register Bouncy Castle JSSE Security Provider"); Security.addProvider(new BouncyCastleJsseProvider()); log.info("Initializing directories"); Path configPath = FILES_DIR.resolve("settings.json"); ensureFilesDirectoryExists(configPath); log.info("Loading server configuration"); appConfig = configGson.fromJson(Files.readString(configPath), Config.class); loadBuildAndGitMetadata(); //Parse CLI Arguments final String argPrefix = "--"; final char splitCharacter = '='; for (String arg : args) { CLIArgument cliArgument = new CLIArgument(argPrefix, splitCharacter, arg); if (cliArgument.getParameterName().equals("normal")) { selectedMode = MODE.NORMAL; } if (cliArgument.getParameterName().equals("migrate-pem-to-keystore")) { selectedMode = MODE.KEYSTORE_MIGRATION_PEM2KS; } if (cliArgument.getParameterName().equals("postsetup")) { selectedMode = MODE.POSTSETUP; } } switch (selectedMode) { case NORMAL -> { initializeCoreComponents(); log.info("Starting normally"); AcmeApiServer.startServer(cryptoStoreManager, appConfig); } case POSTSETUP -> { //Do not init core components, due to changing passwords in UI log.info("Starting Post Setup"); PostSetup.run(cryptoStoreManager, appConfig, FILES_DIR, args); } case KEYSTORE_MIGRATION_PEM2KS -> { initializeCoreComponents(); log.info("Starting in KeyStore migration Mode (PEM to KeyStore)"); KSMigrationTool.run(args, cryptoStoreManager, appConfig, FILES_DIR); } } } /** * Prints a banner with a stylized text art representation. */ private static void printBanner() { System.out.println(""" _ ____ \s / \\ ___ _ __ ___ ___/ ___| ___ _ ____ _____ _ __\s / _ \\ / __| '_ ` _ \\ / _ \\___ \\ / _ \\ '__\\ \\ / / _ \\ '__| / ___ \\ (__| | | | | | __/___) | __/ | \\ V / __/ | \s /_/ \\_\\___|_| |_| |_|\\___|____/ \\___|_| \\_/ \\___|_| \s """); } private static boolean coreComponentsInitialized = false; private static void initializeCoreComponents() throws ClassNotFoundException, CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException { if (coreComponentsInitialized) { return; } initializeDatabaseDrivers(); { //Initialize KeyStore if (appConfig.getKeyStore() instanceof PKCS11KeyStoreParams pkcs11KeyStoreParams) { cryptoStoreManager = new CryptoStoreManager( new PKCS11KeyStoreConfig( Paths.get(pkcs11KeyStoreParams.getLibraryLocation()), pkcs11KeyStoreParams.getSlot(), pkcs11KeyStoreParams.getPassword() ) ); } if (appConfig.getKeyStore() instanceof PKCS12KeyStoreParams pkcs12KeyStoreParams) { cryptoStoreManager = new CryptoStoreManager( new PKCS12KeyStoreConfig( Paths.get(pkcs12KeyStoreParams.getLocation()), pkcs12KeyStoreParams.getPassword() ) ); } if (cryptoStoreManager == null) { throw new IllegalArgumentException("Could not create CryptoStoreManager, due to unsupported KeyStore configuration"); } coreComponentsInitialized = true; } } /** * Ensures that the necessary files directory and configuration file exist. * * @throws IOException If an I/O error occurs while creating directories or checking for the configuration file. */ private static void ensureFilesDirectoryExists(Path configPath) throws IOException { if (!Files.exists(FILES_DIR)) { log.info("First run detected, creating settings directory"); Files.createDirectories(FILES_DIR); } if (!Files.exists(configPath)) { log.fatal("No configuration was found. Please create a file called \"settings.json\" in \"{}\". Then try again", FILES_DIR.toAbsolutePath()); System.exit(1); } } /** * Loads build and Git metadata from resource files and populates corresponding variables. */ private static void loadBuildAndGitMetadata() { try (InputStream is = Main.class.getResourceAsStream("/build.properties")) { if (is != null) { Properties buildMetadataProperties = new Properties(); buildMetadataProperties.load(is); buildMetadataVersion = buildMetadataProperties.getProperty("build.version"); buildMetadataBuildTime = buildMetadataProperties.getProperty("build.date") + " UTC"; } else { log.warn("Unable to load build metadata"); } } catch (Exception e) { log.error("Unable to load build metadata", e); } try (InputStream is = Main.class.getResourceAsStream("/git.properties")) { if (is != null) { Properties gitMetadataProperties = new Properties(); gitMetadataProperties.load(is); buildMetadataGitCommit = gitMetadataProperties.getProperty("git.commit.id.full"); } else { log.warn("Unable to load git metadata"); } } catch (Exception e) { log.error("Unable to load git metadata", e); } } /** * Initializes database drivers for MariaDB and H2. * * @throws ClassNotFoundException If a database driver class is not found. */ private static void initializeDatabaseDrivers() throws ClassNotFoundException { log.info("Loading MariaDB JDBC driver"); Class.forName("org.mariadb.jdbc.Driver"); log.info("Loading H2 JDBC driver"); Class.forName("org.h2.Driver"); } /** * Initializes the Certificate Authority (CA) by generating or loading the CA certificate and key pair. * * @throws NoSuchAlgorithmException If the specified algorithm is not available. * @throws CertificateException If an issue occurs during certificate generation or loading. * @throws IOException If an I/O error occurs while creating directories or writing files. * @throws OperatorCreationException If there's an issue with operator creation during certificate generation. * @throws NoSuchProviderException If the specified security provider is not available. * @throws InvalidAlgorithmParameterException If there's an issue with algorithm parameters during key pair generation. */ static void initializeCA(CryptoStoreManager cryptoStoreManager) throws NoSuchAlgorithmException, CertificateException, IOException, OperatorCreationException, NoSuchProviderException, InvalidAlgorithmParameterException, KeyStoreException { KeyStore caKeyStore = cryptoStoreManager.getKeyStore(); if (!caKeyStore.containsAlias(CryptoStoreManager.KEYSTORE_ALIAS_ROOTCA)) { // Create CA KeyPair caKeyPair = null; if (appConfig.getRootCA().getAlgorithm() instanceof RSAAlgorithmParams rsaParams) { log.info("Using RSA algorithm"); log.info("Generating RSA {} bit Key Pair for Root CA", rsaParams.getKeySize());
caKeyPair = KeyPairGenerator.generateRSAKeyPair(rsaParams.getKeySize(), caKeyStore.getProvider().getName());
14
2023-11-22 15:54:36+00:00
16k
Invadermonky/JustEnoughMagiculture
src/main/java/com/invadermonky/justenoughmagiculture/integrations/jer/mods/JERErebus.java
[ { "identifier": "JERRenderGlowWorm", "path": "src/main/java/com/invadermonky/justenoughmagiculture/client/render/entity/mods/erebus/JERRenderGlowWorm.java", "snippet": "public class JERRenderGlowWorm extends RenderGlowWorm {\n private static final ResourceLocation TEXTURE_ON = new ResourceLocation(\"...
import com.google.common.collect.Sets; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.erebus.JERRenderGlowWorm; import com.invadermonky.justenoughmagiculture.client.render.entity.mods.erebus.JERRenderMagmaCrawler; import com.invadermonky.justenoughmagiculture.configs.JEMConfig; import com.invadermonky.justenoughmagiculture.configs.mods.JEMConfigErebus; import com.invadermonky.justenoughmagiculture.integrations.jei.categories.jer.plant.CustomPlantEntry; import com.invadermonky.justenoughmagiculture.integrations.jer.IJERIntegration; import com.invadermonky.justenoughmagiculture.integrations.jer.JERBase; import com.invadermonky.justenoughmagiculture.integrations.jer.conditionals.JEMConditional; import com.invadermonky.justenoughmagiculture.util.BiomeHelper; import com.invadermonky.justenoughmagiculture.util.LogHelper; import com.invadermonky.justenoughmagiculture.util.ModIds; import com.invadermonky.justenoughmagiculture.util.StringHelper; import erebus.ModBiomes; import erebus.ModBlocks; import erebus.ModItems; import erebus.blocks.EnumWood; import erebus.entity.*; import erebus.items.ItemErebusFood.EnumFoodType; import erebus.items.ItemMaterials.EnumErebusMaterialsType; import erebus.world.biomes.BiomeBaseErebus; import erebus.world.biomes.decorators.BiomeDecoratorFungalForest; import erebus.world.feature.plant.WorldGenRottenTreeStump; import erebus.world.feature.structure.*; import erebus.world.feature.tree.WorldGenGiantEucalyptus; import erebus.world.loot.WeightedLootList; import gnu.trove.map.hash.THashMap; import gnu.trove.set.hash.THashSet; import jeresources.api.conditionals.Conditional; import jeresources.api.conditionals.LightLevel; import jeresources.api.drop.LootDrop; import jeresources.api.drop.PlantDrop; import net.minecraft.block.Block; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.biome.Biome; import net.minecraft.world.storage.loot.*; import net.minecraft.world.storage.loot.conditions.LootCondition; import net.minecraft.world.storage.loot.functions.LootFunction; import net.minecraft.world.storage.loot.functions.SetCount; import net.minecraft.world.storage.loot.functions.SetMetadata; import net.minecraftforge.common.IPlantable; import net.minecraftforge.fml.client.registry.RenderingRegistry; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
14,004
LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_ZOMBIE_ANT.createStack(), 0, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.ANT_PHEROMONES.createStack(), 0.20f) }; registerMob(new EntityZombieAnt(world), LightLevel.hostile, getSpawnBiomes(EntityZombieAnt.class), drops); } if(jerConfig.JER_MOBS.enableZombieAntSoldier) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_ZOMBIE_ANT.createStack(), 0, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.ANT_PHEROMONES.createStack(), 0.10f), new LootDrop(EnumErebusMaterialsType.TERPSISHROOM.createStack(), 0.10f) }; registerMob(new EntityZombieAntSoldier(world), LightLevel.hostile, getSpawnBiomes(EntityZombieAntSoldier.class), drops); } } @Override public void registerModPlants() { if(jerConfig.JER_PLANTS.enableCabbage) { registerPlant((Item & IPlantable) ModItems.CABBAGE_SEEDS, new PlantDrop(new ItemStack(ModItems.CABBAGE_SEEDS), 0, 2), new PlantDrop(EnumFoodType.CABBAGE.createStack(), 1, 1) ); } if(jerConfig.JER_PLANTS.enableDarkFruit) { CustomPlantEntry darkFruit = new CustomPlantEntry( EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), ModBlocks.DARK_FRUIT_VINE.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), 0, 1), new PlantDrop(EnumFoodType.DARK_FRUIT.createStack(), 0, 1) ); darkFruit.setSoil(Blocks.AIR.getDefaultState()); registerCustomPlant(darkFruit); } if(jerConfig.JER_PLANTS.enableHeartBerry) { CustomPlantEntry heartBerry = new CustomPlantEntry( new ItemStack(ModBlocks.HEART_BERRY_BUSH), ModBlocks.HEART_BERRY_BUSH.getDefaultState(), new PlantDrop(new ItemStack(ModItems.HEART_BERRIES), 1, 1) ); heartBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(heartBerry); } if(jerConfig.JER_PLANTS.enableJadeBerry) { CustomPlantEntry jadeBerry = new CustomPlantEntry( new ItemStack(ModBlocks.JADE_BERRY_BUSH), ModBlocks.JADE_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.JADE_BERRIES.createStack(), 1, 1) ); jadeBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(jadeBerry); } if(jerConfig.JER_PLANTS.enableMandrake) { registerPlant((Item & IPlantable) ModItems.MANDRAKE_ROOT, new PlantDrop(new ItemStack(ModItems.MANDRAKE_ROOT), 1, 3) ); } if(jerConfig.JER_PLANTS.enableSwampBerry) { CustomPlantEntry swampBerry = new CustomPlantEntry( new ItemStack(ModBlocks.SWAMP_BERRY_BUSH), ModBlocks.SWAMP_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumFoodType.SWAMP_BERRIES.createStack(), 1, 1) ); swampBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(swampBerry); } if(jerConfig.JER_PLANTS.enableTurnip) { registerPlant((Item & IPlantable) ModItems.TURNIP, new PlantDrop(new ItemStack(ModItems.TURNIP), 1, 3) ); } } public void registerRenderOverrides() { RenderingRegistry.registerEntityRenderingHandler(EntityGlowWorm.class, JERRenderGlowWorm::new); RenderingRegistry.registerEntityRenderingHandler(EntityMagmaCrawler.class, JERRenderMagmaCrawler::new); } private void adjustBugRenderHookUp(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, 0.4, 0); return renderInfo; })); } private void adjustBugRenderHookDown(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, -0.4, 0); return renderInfo; })); } private String[] getSpawnBiomes(Class<? extends EntityLiving> entityClass) { THashSet<Biome> spawnBiomes = new THashSet<>(); mobSpawns.forEach((biome, mobList) -> { if(mobList.contains(entityClass)) spawnBiomes.add(biome); }); return !spawnBiomes.isEmpty() ? BiomeHelper.getBiomeNamesForBiomes(spawnBiomes.toArray(new Biome[0])) : new String[] {"Check Spawns"}; } private void registerErebusDungeon(String name, WeightedLootList lootList, int minRolls, int maxRolls) { JERDungeonStrings dungeon = new JERDungeonStrings(name, lootList, minRolls, maxRolls); registerDungeonLoot(dungeon.category, dungeon.unlocName, dungeon.lootTable); } private static class JERDungeonStrings { public final String category; public final String unlocName; public final LootTable lootTable; public JERDungeonStrings(String name, WeightedLootList lootList, int minRolls, int maxRolls) { this.category = String.format("%s:%s", ModIds.EREBUS.MOD_ID, name);
package com.invadermonky.justenoughmagiculture.integrations.jer.mods; public class JERErebus extends JERBase implements IJERIntegration { private static JERErebus instance; private final JEMConfigErebus.JER jerConfig = JEMConfig.EREBUS.JUST_ENOUGH_RESOURCES; private static THashMap<BiomeBaseErebus, THashSet<Class<? extends EntityLiving>>> mobSpawns; private JERErebus() {} public JERErebus(boolean enableJERDungeons, boolean enableJERMobs, boolean enableJERPlants) { if(enableJERDungeons) registerModDungeons(); if(enableJERMobs) registerModEntities(); if(enableJERPlants) registerModPlants(); getInstance(); } public static JERErebus getInstance() { return instance != null ? instance : (instance = new JERErebus()); } @Override public void registerModDungeons() { registerErebusDungeon("antlion_dungeon", WorldGenAntlionDungeon.chestLoot, 3, 10); registerErebusDungeon("antlion_lair", WorldGenAntlionLair.chestLoot, 10, 14); registerErebusDungeon("dragonfly_dungeon", WorldGenDragonflyDungeon.CHEST_LOOT, 5, 15); registerErebusDungeon("dung_pile", WorldGenDungPile.CHEST_LOOT, 8, 14); registerErebusDungeon("giant_eucalyptus", WorldGenGiantEucalyptus.chestLoot, 3, 10); registerErebusDungeon("locust_shrine", WorldGenLocustShrine.CHEST_LOOT,2, 3); registerErebusDungeon("rotten_tree_stump", WorldGenRottenTreeStump.chestLoot, 3, 10); registerErebusDungeon("spider_dungeon", WorldGenSpiderDungeons.chestLoot, 3, 10); } @Override public void registerModEntities() { populateMobSpawns(); String[] allBiomes = BiomeHelper.getBiomeNamesForBiomes(mobSpawns.keySet().toArray(new Biome[0])); LootDrop exoPlateDrop = new LootDrop(EnumErebusMaterialsType.PLATE_EXO.createStack(), 0, 3, Conditional.affectedByLooting); if(jerConfig.JER_MOBS.enableAntlion) { registerMob(new EntityAntlion(world), LightLevel.hostile, getSpawnBiomes(EntityAntlion.class), exoPlateDrop); } if(jerConfig.JER_MOBS.enableAntlionGuardian) { registerMob(new EntityAntlionMiniBoss(world), LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), exoPlateDrop); registerRenderHook(EntityAntlionMiniBoss.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableAntlionOverlord) { LootDrop[] drops = new LootDrop[] { new LootDrop(new ItemStack(ModBlocks.ANTLION_EGG)), new LootDrop(EnumErebusMaterialsType.SOUL_CRYSTAL.createStack()), new LootDrop(new ItemStack(ModItems.WAR_HAMMER)) }; registerMob(new EntityAntlionBoss(world), LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), drops); registerRenderHook(EntityAntlionBoss.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableBedBug) { registerMob(new EntityBedBug(world), LightLevel.hostile, allBiomes, new LootDrop(new ItemStack(Blocks.WOOL, 1, 0))); registerRenderHook(EntityBedBug.class, ((renderInfo, e) -> { GlStateManager.translate(0,-0.2,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableBeetle) { registerMob(new EntityBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityBeetle.class), exoPlateDrop); adjustBugRenderHookUp(EntityBeetle.class); } if(jerConfig.JER_MOBS.enableBeetleLarva) { List<LootDrop> larvaDrops = new ArrayList<>(); LootDrop foodDrop = new LootDrop(new ItemStack(ModItems.EREBUS_FOOD, 1, 0), 1, 1, JEMConditional.isNotSquashed); foodDrop.smeltedItem = new ItemStack(ModItems.EREBUS_FOOD, 1, 1); larvaDrops.add(foodDrop); larvaDrops.add(new LootDrop(Items.SLIME_BALL, 1, 1, ((float)199/200), JEMConditional.isSquashed)); larvaDrops.add(new LootDrop(Items.DIAMOND, 0, 1, ((float)1/200), JEMConditional.isSquashed, Conditional.rareDrop)); registerMob(new EntityBeetleLarva(world), LightLevel.hostile, getSpawnBiomes(EntityBeetleLarva.class), larvaDrops); adjustBugRenderHookUp(EntityBeetleLarva.class); } if(jerConfig.JER_MOBS.enableBlackWidow) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.STRING, 0, 1, Conditional.affectedByLooting), new LootDrop(Items.SPIDER_EYE, 0, 1, (float)1/3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack()) }; registerMob(new EntityBlackWidow(world), LightLevel.hostile, getSpawnBiomes(EntityBlackWidow.class), drops); } if(jerConfig.JER_MOBS.enableBogMaw) { registerMob(new EntityBogMaw(world), LightLevel.hostile, getSpawnBiomes(EntityBogMaw.class), new LootDrop(EnumErebusMaterialsType.BOGMAW_ROOT.createStack(), 0, 2, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableBombardierBeetle) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.GUNPOWDER, 1, 1), new LootDrop(Items.BLAZE_POWDER, 1, 1), exoPlateDrop }; registerMob(new EntityBombardierBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityBombardierBeetle.class), drops); } if(jerConfig.JER_MOBS.enableBombardierBeetleLarva) { List<LootDrop> larvaDrops = new ArrayList<>(); LootDrop foodDrop = new LootDrop(new ItemStack(ModItems.EREBUS_FOOD, 1, 0), 1, 1, JEMConditional.isNotSquashed); foodDrop.smeltedItem = new ItemStack(ModItems.EREBUS_FOOD, 1, 1); larvaDrops.add(foodDrop); larvaDrops.add(new LootDrop(Items.SLIME_BALL, 1, 1, ((float)199/200), JEMConditional.isSquashed)); larvaDrops.add(new LootDrop(Items.DIAMOND, 0, 1, ((float)1/200), JEMConditional.isSquashed)); registerMob(new EntityBombardierBeetleLarva(world), LightLevel.hostile, getSpawnBiomes(EntityBombardierBeetleLarva.class), larvaDrops); } if(jerConfig.JER_MOBS.enableBotFly) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.FLY_WING.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 3, 0.25f, Conditional.affectedByLooting) }; registerMob(new EntityBotFly(world), LightLevel.hostile, getSpawnBiomes(EntityBotFly.class), drops); } if(jerConfig.JER_MOBS.enableCentipede) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.BIO_VELOCITY.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.SUPERNATURAL_VELOCITY.createStack(), 0, 1, 0.02f, Conditional.rareDrop) }; registerMob(new EntityCentipede(world), LightLevel.hostile, getSpawnBiomes(EntityCentipede.class), drops); } if(jerConfig.JER_MOBS.enableChameleonTick) { registerMob(new EntityChameleonTick(world), LightLevel.hostile, getSpawnBiomes(EntityChameleonTick.class), new LootDrop(EnumErebusMaterialsType.CAMO_POWDER.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableCicada) { registerMob(new EntityCicada(world), LightLevel.hostile, getSpawnBiomes(EntityCicada.class), new LootDrop(EnumErebusMaterialsType.REPELLENT.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableCropWeevil) { LootDrop[] drops = new LootDrop[]{ new LootDrop(new ItemStack(ModBlocks.GIANT_FLOWER_STIGMA), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.PUMPKIN_SEEDS), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.MELON_SEEDS), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.DYE, 1, 3), 1, 3, 0.20f, Conditional.affectedByLooting), new LootDrop(new ItemStack(ModItems.TURNIP), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.NETHER_WART), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.WHEAT), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.REEDS), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(EnumWood.BAMBOO.getSapling()), 1, 1, 0.01425f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.CARROT), 1, 1, 0.015f, Conditional.affectedByLooting), new LootDrop(new ItemStack(Items.POTATO), 1, 1, 0.015f, Conditional.affectedByLooting) }; registerMob(new EntityCropWeevil(world), LightLevel.hostile, getSpawnBiomes(EntityCropWeevil.class), drops); registerRenderHook(EntityCropWeevil.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableCrushroom) { registerMob(new EntityCrushroom(world), LightLevel.hostile, getSpawnBiomes(EntityCrushroom.class), new LootDrop(EnumErebusMaterialsType.HIDE_SHROOM.createStack(), 0, 2, Conditional.affectedByLooting)); registerRenderHook(EntityCrushroom.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); GlStateManager.translate(-0.05,-0.8,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableDragonfly) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.DRAGONFLY_WING.createStack()), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 1, 0.20f, Conditional.affectedByLooting), new LootDrop(Items.ENDER_PEARL, 0, 1, 0.15f, Conditional.affectedByLooting) }; registerMob(new EntityDragonfly(world), LightLevel.hostile, getSpawnBiomes(EntityDragonfly.class), drops); registerRenderHook(EntityDragonfly.class, ((renderInfo, e) -> { GlStateManager.scale(1.5,1.5,1.5); return renderInfo; })); } if(jerConfig.JER_MOBS.enableFireAnt) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.MAGMA_CREAM, 1, 1, Conditional.affectedByLooting), new LootDrop(Items.FIRE_CHARGE, 0, 1, 0.20f, Conditional.affectedByLooting) }; registerMob(new EntityFireAnt(world), LightLevel.hostile, getSpawnBiomes(EntityFireAnt.class), drops); registerRenderHook(EntityFireAnt.class, ((renderInfo, e) -> { GlStateManager.scale(1.1,1.1,1.1); return renderInfo; })); } if(jerConfig.JER_MOBS.enableFireAntSoldier) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.BLAZE_POWDER, 1, 1, Conditional.affectedByLooting), new LootDrop(Items.BLAZE_ROD, 0, 1, 0.20f, Conditional.affectedByLooting) }; registerMob(new EntityFireAntSoldier(world), LightLevel.hostile, getSpawnBiomes(EntityFireAntSoldier.class), drops); } if(jerConfig.JER_MOBS.enableFly) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.FLY_WING.createStack(), 0, 1, 0.10f), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 1, 0.05f, Conditional.rareDrop) }; registerMob(new EntityFly(world), LightLevel.hostile, getSpawnBiomes(EntityFly.class), drops); registerRenderHook(EntityFly.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableFungalWeevil) { List<LootDrop> drops = new ArrayList<>(); drops.add(new LootDrop(new ItemStack(Blocks.BROWN_MUSHROOM), 0.1667f)); drops.add(new LootDrop(new ItemStack(Blocks.RED_MUSHROOM), 0.1667f)); float chance = (float) 2/3 * 1 / BiomeDecoratorFungalForest.MUSHROOMS.length; for(Block block : BiomeDecoratorFungalForest.MUSHROOMS) { drops.add(new LootDrop(new ItemStack(block), chance)); } registerMob(new EntityFungalWeevil(world), LightLevel.hostile, getSpawnBiomes(EntityFungalWeevil.class), drops); registerRenderHook(EntitySolifuge.class, ((renderInfo, e) -> { GlStateManager.scale(1.6,1.6,1.6); return renderInfo; })); } if(jerConfig.JER_MOBS.enableGlowWorm) { registerMob(new EntityGlowWorm(world), LightLevel.hostile, getSpawnBiomes(EntityGlowWorm.class), new LootDrop(EnumErebusMaterialsType.BIO_LUMINESCENCE.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableGrasshopper) { LootDrop foodDrop = new LootDrop(EnumFoodType.GRASSHOPPER_LEG_RAW.createStack(), 0, 3, Conditional.affectedByLooting); foodDrop.smeltedItem = EnumFoodType.GRASSHOPPER_LEG_COOKED.createStack(); registerMob(new EntityGrasshopper(world), LightLevel.hostile, getSpawnBiomes(EntityGrasshopper.class), foodDrop); } if(jerConfig.JER_MOBS.enableHoneyPotAnt) { registerMob(new EntityHoneyPotAnt(world), LightLevel.hostile, getSpawnBiomes(EntityHoneyPotAnt.class), new LootDrop(EnumErebusMaterialsType.NECTAR.createStack(), 1, 8, 1f)); adjustBugRenderHookUp(EntityHoneyPotAnt.class); registerRenderHook(EntityHoneyPotAnt.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableJumpingSpider) { registerMob(new EntityJumpingSpider(world), LightLevel.hostile, getSpawnBiomes(EntityJumpingSpider.class), new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableLavaWebSpider) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.FIRE_CHARGE, 1, 1, Conditional.affectedByLooting), new LootDrop(Items.SPIDER_EYE, 0, 2, Conditional.affectedByLooting) }; registerMob(new EntityLavaWebSpider(world), LightLevel.hostile, getSpawnBiomes(EntityLavaWebSpider.class), drops); registerRenderHook(EntityLavaWebSpider.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableLocust) { registerMob(new EntityLocust(world), LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.SUBTERRANEAN_SAVANNAH), new LootDrop(EnumErebusMaterialsType.ELASTIC_FIBRE.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableMagmaCrawler) { registerMob(new EntityMagmaCrawler(world), LightLevel.hostile, getSpawnBiomes(EntityMagmaCrawler.class), new LootDrop(EnumErebusMaterialsType.MAGMA_CRAWLER_EYE.createStack())); } if(jerConfig.JER_MOBS.enableMidgeSwarm) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.FLY_WING.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.COMPOUND_EYES.createStack(), 0, 3, 0.20f, Conditional.affectedByLooting) }; registerMob(new EntityMidgeSwarm(world), LightLevel.hostile, getSpawnBiomes(EntityMidgeSwarm.class), drops); } if(jerConfig.JER_MOBS.enableMoneySpider) { List<String> spawnBiomes = new ArrayList<>(); spawnBiomes.addAll(Arrays.asList(getSpawnBiomes(EntityLavaWebSpider.class))); spawnBiomes.addAll(Arrays.asList(getSpawnBiomes(EntityTarantula.class))); registerMob(new EntityMoneySpider(world), LightLevel.hostile, spawnBiomes.isEmpty() ? new String[] {"jer.any"} : spawnBiomes.toArray(new String[0]), new LootDrop(Items.GOLD_INGOT, 0, 1, 0.10f, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableMosquito) { registerMob(new EntityMosquito(world), LightLevel.hostile, getSpawnBiomes(EntityMosquito.class), new LootDrop(ModItems.LIFE_BLOOD, 1, 5)); registerRenderHook(EntityMosquito.class, ((renderInfo, e) -> { GlStateManager.translate(0,-0.5,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableMoth) { registerMob(new EntityMoth(world), LightLevel.hostile, getSpawnBiomes(EntityMoth.class), new LootDrop(Items.GLOWSTONE_DUST, 0.20f)); } if(jerConfig.JER_MOBS.enablePondSkater) { registerMob(new EntityPondSkater(world), LightLevel.hostile, getSpawnBiomes(EntityPondSkater.class), new LootDrop(EnumErebusMaterialsType.HYDROFUGE.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enablePrayingMantis) { EntityPrayingMantis mantis = new EntityPrayingMantis(world); mantis.setAlpha(1.0f); registerMob(mantis, LightLevel.hostile, getSpawnBiomes(EntityPrayingMantis.class), new LootDrop(EnumErebusMaterialsType.CAMO_POWDER.createStack(), 0, 3, Conditional.affectedByLooting)); adjustBugRenderHookDown(EntityPrayingMantis.class); } if(jerConfig.JER_MOBS.enablePunchroom) { registerMob(new EntityPunchroom(world), LightLevel.hostile, getSpawnBiomes(EntityPunchroom.class), new LootDrop(EnumErebusMaterialsType.ELASTIC_FIBRE.createStack(), 1, 1, 0.20f, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableRhinoBeetle) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_EXO_RHINO.createStack(), 1, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.RHINO_BEETLE_HORN.createStack(), 0, 1, 0.05f, Conditional.rareDrop) }; registerMob(new EntityRhinoBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityRhinoBeetle.class), drops); registerRenderHook(EntityRhinoBeetle.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); GlStateManager.translate(0,1.0,0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableScorpion) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.POISON_GLAND.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.SCORPION_PINCER.createStack(), 0, 3, 0.0333f, Conditional.affectedByLooting, Conditional.rareDrop) }; registerMob(new EntityScorpion(world), LightLevel.hostile, getSpawnBiomes(EntityScorpion.class), drops); adjustBugRenderHookDown(EntityScorpion.class); } if(jerConfig.JER_MOBS.enableScytodes) { LootDrop[] drops = new LootDrop[] { new LootDrop(Items.STRING, 0, 3, Conditional.affectedByLooting), new LootDrop(Items.SPIDER_EYE, 0, 2, Conditional.affectedByLooting) }; registerMob(new EntityScytodes(world), LightLevel.hostile, getSpawnBiomes(EntityScytodes.class), drops); registerRenderHook(EntityScytodes.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableSolifuge) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.BIO_VELOCITY.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.SUPERNATURAL_VELOCITY.createStack(), 0, 1, 0.02f, Conditional.rareDrop) }; registerMob(new EntitySolifuge(world), LightLevel.hostile, getSpawnBiomes(EntitySolifuge.class), drops); registerRenderHook(EntitySolifuge.class, ((renderInfo, e) -> { GlStateManager.scale(1.4,1.4,1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableStagBeetle) { List<LootDrop> drops = new ArrayList<>(); drops.add(exoPlateDrop); LootDrop foodDrop = new LootDrop(ModItems.STAG_HEART_RAW, 0.1333f); foodDrop.smeltedItem = new ItemStack(ModItems.STAG_HEART_COOKED); drops.add(foodDrop); drops.add(new LootDrop(EnumErebusMaterialsType.STAG_BEETLE_MANDIBLES.createStack(), 0, 1, 0.0333f, Conditional.rareDrop)); registerMob(new EntityStagBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityStagBeetle.class), drops); registerRenderHook(EntityStagBeetle.class, ((renderInfo, e) -> { GlStateManager.scale(1.4, 1.4, 1.4); GlStateManager.translate(0, 1.0, 0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTarantula) { List<LootDrop> drops = new ArrayList<>(); LootDrop foodDrop = new LootDrop(EnumFoodType.TARANTULA_LEG_RAW.createStack(), 1, 1, Conditional.affectedByLooting); foodDrop.smeltedItem = EnumFoodType.TARANTULA_LEG_COOKED.createStack(); drops.add(foodDrop); drops.add(new LootDrop(Items.SPIDER_EYE, 0, 1, Conditional.affectedByLooting)); registerMob(new EntityTarantula(world), LightLevel.hostile, getSpawnBiomes(EntityTarantula.class), drops); } if(jerConfig.JER_MOBS.enableTarantulaBroodMother) { registerMob(new EntityTarantulaMiniboss(world), LightLevel.hostile, allBiomes, new LootDrop(new ItemStack(ModItems.SPIDER_T_SHIRT))); registerRenderHook(EntityTarantulaMiniboss.class, ((renderInfo, e) -> { GlStateManager.scale(1.4, 1.4, 1.4); return renderInfo; })); } if(jerConfig.JER_MOBS.enableTitanBeetle) { List<LootDrop> drops = new ArrayList<>(); drops.add(exoPlateDrop); LootDrop foodDrop = new LootDrop(EnumFoodType.TITAN_CHOP_RAW.createStack()); foodDrop.smeltedItem = EnumFoodType.TITAN_CHOP_COOKED.createStack(); drops.add(foodDrop); registerMob(new EntityTitanBeetle(world), LightLevel.hostile, getSpawnBiomes(EntityTitanBeetle.class), drops); registerRenderHook(EntityTitanBeetle.class, ((renderInfo, e) -> { GlStateManager.scale(1.4, 1.4, 1.4); GlStateManager.translate(0, 1.0, 0); return renderInfo; })); } boolean isUmberGolemRegistered = false; if(jerConfig.JER_MOBS.enableUmberGolemMud) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 0); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(jerConfig.JER_MOBS.enableUmberGolemIron) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 1); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(jerConfig.JER_MOBS.enableUmberGolemGold) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 2); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(jerConfig.JER_MOBS.enableUmberGolemJade) { EntityUmberGolemDungeonTypes umberGolem = new EntityUmberGolemDungeonTypes(world); umberGolem.setType((byte) 3); registerMob(umberGolem, LightLevel.hostile, BiomeHelper.getBiomeNamesForBiomes(ModBiomes.VOLCANIC_DESERT), new LootDrop(new ItemStack(ModItems.IDOLS, 1, umberGolem.getType()))); isUmberGolemRegistered = true; } if(isUmberGolemRegistered) { registerRenderHook(EntityUmberGolemDungeonTypes.class, ((renderInfo, e) -> { GlStateManager.translate(-0.025, -0.4, 0); return renderInfo; })); } if(jerConfig.JER_MOBS.enableVelvetWorm) { registerMob(new EntityVelvetWorm(world), LightLevel.hostile, getSpawnBiomes(EntityVelvetWorm.class), new LootDrop(Items.SLIME_BALL, 1, 2, Conditional.affectedByLooting)); registerRenderHook(EntityVelvetWorm.class, ((renderInfo, e) -> { GlStateManager.scale(1.6,1.6,1.6); return renderInfo; })); } if(jerConfig.JER_MOBS.enableWasp) { registerMob(new EntityWasp(world), LightLevel.hostile, getSpawnBiomes(EntityWasp.class), new LootDrop(EnumErebusMaterialsType.WASP_STING.createStack(), 0, 3, Conditional.affectedByLooting)); } if(jerConfig.JER_MOBS.enableWaspBoss) { EntityWasp waspBoss = new EntityWasp(world); waspBoss.setIsBoss((byte) 1); LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.WASP_STING.createStack(), 0, 3, Conditional.affectedByLooting), new LootDrop(new ItemStack(ModItems.ANTI_VENOM_BOTTLE)) }; registerMob(waspBoss, LightLevel.hostile, getSpawnBiomes(EntityWasp.class), drops); } if(jerConfig.JER_MOBS.enableWoodlouse) { registerMob(new EntityWoodlouse(world), LightLevel.hostile, allBiomes, new LootDrop(EnumErebusMaterialsType.WHETSTONE_POWDER.createStack(), 0, 3, Conditional.affectedByLooting)); registerRenderHook(EntityWoodlouse.class, ((renderInfo, e) -> { GlStateManager.scale(1.2,1.2,1.2); return renderInfo; })); } if(jerConfig.JER_MOBS.enableWorkerBee) { registerMob(new EntityWorkerBee(world), LightLevel.hostile, getSpawnBiomes(EntityWorkerBee.class), new LootDrop(EnumErebusMaterialsType.NECTAR.createStack(2))); adjustBugRenderHookUp(EntityWorkerBee.class); } if(jerConfig.JER_MOBS.enableZombieAnt) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_ZOMBIE_ANT.createStack(), 0, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.ANT_PHEROMONES.createStack(), 0.20f) }; registerMob(new EntityZombieAnt(world), LightLevel.hostile, getSpawnBiomes(EntityZombieAnt.class), drops); } if(jerConfig.JER_MOBS.enableZombieAntSoldier) { LootDrop[] drops = new LootDrop[] { new LootDrop(EnumErebusMaterialsType.PLATE_ZOMBIE_ANT.createStack(), 0, 2, Conditional.affectedByLooting), new LootDrop(EnumErebusMaterialsType.ANT_PHEROMONES.createStack(), 0.10f), new LootDrop(EnumErebusMaterialsType.TERPSISHROOM.createStack(), 0.10f) }; registerMob(new EntityZombieAntSoldier(world), LightLevel.hostile, getSpawnBiomes(EntityZombieAntSoldier.class), drops); } } @Override public void registerModPlants() { if(jerConfig.JER_PLANTS.enableCabbage) { registerPlant((Item & IPlantable) ModItems.CABBAGE_SEEDS, new PlantDrop(new ItemStack(ModItems.CABBAGE_SEEDS), 0, 2), new PlantDrop(EnumFoodType.CABBAGE.createStack(), 1, 1) ); } if(jerConfig.JER_PLANTS.enableDarkFruit) { CustomPlantEntry darkFruit = new CustomPlantEntry( EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), ModBlocks.DARK_FRUIT_VINE.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.DARK_FRUIT_SEEDS.createStack(), 0, 1), new PlantDrop(EnumFoodType.DARK_FRUIT.createStack(), 0, 1) ); darkFruit.setSoil(Blocks.AIR.getDefaultState()); registerCustomPlant(darkFruit); } if(jerConfig.JER_PLANTS.enableHeartBerry) { CustomPlantEntry heartBerry = new CustomPlantEntry( new ItemStack(ModBlocks.HEART_BERRY_BUSH), ModBlocks.HEART_BERRY_BUSH.getDefaultState(), new PlantDrop(new ItemStack(ModItems.HEART_BERRIES), 1, 1) ); heartBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(heartBerry); } if(jerConfig.JER_PLANTS.enableJadeBerry) { CustomPlantEntry jadeBerry = new CustomPlantEntry( new ItemStack(ModBlocks.JADE_BERRY_BUSH), ModBlocks.JADE_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumErebusMaterialsType.JADE_BERRIES.createStack(), 1, 1) ); jadeBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(jadeBerry); } if(jerConfig.JER_PLANTS.enableMandrake) { registerPlant((Item & IPlantable) ModItems.MANDRAKE_ROOT, new PlantDrop(new ItemStack(ModItems.MANDRAKE_ROOT), 1, 3) ); } if(jerConfig.JER_PLANTS.enableSwampBerry) { CustomPlantEntry swampBerry = new CustomPlantEntry( new ItemStack(ModBlocks.SWAMP_BERRY_BUSH), ModBlocks.SWAMP_BERRY_BUSH.getDefaultState(), new PlantDrop(EnumFoodType.SWAMP_BERRIES.createStack(), 1, 1) ); swampBerry.setSoil(Blocks.DIRT.getDefaultState()); registerCustomPlant(swampBerry); } if(jerConfig.JER_PLANTS.enableTurnip) { registerPlant((Item & IPlantable) ModItems.TURNIP, new PlantDrop(new ItemStack(ModItems.TURNIP), 1, 3) ); } } public void registerRenderOverrides() { RenderingRegistry.registerEntityRenderingHandler(EntityGlowWorm.class, JERRenderGlowWorm::new); RenderingRegistry.registerEntityRenderingHandler(EntityMagmaCrawler.class, JERRenderMagmaCrawler::new); } private void adjustBugRenderHookUp(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, 0.4, 0); return renderInfo; })); } private void adjustBugRenderHookDown(Class<? extends EntityLivingBase> clazz) { registerRenderHook(clazz, ((renderInfo, e) -> { GlStateManager.translate(0, -0.4, 0); return renderInfo; })); } private String[] getSpawnBiomes(Class<? extends EntityLiving> entityClass) { THashSet<Biome> spawnBiomes = new THashSet<>(); mobSpawns.forEach((biome, mobList) -> { if(mobList.contains(entityClass)) spawnBiomes.add(biome); }); return !spawnBiomes.isEmpty() ? BiomeHelper.getBiomeNamesForBiomes(spawnBiomes.toArray(new Biome[0])) : new String[] {"Check Spawns"}; } private void registerErebusDungeon(String name, WeightedLootList lootList, int minRolls, int maxRolls) { JERDungeonStrings dungeon = new JERDungeonStrings(name, lootList, minRolls, maxRolls); registerDungeonLoot(dungeon.category, dungeon.unlocName, dungeon.lootTable); } private static class JERDungeonStrings { public final String category; public final String unlocName; public final LootTable lootTable; public JERDungeonStrings(String name, WeightedLootList lootList, int minRolls, int maxRolls) { this.category = String.format("%s:%s", ModIds.EREBUS.MOD_ID, name);
this.unlocName = StringHelper.getDungeonTranslationKey(ModIds.EREBUS.MOD_ID, name);
11
2023-11-19 23:09:14+00:00
16k
Provismet/ProviHealth
src/main/java/com/provismet/provihealth/ProviHealthClient.java
[ { "identifier": "ProviHealthApi", "path": "src/main/java/com/provismet/provihealth/api/ProviHealthApi.java", "snippet": "public interface ProviHealthApi {\n public void onInitialize ();\n\n /**\n * Registers an icon that will display on top of the health bar in the HUD for a specific entity gr...
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.provismet.provihealth.api.ProviHealthApi; import com.provismet.provihealth.config.Options; import com.provismet.provihealth.hud.TargetHealthBar; import com.provismet.provihealth.particle.Particles; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier;
11,805
package com.provismet.provihealth; public class ProviHealthClient implements ClientModInitializer { public static final String MODID = "provihealth"; public static final Logger LOGGER = LoggerFactory.getLogger("Provi's Health Bars"); public static Identifier identifier (String path) { return Identifier.of(MODID, path); } @Override public void onInitializeClient () { HudRenderCallback.EVENT.register(new TargetHealthBar()); FabricLoader.getInstance().getEntrypointContainers(MODID, ProviHealthApi.class).forEach( entrypoint -> { String otherModId = entrypoint.getProvider().getMetadata().getId(); try { entrypoint.getEntrypoint().onInitialize(); } catch (Exception e) { LOGGER.error("Mod " + otherModId + " caused an error during inter-mod initialisation: ", e); } } ); Options.load();
package com.provismet.provihealth; public class ProviHealthClient implements ClientModInitializer { public static final String MODID = "provihealth"; public static final Logger LOGGER = LoggerFactory.getLogger("Provi's Health Bars"); public static Identifier identifier (String path) { return Identifier.of(MODID, path); } @Override public void onInitializeClient () { HudRenderCallback.EVENT.register(new TargetHealthBar()); FabricLoader.getInstance().getEntrypointContainers(MODID, ProviHealthApi.class).forEach( entrypoint -> { String otherModId = entrypoint.getProvider().getMetadata().getId(); try { entrypoint.getEntrypoint().onInitialize(); } catch (Exception e) { LOGGER.error("Mod " + otherModId + " caused an error during inter-mod initialisation: ", e); } } ); Options.load();
Particles.register();
3
2023-11-26 02:46:37+00:00
16k
ArmanKhanDev/FakepixelDungeonHelper
src/main/java/io/github/quantizr/core/Waypoints.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"...
import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.github.quantizr.DungeonRooms; import io.github.quantizr.events.PacketEvent; import io.github.quantizr.utils.Utils; import io.github.quantizr.utils.WaypointUtils; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Blocks; import net.minecraft.network.play.server.S0DPacketCollectItem; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.StringUtils; import net.minecraftforge.client.event.ClientChatReceivedEvent; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.eventhandler.EventPriority; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.gameevent.InputEvent; import java.awt.*; import java.util.*; import java.util.List;
13,455
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks; BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get("x").getAsInt(), secretsObject.get("y").getAsInt(), secretsObject.get("z").getAsInt())); if (pos == null) continue; double x = pos.getX() - viewerX; double y = pos.getY() - viewerY; double z = pos.getZ() - viewerZ; double distSq = x*x + y*y + z*z; GlStateManager.disableDepth(); GlStateManager.disableCull();
/* Copyright 2021 Quantizr(_risk) This file is used as part of Dungeon Rooms Mod (DRM). (Github: <https://github.com/Quantizr/DungeonRoomsMod>) DRM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DRM. If not, see <https://www.gnu.org/licenses/>. */ package io.github.quantizr.core; public class Waypoints { public static boolean enabled = true; public static boolean showEntrance = true; public static boolean showSuperboom = true; public static boolean showSecrets = true; public static boolean showFairySouls = true; public static boolean sneakToDisable = true; public static boolean disableWhenAllFound = true; public static boolean allFound = false; public static boolean showWaypointText = true; public static boolean showBoundingBox = true; public static boolean showBeacon = true; public static int secretNum = 0; public static int completedSecrets = 0; public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>(); public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9])); static long lastSneakTime = 0; @SubscribeEvent public void onWorldRender(RenderWorldLastEvent event) { if (!enabled) return; String roomName = AutoRoom.lastRoomName; if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) { secretNum = AutoRoom.lastRoomJson.get("secrets").getAsInt(); if (DungeonRooms.waypointsJson.get(roomName) != null) { JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray(); int arraySize = secretsArray.size(); for(int i = 0; i < arraySize; i++) { JsonObject secretsObject = secretsArray.get(i).getAsJsonObject(); boolean display = true; for(int j = 1; j <= secretNum; j++) { if (!secretsList.get(j-1)) { if (secretsObject.get("secretName").getAsString().contains(String.valueOf(j))) { display = false; break; } } } if (!display) continue; if (disableWhenAllFound && allFound && !secretsObject.get("category").getAsString().equals("fairysoul")) continue; Color color; switch (secretsObject.get("category").getAsString()) { case "entrance": if (!showEntrance) continue; color = new Color(0, 255, 0); break; case "superboom": if (!showSuperboom) continue; color = new Color(255, 0, 0); break; case "chest": if (!showSecrets) continue; color = new Color(2, 213, 250); break; case "item": if (!showSecrets) continue; color = new Color(2, 64, 250); break; case "bat": if (!showSecrets) continue; color = new Color(142, 66, 0); break; case "wither": if (!showSecrets) continue; color = new Color(30, 30, 30); break; case "lever": if (!showSecrets) continue; color = new Color(250, 217, 2); break; case "fairysoul": if (!showFairySouls) continue; color = new Color(255, 85, 255); break; default: color = new Color(190, 255, 252); } Entity viewer = Minecraft.getMinecraft().getRenderViewEntity(); double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks; double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks; double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks; BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get("x").getAsInt(), secretsObject.get("y").getAsInt(), secretsObject.get("z").getAsInt())); if (pos == null) continue; double x = pos.getX() - viewerX; double y = pos.getY() - viewerY; double z = pos.getZ() - viewerZ; double distSq = x*x + y*y + z*z; GlStateManager.disableDepth(); GlStateManager.disableCull();
if (showBoundingBox) WaypointUtils.drawFilledBoundingBox(new AxisAlignedBB(x, y, z, x + 1, y + 1, z + 1), color, 0.4f);
3
2023-12-22 04:44:39+00:00
16k
lonelytransistor/LauncherAndroidTV
app/src/main/java/net/lonelytransistor/launcher/MovieCard.java
[ { "identifier": "AllRepos", "path": "app/src/main/java/net/lonelytransistor/launcher/repos/AllRepos.java", "snippet": "public class AllRepos {\n public static Drawable newIcon;\n public static Drawable pausedIcon;\n public static Drawable tickIcon;\n public static Drawable nextIcon;\n pub...
import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.Log; import androidx.annotation.NonNull; import net.lonelytransistor.launcher.repos.AllRepos; import net.lonelytransistor.launcher.repos.ApkRepo; import net.lonelytransistor.launcher.repos.JustWatch; import net.lonelytransistor.launcher.repos.MovieTitle; import java.util.ArrayList; import java.util.List; import java.util.Objects;
13,057
package net.lonelytransistor.launcher; public class MovieCard extends Card { public String title; public String desc; public Drawable statusIcon; public Uri mainImage; public int progressBar; public int score; public int popularity; public int popularityDelta; public MovieCard(MovieCard c) { title = c.title; desc = c.desc; statusIcon = c.statusIcon; mainImage = c.mainImage; progressBar = c.progressBar; score = c.score; popularity = c.popularity; popularityDelta = c.popularityDelta; clickIntent = c.clickIntent; } Intent clickIntent;
package net.lonelytransistor.launcher; public class MovieCard extends Card { public String title; public String desc; public Drawable statusIcon; public Uri mainImage; public int progressBar; public int score; public int popularity; public int popularityDelta; public MovieCard(MovieCard c) { title = c.title; desc = c.desc; statusIcon = c.statusIcon; mainImage = c.mainImage; progressBar = c.progressBar; score = c.score; popularity = c.popularity; popularityDelta = c.popularityDelta; clickIntent = c.clickIntent; } Intent clickIntent;
public MovieCard(MovieTitle m) {
3
2023-12-28 18:24:12+00:00
16k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/controller/GameController.java
[ { "identifier": "ChessBackup", "path": "CS109_2022_Fall/Chess/model/ChessBackup.java", "snippet": "public class ChessBackup {\n String nowColor;\n String[][] type, color;\n boolean[][] reversal;\n String records = \"--\", redEatenList, blackEatenList;\n int redScore, blackScore;\n\n pu...
import Chess.chessComponent.*; import Chess.model.ChessBackup; import Chess.model.ChessboardPoint; import Chess.utils.FileUtils; import Chess.view.Chessboard; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import javax.swing.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import static Chess.utils.FileUtils.getCorrectSlash; import static Chess.view.Chessboard.COL_SIZE; import static Chess.view.Chessboard.ROW_SIZE; import static Chess.view.StartFrame.checkRecords;
12,557
package Chess.controller; /** * 这个类主要完成由窗体上组件触发的动作。 * 例如点击button等 * ChessGameFrame中组件调用本类的对象,在本类中的方法里完成逻辑运算,将运算的结果传递至chessboard中绘制 */ public class GameController { private Chessboard chessboard; public Gson gson = new Gson(); public GameController(Chessboard chessboard) { this.chessboard = chessboard; } public List<String> loadGameFromFile(String path) { try { List<String> chessData = Files.readAllLines(Path.of(path)); //chessboard.loadGame(chessData); return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame(); String[][] reversalString = new String[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalString[i][j] = String.valueOf(backup.getReversal()[i][j]); } } Map<String, JsonElement> data = new HashMap<>(); data.put("nowColor", gson.toJsonTree(backup.getNowColor())); data.put("type", gson.toJsonTree(backup.getType())); data.put("color", gson.toJsonTree(backup.getColor())); data.put("reversal", gson.toJsonTree(reversalString)); data.put("records", gson.toJsonTree(backup.getRecords())); data.put("redEatenList", gson.toJsonTree(backup.getRedEatenList())); data.put("blackEatenList", gson.toJsonTree(backup.getBlackEatenList())); data.put("redScore", gson.toJsonTree(backup.getRedScore())); data.put("blackScore", gson.toJsonTree(backup.getBlackScore())); try { FileUtils.saveDataToFile("save", Base64.getEncoder().encodeToString(gson.toJson(data).getBytes(StandardCharsets.UTF_8)), "txt");
package Chess.controller; /** * 这个类主要完成由窗体上组件触发的动作。 * 例如点击button等 * ChessGameFrame中组件调用本类的对象,在本类中的方法里完成逻辑运算,将运算的结果传递至chessboard中绘制 */ public class GameController { private Chessboard chessboard; public Gson gson = new Gson(); public GameController(Chessboard chessboard) { this.chessboard = chessboard; } public List<String> loadGameFromFile(String path) { try { List<String> chessData = Files.readAllLines(Path.of(path)); //chessboard.loadGame(chessData); return chessData; } catch (IOException e) { e.printStackTrace(); } return null; } public void toGSon() { ChessBackup backup = chessboard.backupGame(); String[][] reversalString = new String[ROW_SIZE][COL_SIZE]; for (int i = 0; i < ROW_SIZE; i++) { for (int j = 0; j < COL_SIZE; j++) { reversalString[i][j] = String.valueOf(backup.getReversal()[i][j]); } } Map<String, JsonElement> data = new HashMap<>(); data.put("nowColor", gson.toJsonTree(backup.getNowColor())); data.put("type", gson.toJsonTree(backup.getType())); data.put("color", gson.toJsonTree(backup.getColor())); data.put("reversal", gson.toJsonTree(reversalString)); data.put("records", gson.toJsonTree(backup.getRecords())); data.put("redEatenList", gson.toJsonTree(backup.getRedEatenList())); data.put("blackEatenList", gson.toJsonTree(backup.getBlackEatenList())); data.put("redScore", gson.toJsonTree(backup.getRedScore())); data.put("blackScore", gson.toJsonTree(backup.getBlackScore())); try { FileUtils.saveDataToFile("save", Base64.getEncoder().encodeToString(gson.toJson(data).getBytes(StandardCharsets.UTF_8)), "txt");
JOptionPane.showMessageDialog(null, "保存在 " + System.getProperty("user.dir") + getCorrectSlash() + "save.txt");
4
2023-12-31 05:50:13+00:00
16k
psobiech/opengr8on
client/src/main/java/pl/psobiech/opengr8on/client/Main.java
[ { "identifier": "CLUDevice", "path": "lib/src/main/java/pl/psobiech/opengr8on/client/device/CLUDevice.java", "snippet": "public class CLUDevice {\n private final String name;\n\n private final Long serialNumber;\n\n private final String macAddress;\n\n private Inet4Address address;\n\n pr...
import java.io.IOException; import java.net.Inet4Address; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; import java.util.Map; import java.util.Optional; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.psobiech.opengr8on.client.device.CLUDevice; import pl.psobiech.opengr8on.client.device.CLUDeviceConfig; import pl.psobiech.opengr8on.client.device.CipherTypeEnum; import pl.psobiech.opengr8on.exceptions.UnexpectedException; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil.NetworkInterfaceDto; import pl.psobiech.opengr8on.util.ObjectMapperFactory; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.Util; import pl.psobiech.opengr8on.xml.interfaces.CLU; import pl.psobiech.opengr8on.xml.interfaces.InterfaceRegistry; import pl.psobiech.opengr8on.xml.omp.OmpReader;
13,943
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseGet(() -> { final CipherKey cipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); LOGGER.debug("Generated random project key: {}", cipherKey); return cipherKey; }); final Integer cluLimit = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.CLU_LIMIT_PATH_OPTION)) .map(Integer::parseInt) .orElse(1); discover(networkInterface, projectCipherKey, cluLimit, interfaceRegistry); return; } final Inet4Address ipAddress = CLIParameters.getRemoteIPAddress(commandLine); if (commandLine.hasOption(CLIParameters.FETCH_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.PROJECT_PATH_OPTION)) .map(Paths::get) .map(OmpReader::readProjectCipherKey) .orElseThrow(() -> new UnexpectedException("Provide a project location")); final CLUDevice device = fetchDevice(networkInterface, ipAddress, projectCipherKey, interfaceRegistry); // try (CLUClient client = new CLUClient(networkInterface, device, projectCipherKey)) { // // NOP // } } else if (commandLine.hasOption(CLIParameters.EXECUTE_OPTION)) { final String command = commandLine.getOptionValue(CLIParameters.EXECUTE_OPTION); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseThrow(() -> new UnexpectedException("Provide a project location")); try (CLUClient client = new CLUClient(networkInterface.getAddress(), ipAddress, projectCipherKey)) { LOGGER.info(client.execute(command).get()); final Boolean success = client.startTFTPdServer().get(); if (success) { final CLUDevice device = client.getCluDevice(); final Path rootPath = Paths.get(".").resolve("live").resolve(String.valueOf(device.getSerialNumber())); FileUtil.mkdir(rootPath); for (CLUFiles cluLikeFile : CLUFiles.values()) { if (!cluLikeFile.isReadable() || !cluLikeFile.isWritable()) { continue; } final Path target = rootPath.resolve(cluLikeFile.getDevice() + "_" + StringUtils.lowerCase(cluLikeFile.getFileName())); try { client.downloadFile(cluLikeFile.getLocation(), target); } catch (Exception e) { FileUtil.deleteQuietly(target); } } } } } } private static void discover( NetworkInterfaceDto networkInterface, CipherKey projectCipherKey, Integer cluLimit, InterfaceRegistry interfaceRegistry ) { try (Client broadcastClient = new Client(networkInterface.getAddress())) { broadcastClient.discover( projectCipherKey, PRIVATE_KEYS, DEFAULT_LONG_TIMEOUT, cluLimit ) .map(cluDevice -> { LOGGER.debug("Discovered device: {}", cluDevice); return new CLUClient(networkInterface.getAddress(), cluDevice); }) .forEach(client -> { try (client) { final CLUDevice device = client.getCluDevice(); client.updateCipherKey(projectCipherKey) .get(); client.reset(DEFAULT_LONG_TIMEOUT) .get();
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.client; public class Main { private static final Duration DEFAULT_LONG_TIMEOUT = Duration.ofMillis(30_000); private static final int TIMEOUT = 4_000; private static final Logger LOGGER = LoggerFactory.getLogger(Main.class); private static final Map<Long, byte[]> PRIVATE_KEYS = Map.of( 0x0L, "00000000".getBytes() ); private static final Inet4Address MIN_IP = IPv4AddressUtil.parseIPv4("10.72.144.1"); private Main() { // NOP } public static void main(String[] args) throws Exception { final CommandLine commandLine = new DefaultParser().parse(CLIParameters.OPTIONS, args); if (commandLine.hasOption(CLIParameters.HELP_OPTION)) { new HelpFormatter() .printHelp("java -jar client.jar", CLIParameters.OPTIONS); System.exit(0); } // final NetworkInterfaceDto networkInterface = CLIParameters.getNetworkInterface(commandLine); LOGGER.debug("Using network interface: {}", networkInterface); if (commandLine.hasOption(CLIParameters.DISCOVER_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseGet(() -> { final CipherKey cipherKey = new CipherKey(RandomUtil.bytes(16), RandomUtil.bytes(16)); LOGGER.debug("Generated random project key: {}", cipherKey); return cipherKey; }); final Integer cluLimit = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.CLU_LIMIT_PATH_OPTION)) .map(Integer::parseInt) .orElse(1); discover(networkInterface, projectCipherKey, cluLimit, interfaceRegistry); return; } final Inet4Address ipAddress = CLIParameters.getRemoteIPAddress(commandLine); if (commandLine.hasOption(CLIParameters.FETCH_OPTION)) { final InterfaceRegistry interfaceRegistry = CLIParameters.getInterfaceRegistry(commandLine); final CipherKey projectCipherKey = Optional.ofNullable(commandLine.getOptionValue(CLIParameters.PROJECT_PATH_OPTION)) .map(Paths::get) .map(OmpReader::readProjectCipherKey) .orElseThrow(() -> new UnexpectedException("Provide a project location")); final CLUDevice device = fetchDevice(networkInterface, ipAddress, projectCipherKey, interfaceRegistry); // try (CLUClient client = new CLUClient(networkInterface, device, projectCipherKey)) { // // NOP // } } else if (commandLine.hasOption(CLIParameters.EXECUTE_OPTION)) { final String command = commandLine.getOptionValue(CLIParameters.EXECUTE_OPTION); final CipherKey projectCipherKey = CLIParameters.getProjectCipherKey(commandLine) .orElseThrow(() -> new UnexpectedException("Provide a project location")); try (CLUClient client = new CLUClient(networkInterface.getAddress(), ipAddress, projectCipherKey)) { LOGGER.info(client.execute(command).get()); final Boolean success = client.startTFTPdServer().get(); if (success) { final CLUDevice device = client.getCluDevice(); final Path rootPath = Paths.get(".").resolve("live").resolve(String.valueOf(device.getSerialNumber())); FileUtil.mkdir(rootPath); for (CLUFiles cluLikeFile : CLUFiles.values()) { if (!cluLikeFile.isReadable() || !cluLikeFile.isWritable()) { continue; } final Path target = rootPath.resolve(cluLikeFile.getDevice() + "_" + StringUtils.lowerCase(cluLikeFile.getFileName())); try { client.downloadFile(cluLikeFile.getLocation(), target); } catch (Exception e) { FileUtil.deleteQuietly(target); } } } } } } private static void discover( NetworkInterfaceDto networkInterface, CipherKey projectCipherKey, Integer cluLimit, InterfaceRegistry interfaceRegistry ) { try (Client broadcastClient = new Client(networkInterface.getAddress())) { broadcastClient.discover( projectCipherKey, PRIVATE_KEYS, DEFAULT_LONG_TIMEOUT, cluLimit ) .map(cluDevice -> { LOGGER.debug("Discovered device: {}", cluDevice); return new CLUClient(networkInterface.getAddress(), cluDevice); }) .forEach(client -> { try (client) { final CLUDevice device = client.getCluDevice(); client.updateCipherKey(projectCipherKey) .get(); client.reset(DEFAULT_LONG_TIMEOUT) .get();
Util.repeatUntilTrueOrTimeout(
9
2023-12-23 09:56:14+00:00
16k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/render/ESP.java
[ { "identifier": "MayOBees", "path": "src/main/java/com/github/may2beez/mayobees/MayOBees.java", "snippet": "@Mod(modid = \"mayobees\", useMetadata=true)\npublic class MayOBees {\n public static final MayOBeesConfig CONFIG = new MayOBeesConfig();\n public static final Gson GSON = new GsonBuilder()....
import cc.polyfrost.oneconfig.config.core.OneColor; import com.github.may2beez.mayobees.MayOBees; import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.event.ClickEvent; import com.github.may2beez.mayobees.handler.GameStateHandler; import com.github.may2beez.mayobees.module.IModule; import com.github.may2beez.mayobees.util.HeadUtils; import com.github.may2beez.mayobees.util.RenderUtils; import com.google.gson.reflect.TypeToken; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.Vec3; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.stream.Collectors;
13,411
package com.github.may2beez.mayobees.module.impl.render; public class ESP implements IModule { private final Minecraft mc = Minecraft.getMinecraft(); private final HashMap<String, List<Location>> clickedFairySouls = new HashMap<>(); private final CopyOnWriteArrayList<EntityArmorStand> visibleFairySouls = new CopyOnWriteArrayList<>(); private final List<BlockPos> clickedGifts = new ArrayList<>(); private final File clickedFairySoulsFile = new File(mc.mcDataDir + "/config/mayobees/clickedFairySouls.json"); private static ESP instance; public static ESP getInstance() { if (instance == null) { instance = new ESP(); } return instance; } @Override public String getName() { return "ESP"; } public ESP() { try { if (!clickedFairySoulsFile.getParentFile().exists()) { clickedFairySoulsFile.getParentFile().mkdirs(); } if (!clickedFairySoulsFile.exists()) { clickedFairySoulsFile.createNewFile(); // fill it with empty array FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } catch (IOException e) { throw new RuntimeException(e); } FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(clickedFairySoulsFile); byte[] bytes = new byte[fileInputStream.available()]; fileInputStream.read(bytes); String json = new String(bytes); if (json.isEmpty()) return; Type type = new TypeToken<HashMap<String, List<Location>>>() { }.getType(); try { HashMap<String, List<Location>> locations = MayOBees.GSON.fromJson(json, type); if (locations == null) return; clickedFairySouls.putAll(locations); } catch (Exception e) { e.printStackTrace(); saveClickedFairySouls(); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } private void saveClickedFairySouls() { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public void resetClickedFairySouls() { clickedFairySouls.clear(); saveClickedFairySouls(); } public void resetClickedFairySoulsOnlyCurrentIsland() { clickedFairySouls.remove(GameStateHandler.getInstance().getLocation().getName()); saveClickedFairySouls(); } public void addAllVisibleFairySoulsToClickedList() { List<Location> thisLocationFairySouls = clickedFairySouls.computeIfAbsent(GameStateHandler.getInstance().getLocation().getName(), k -> new ArrayList<>()); for (EntityArmorStand entityArmorStand : visibleFairySouls) { if (listHasElement(thisLocationFairySouls, Location.of(entityArmorStand.getPosition()))) continue; thisLocationFairySouls.add(Location.of(entityArmorStand.getPosition())); } clickedFairySouls.put(GameStateHandler.getInstance().getLocation().getName(), thisLocationFairySouls); saveClickedFairySouls(); } public void resetClickedGifts() { clickedGifts.clear(); } @Override public boolean isRunning() {
package com.github.may2beez.mayobees.module.impl.render; public class ESP implements IModule { private final Minecraft mc = Minecraft.getMinecraft(); private final HashMap<String, List<Location>> clickedFairySouls = new HashMap<>(); private final CopyOnWriteArrayList<EntityArmorStand> visibleFairySouls = new CopyOnWriteArrayList<>(); private final List<BlockPos> clickedGifts = new ArrayList<>(); private final File clickedFairySoulsFile = new File(mc.mcDataDir + "/config/mayobees/clickedFairySouls.json"); private static ESP instance; public static ESP getInstance() { if (instance == null) { instance = new ESP(); } return instance; } @Override public String getName() { return "ESP"; } public ESP() { try { if (!clickedFairySoulsFile.getParentFile().exists()) { clickedFairySoulsFile.getParentFile().mkdirs(); } if (!clickedFairySoulsFile.exists()) { clickedFairySoulsFile.createNewFile(); // fill it with empty array FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } catch (IOException e) { throw new RuntimeException(e); } FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(clickedFairySoulsFile); byte[] bytes = new byte[fileInputStream.available()]; fileInputStream.read(bytes); String json = new String(bytes); if (json.isEmpty()) return; Type type = new TypeToken<HashMap<String, List<Location>>>() { }.getType(); try { HashMap<String, List<Location>> locations = MayOBees.GSON.fromJson(json, type); if (locations == null) return; clickedFairySouls.putAll(locations); } catch (Exception e) { e.printStackTrace(); saveClickedFairySouls(); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileInputStream != null) try { fileInputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } private void saveClickedFairySouls() { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(clickedFairySoulsFile); String json = MayOBees.GSON.toJson(clickedFairySouls); fileOutputStream.write(json.getBytes()); } catch (IOException e) { throw new RuntimeException(e); } finally { if (fileOutputStream != null) try { fileOutputStream.close(); } catch (IOException e) { throw new RuntimeException(e); } } } public void resetClickedFairySouls() { clickedFairySouls.clear(); saveClickedFairySouls(); } public void resetClickedFairySoulsOnlyCurrentIsland() { clickedFairySouls.remove(GameStateHandler.getInstance().getLocation().getName()); saveClickedFairySouls(); } public void addAllVisibleFairySoulsToClickedList() { List<Location> thisLocationFairySouls = clickedFairySouls.computeIfAbsent(GameStateHandler.getInstance().getLocation().getName(), k -> new ArrayList<>()); for (EntityArmorStand entityArmorStand : visibleFairySouls) { if (listHasElement(thisLocationFairySouls, Location.of(entityArmorStand.getPosition()))) continue; thisLocationFairySouls.add(Location.of(entityArmorStand.getPosition())); } clickedFairySouls.put(GameStateHandler.getInstance().getLocation().getName(), thisLocationFairySouls); saveClickedFairySouls(); } public void resetClickedGifts() { clickedGifts.clear(); } @Override public boolean isRunning() {
return MayOBeesConfig.chestESP || MayOBeesConfig.fairySoulESP || MayOBeesConfig.giftESP;
1
2023-12-24 15:39:11+00:00
16k
Trodev-IT/ScanHub
app/src/main/java/com/trodev/scanhub/HomeFragment.java
[ { "identifier": "EmailActivity", "path": "app/src/main/java/com/trodev/scanhub/activities/EmailActivity.java", "snippet": "public class EmailActivity extends AppCompatActivity {\n\n public final static int QRCodeWidth = 500;\n Bitmap bitmap;\n private Button make_btn, save_btn, downloadBtn;\n ...
import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import com.google.android.material.card.MaterialCardView; import com.trodev.scanhub.activities.EmailActivity; import com.trodev.scanhub.activities.LocationActivity; import com.trodev.scanhub.activities.ProductQrActivity; import com.trodev.scanhub.activities.ScanGalleryActivity; import com.trodev.scanhub.activities.ScannerActivity; import com.trodev.scanhub.activities.SmsActivity; import com.trodev.scanhub.activities.URLActivity; import com.trodev.scanhub.activities.WifiQrActivity;
12,473
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() { startActivity(new Intent(getContext(), WifiQrActivity.class)); } private void goto_message() {
package com.trodev.scanhub; public class HomeFragment extends Fragment { MaterialCardView product_qr, message, wifi; MaterialCardView email_qr, location_qr, url_qr; public HomeFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); /*init views*/ product_qr = view.findViewById(R.id.product_qr); message = view.findViewById(R.id.message); wifi = view.findViewById(R.id.wifi); email_qr = view.findViewById(R.id.email_qr); location_qr = view.findViewById(R.id.location_qr); url_qr = view.findViewById(R.id.url_qr); /*set on click listener*/ product_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_product(); } }); message.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_message(); } }); wifi.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goto_wifi(); } }); email_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_email(); } }); location_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_location(); } }); url_qr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { goto_url(); } }); return view; } private void goto_url() { startActivity(new Intent(getContext(), URLActivity.class)); } private void goto_location() { startActivity(new Intent(getContext(), LocationActivity.class)); } private void goto_email() { startActivity(new Intent(getContext(), EmailActivity.class)); } private void goto_wifi() { startActivity(new Intent(getContext(), WifiQrActivity.class)); } private void goto_message() {
startActivity(new Intent(getContext(), SmsActivity.class));
5
2023-12-26 05:10:38+00:00
16k
HuXin0817/shop_api
buyer-api/src/main/java/cn/lili/controller/distribution/DistributionGoodsBuyerController.java
[ { "identifier": "ResultCode", "path": "framework/src/main/java/cn/lili/common/enums/ResultCode.java", "snippet": "public enum ResultCode {\n\n /**\n * 成功状态码\n */\n SUCCESS(200, \"成功\"),\n\n /**\n * 失败返回码\n */\n ERROR(400, \"服务器繁忙,请稍后重试\"),\n\n /**\n * 失败返回码\n */\n ...
import cn.lili.common.aop.annotation.PreventDuplicateSubmissions; import cn.lili.common.enums.ResultCode; import cn.lili.common.enums.ResultUtil; import cn.lili.common.exception.ServiceException; import cn.lili.common.vo.ResultMessage; import cn.lili.modules.distribution.entity.dto.DistributionGoodsSearchParams; import cn.lili.modules.distribution.entity.vos.DistributionGoodsVO; import cn.lili.modules.distribution.service.DistributionGoodsService; import cn.lili.modules.distribution.service.DistributionSelectedGoodsService; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.constraints.NotNull;
11,463
package cn.lili.controller.distribution; /** * 买家端,分销商品接口 * * @author Bulbasaur * @since 2020/11/16 10:06 下午 */ @RestController @Api(tags = "买家端,分销商品接口") @RequestMapping("/buyer/distribution/goods") public class DistributionGoodsBuyerController { /** * 分销商品 */ @Autowired private DistributionGoodsService distributionGoodsService; /** * 选择分销商品 */ @Autowired private DistributionSelectedGoodsService distributionSelectedGoodsService; @ApiOperation(value = "获取分销商商品列表") @GetMapping public ResultMessage<IPage<DistributionGoodsVO>> distributionGoods(DistributionGoodsSearchParams distributionGoodsSearchParams) { return ResultUtil.data(distributionGoodsService.goodsPage(distributionGoodsSearchParams)); } @PreventDuplicateSubmissions @ApiOperation(value = "选择分销商品") @ApiImplicitParams({ @ApiImplicitParam(name = "distributionGoodsId", value = "分销ID", required = true, dataType = "String", paramType = "path"), @ApiImplicitParam(name = "checked", value = "是否选择", required = true, dataType = "boolean", paramType = "query") }) @GetMapping(value = "/checked/{distributionGoodsId}") public ResultMessage<Object> distributionCheckGoods( @NotNull(message = "分销商品不能为空") @PathVariable("distributionGoodsId") String distributionGoodsId, Boolean checked) { boolean result = false; if (checked) { result = distributionSelectedGoodsService.add(distributionGoodsId); } else { result = distributionSelectedGoodsService.delete(distributionGoodsId); } //判断操作结果 if (result) { return ResultUtil.success(ResultCode.SUCCESS); } else {
package cn.lili.controller.distribution; /** * 买家端,分销商品接口 * * @author Bulbasaur * @since 2020/11/16 10:06 下午 */ @RestController @Api(tags = "买家端,分销商品接口") @RequestMapping("/buyer/distribution/goods") public class DistributionGoodsBuyerController { /** * 分销商品 */ @Autowired private DistributionGoodsService distributionGoodsService; /** * 选择分销商品 */ @Autowired private DistributionSelectedGoodsService distributionSelectedGoodsService; @ApiOperation(value = "获取分销商商品列表") @GetMapping public ResultMessage<IPage<DistributionGoodsVO>> distributionGoods(DistributionGoodsSearchParams distributionGoodsSearchParams) { return ResultUtil.data(distributionGoodsService.goodsPage(distributionGoodsSearchParams)); } @PreventDuplicateSubmissions @ApiOperation(value = "选择分销商品") @ApiImplicitParams({ @ApiImplicitParam(name = "distributionGoodsId", value = "分销ID", required = true, dataType = "String", paramType = "path"), @ApiImplicitParam(name = "checked", value = "是否选择", required = true, dataType = "boolean", paramType = "query") }) @GetMapping(value = "/checked/{distributionGoodsId}") public ResultMessage<Object> distributionCheckGoods( @NotNull(message = "分销商品不能为空") @PathVariable("distributionGoodsId") String distributionGoodsId, Boolean checked) { boolean result = false; if (checked) { result = distributionSelectedGoodsService.add(distributionGoodsId); } else { result = distributionSelectedGoodsService.delete(distributionGoodsId); } //判断操作结果 if (result) { return ResultUtil.success(ResultCode.SUCCESS); } else {
throw new ServiceException(ResultCode.ERROR);
2
2023-12-24 19:45:18+00:00
16k
Yanyutin753/PandoraNext-TokensTool
rearServer/src/main/java/com/tokensTool/pandoraNext/controller/autoTokenController.java
[ { "identifier": "Result", "path": "rearServer/src/main/java/com/tokensTool/pandoraNext/pojo/Result.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class Result {\n\n /**\n * 响应码,1 代表成功; 0 代表失败\n */\n\n private Integer code;\n /**\n * 响应信息 描述字符串\n */\n\n...
import com.tokensTool.pandoraNext.anno.Log; import com.tokensTool.pandoraNext.pojo.Result; import com.tokensTool.pandoraNext.pojo.token; import com.tokensTool.pandoraNext.service.impl.poolServiceImpl; import com.tokensTool.pandoraNext.service.impl.shareServiceImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.*; import java.util.List;
13,832
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired private poolServiceImpl poolService; @Autowired private shareServiceImpl shareService; /** * 自动更新access_Token和share_token * 更换tokens.json里存储的Tokens * 自动重启 * * @return "更新成功" or "更新失败" * @throws Exception */ @Log @Scheduled(cron = "0 0 */6 * * ?") public void toUpdateToken() { try { log.info("开始自动检查更新refresh_token,session_token,生成和刷新share_token,pool_token.........................."); toUpdateAllToken(); } catch (Exception e) { e.printStackTrace(); }
package com.tokensTool.pandoraNext.controller; /** * @author Yangyang * @create 2023-11-11 18:19 */ @Slf4j @RestController @RequestMapping("/api") public class autoTokenController { @Autowired private com.tokensTool.pandoraNext.service.apiService apiService; @Autowired private poolServiceImpl poolService; @Autowired private shareServiceImpl shareService; /** * 自动更新access_Token和share_token * 更换tokens.json里存储的Tokens * 自动重启 * * @return "更新成功" or "更新失败" * @throws Exception */ @Log @Scheduled(cron = "0 0 */6 * * ?") public void toUpdateToken() { try { log.info("开始自动检查更新refresh_token,session_token,生成和刷新share_token,pool_token.........................."); toUpdateAllToken(); } catch (Exception e) { e.printStackTrace(); }
log.info(Result.error("自动检查更新access_token,share_token和pool_token失败").toString());
0
2023-11-17 11:37:37+00:00
16k
quarkiverse/quarkus-langchain4j
openai/azure-openai/runtime/src/main/java/io/quarkiverse/langchain4j/azure/openai/runtime/AzureOpenAiRecorder.java
[ { "identifier": "firstOrDefault", "path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/OptionalUtil.java", "snippet": "@SafeVarargs\npublic static <T> T firstOrDefault(T defaultValue, Optional<T>... values) {\n for (Optional<T> o : values) {\n if (o != null && o.isPresent()) ...
import static io.quarkiverse.langchain4j.runtime.OptionalUtil.firstOrDefault; import java.util.function.Supplier; import io.quarkiverse.langchain4j.azure.openai.AzureOpenAiChatModel; import io.quarkiverse.langchain4j.azure.openai.AzureOpenAiEmbeddingModel; import io.quarkiverse.langchain4j.azure.openai.AzureOpenAiStreamingChatModel; import io.quarkiverse.langchain4j.azure.openai.runtime.config.ChatModelConfig; import io.quarkiverse.langchain4j.azure.openai.runtime.config.EmbeddingModelConfig; import io.quarkiverse.langchain4j.azure.openai.runtime.config.Langchain4jAzureOpenAiConfig; import io.quarkiverse.langchain4j.openai.QuarkusOpenAiClient; import io.quarkus.runtime.ShutdownContext; import io.quarkus.runtime.annotations.Recorder;
11,660
package io.quarkiverse.langchain4j.azure.openai.runtime; @Recorder public class AzureOpenAiRecorder { public Supplier<?> chatModel(Langchain4jAzureOpenAiConfig runtimeConfig) { ChatModelConfig chatModelConfig = runtimeConfig.chatModel(); var builder = AzureOpenAiChatModel.builder() .baseUrl(getBaseUrl(runtimeConfig)) .apiKey(runtimeConfig.apiKey()) .apiVersion(runtimeConfig.apiVersion()) .timeout(runtimeConfig.timeout()) .maxRetries(runtimeConfig.maxRetries()) .logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests())) .logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses())) .temperature(chatModelConfig.temperature()) .topP(chatModelConfig.topP()) .presencePenalty(chatModelConfig.presencePenalty()) .frequencyPenalty(chatModelConfig.frequencyPenalty()); if (chatModelConfig.maxTokens().isPresent()) { builder.maxTokens(chatModelConfig.maxTokens().get()); } return new Supplier<>() { @Override public Object get() { return builder.build(); } }; } public Supplier<?> streamingChatModel(Langchain4jAzureOpenAiConfig runtimeConfig) { ChatModelConfig chatModelConfig = runtimeConfig.chatModel(); var builder = AzureOpenAiStreamingChatModel.builder() .baseUrl(getBaseUrl(runtimeConfig)) .apiKey(runtimeConfig.apiKey()) .timeout(runtimeConfig.timeout()) .logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests())) .logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses())) .temperature(chatModelConfig.temperature()) .topP(chatModelConfig.topP()) .presencePenalty(chatModelConfig.presencePenalty()) .frequencyPenalty(chatModelConfig.frequencyPenalty()); if (chatModelConfig.maxTokens().isPresent()) { builder.maxTokens(chatModelConfig.maxTokens().get()); } return new Supplier<>() { @Override public Object get() { return builder.build(); } }; } public Supplier<?> embeddingModel(Langchain4jAzureOpenAiConfig runtimeConfig) { EmbeddingModelConfig embeddingModelConfig = runtimeConfig.embeddingModel(); var builder = AzureOpenAiEmbeddingModel.builder() .baseUrl(getBaseUrl(runtimeConfig)) .apiKey(runtimeConfig.apiKey()) .timeout(runtimeConfig.timeout()) .maxRetries(runtimeConfig.maxRetries()) .logRequests(firstOrDefault(false, embeddingModelConfig.logRequests(), runtimeConfig.logRequests())) .logResponses(firstOrDefault(false, embeddingModelConfig.logResponses(), runtimeConfig.logResponses())); return new Supplier<>() { @Override public Object get() { return builder.build(); } }; } private String getBaseUrl(Langchain4jAzureOpenAiConfig runtimeConfig) { var baseUrl = runtimeConfig.baseUrl(); return !baseUrl.trim().isEmpty() ? baseUrl : String.format("https://%s.openai.azure.com/openai/deployments/%s", runtimeConfig.resourceName(), runtimeConfig.deploymentId()); } public void cleanUp(ShutdownContext shutdown) { shutdown.addShutdownTask(new Runnable() { @Override public void run() {
package io.quarkiverse.langchain4j.azure.openai.runtime; @Recorder public class AzureOpenAiRecorder { public Supplier<?> chatModel(Langchain4jAzureOpenAiConfig runtimeConfig) { ChatModelConfig chatModelConfig = runtimeConfig.chatModel(); var builder = AzureOpenAiChatModel.builder() .baseUrl(getBaseUrl(runtimeConfig)) .apiKey(runtimeConfig.apiKey()) .apiVersion(runtimeConfig.apiVersion()) .timeout(runtimeConfig.timeout()) .maxRetries(runtimeConfig.maxRetries()) .logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests())) .logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses())) .temperature(chatModelConfig.temperature()) .topP(chatModelConfig.topP()) .presencePenalty(chatModelConfig.presencePenalty()) .frequencyPenalty(chatModelConfig.frequencyPenalty()); if (chatModelConfig.maxTokens().isPresent()) { builder.maxTokens(chatModelConfig.maxTokens().get()); } return new Supplier<>() { @Override public Object get() { return builder.build(); } }; } public Supplier<?> streamingChatModel(Langchain4jAzureOpenAiConfig runtimeConfig) { ChatModelConfig chatModelConfig = runtimeConfig.chatModel(); var builder = AzureOpenAiStreamingChatModel.builder() .baseUrl(getBaseUrl(runtimeConfig)) .apiKey(runtimeConfig.apiKey()) .timeout(runtimeConfig.timeout()) .logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests())) .logResponses(firstOrDefault(false, chatModelConfig.logResponses(), runtimeConfig.logResponses())) .temperature(chatModelConfig.temperature()) .topP(chatModelConfig.topP()) .presencePenalty(chatModelConfig.presencePenalty()) .frequencyPenalty(chatModelConfig.frequencyPenalty()); if (chatModelConfig.maxTokens().isPresent()) { builder.maxTokens(chatModelConfig.maxTokens().get()); } return new Supplier<>() { @Override public Object get() { return builder.build(); } }; } public Supplier<?> embeddingModel(Langchain4jAzureOpenAiConfig runtimeConfig) { EmbeddingModelConfig embeddingModelConfig = runtimeConfig.embeddingModel(); var builder = AzureOpenAiEmbeddingModel.builder() .baseUrl(getBaseUrl(runtimeConfig)) .apiKey(runtimeConfig.apiKey()) .timeout(runtimeConfig.timeout()) .maxRetries(runtimeConfig.maxRetries()) .logRequests(firstOrDefault(false, embeddingModelConfig.logRequests(), runtimeConfig.logRequests())) .logResponses(firstOrDefault(false, embeddingModelConfig.logResponses(), runtimeConfig.logResponses())); return new Supplier<>() { @Override public Object get() { return builder.build(); } }; } private String getBaseUrl(Langchain4jAzureOpenAiConfig runtimeConfig) { var baseUrl = runtimeConfig.baseUrl(); return !baseUrl.trim().isEmpty() ? baseUrl : String.format("https://%s.openai.azure.com/openai/deployments/%s", runtimeConfig.resourceName(), runtimeConfig.deploymentId()); } public void cleanUp(ShutdownContext shutdown) { shutdown.addShutdownTask(new Runnable() { @Override public void run() {
QuarkusOpenAiClient.clearCache();
7
2023-11-13 09:10:27+00:00
16k
qiusunshine/xiu
clinglibrary/src/main/java/org/fourthline/cling/ManagedUpnpService.java
[ { "identifier": "ControlPoint", "path": "clinglibrary/src/main/java/org/fourthline/cling/controlpoint/ControlPoint.java", "snippet": "public interface ControlPoint {\n\n public UpnpServiceConfiguration getConfiguration();\n public ProtocolFactory getProtocolFactory();\n public Registry getRegis...
import org.fourthline.cling.controlpoint.ControlPoint; import org.fourthline.cling.model.meta.LocalDevice; import org.fourthline.cling.model.meta.RemoteDevice; import org.fourthline.cling.protocol.ProtocolFactory; import org.fourthline.cling.registry.Registry; import org.fourthline.cling.registry.RegistryListener; import org.fourthline.cling.registry.event.After; import org.fourthline.cling.registry.event.Before; import org.fourthline.cling.registry.event.FailedRemoteDeviceDiscovery; import org.fourthline.cling.registry.event.LocalDeviceDiscovery; import org.fourthline.cling.registry.event.Phase; import org.fourthline.cling.registry.event.RegistryShutdown; import org.fourthline.cling.registry.event.RemoteDeviceDiscovery; import org.fourthline.cling.transport.DisableRouter; import org.fourthline.cling.transport.EnableRouter; import org.fourthline.cling.transport.Router; import java.util.logging.Logger; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Event; import javax.enterprise.event.Observes; import javax.enterprise.inject.Any; import javax.enterprise.inject.Instance; import javax.enterprise.util.AnnotationLiteral; import javax.inject.Inject;
12,898
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.fourthline.cling; /** * Adapter for CDI environments. * <p> * The CDI container provides injectable instances of Cling UPnP interfaces, e.g. * you can <code>@Inject Registry</code> or <code>@Inject ControlPoint</code>. * </p> * <p> * Furthermore, this adapter also binds Cling into the CDI eventing system. You * can <code>@Observe RemoteDeviceDiscoveryStart</code> etc. events of the * registry. * </p> * <p> * Even better, in the future you might be able to listen to GENA UPnP events with * the same API - although this will require some magic for subscription... * </p> * <p> * TODO: This is a work in progress. * </p> * * @author Christian Bauer */ @ApplicationScoped public class ManagedUpnpService implements UpnpService { final private static Logger log = Logger.getLogger(ManagedUpnpService.class.getName()); @Inject RegistryListenerAdapter registryListenerAdapter; @Inject Instance<UpnpServiceConfiguration> configuration; @Inject Instance<Registry> registryInstance; @Inject Instance<Router> routerInstance; @Inject Instance<ProtocolFactory> protocolFactoryInstance; @Inject Instance<ControlPoint> controlPointInstance; @Inject Event<EnableRouter> enableRouterEvent; @Inject Event<DisableRouter> disableRouterEvent; @Override public UpnpServiceConfiguration getConfiguration() { return configuration.get(); } @Override public ControlPoint getControlPoint() { return controlPointInstance.get(); } @Override public ProtocolFactory getProtocolFactory() { return protocolFactoryInstance.get(); } @Override public Registry getRegistry() { return registryInstance.get(); } @Override public Router getRouter() { return routerInstance.get(); } public void start(@Observes Start start) { log.info(">>> Starting managed UPnP service..."); // First start the registry before we can receive messages through the transport getRegistry().addListener(registryListenerAdapter); enableRouterEvent.fire(new EnableRouter()); log.info("<<< Managed UPnP service started successfully"); } @Override public void shutdown() { shutdown(null); } public void shutdown(@Observes Shutdown shutdown) { // Well, since java.util.logging has its own shutdown hook, this // might actually make it into the log or not... log.info(">>> Shutting down managed UPnP service..."); // First stop the registry and announce BYEBYE on the transport getRegistry().shutdown(); disableRouterEvent.fire(new DisableRouter()); getConfiguration().shutdown(); log.info("<<< Managed UPnP service shutdown completed"); } @ApplicationScoped static class RegistryListenerAdapter implements RegistryListener { @Inject @Any Event<RemoteDeviceDiscovery> remoteDeviceDiscoveryEvent; @Inject @Any Event<FailedRemoteDeviceDiscovery> failedRemoteDeviceDiscoveryEvent; @Inject @Any Event<LocalDeviceDiscovery> localDeviceDiscoveryEvent; @Inject @Any
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.fourthline.cling; /** * Adapter for CDI environments. * <p> * The CDI container provides injectable instances of Cling UPnP interfaces, e.g. * you can <code>@Inject Registry</code> or <code>@Inject ControlPoint</code>. * </p> * <p> * Furthermore, this adapter also binds Cling into the CDI eventing system. You * can <code>@Observe RemoteDeviceDiscoveryStart</code> etc. events of the * registry. * </p> * <p> * Even better, in the future you might be able to listen to GENA UPnP events with * the same API - although this will require some magic for subscription... * </p> * <p> * TODO: This is a work in progress. * </p> * * @author Christian Bauer */ @ApplicationScoped public class ManagedUpnpService implements UpnpService { final private static Logger log = Logger.getLogger(ManagedUpnpService.class.getName()); @Inject RegistryListenerAdapter registryListenerAdapter; @Inject Instance<UpnpServiceConfiguration> configuration; @Inject Instance<Registry> registryInstance; @Inject Instance<Router> routerInstance; @Inject Instance<ProtocolFactory> protocolFactoryInstance; @Inject Instance<ControlPoint> controlPointInstance; @Inject Event<EnableRouter> enableRouterEvent; @Inject Event<DisableRouter> disableRouterEvent; @Override public UpnpServiceConfiguration getConfiguration() { return configuration.get(); } @Override public ControlPoint getControlPoint() { return controlPointInstance.get(); } @Override public ProtocolFactory getProtocolFactory() { return protocolFactoryInstance.get(); } @Override public Registry getRegistry() { return registryInstance.get(); } @Override public Router getRouter() { return routerInstance.get(); } public void start(@Observes Start start) { log.info(">>> Starting managed UPnP service..."); // First start the registry before we can receive messages through the transport getRegistry().addListener(registryListenerAdapter); enableRouterEvent.fire(new EnableRouter()); log.info("<<< Managed UPnP service started successfully"); } @Override public void shutdown() { shutdown(null); } public void shutdown(@Observes Shutdown shutdown) { // Well, since java.util.logging has its own shutdown hook, this // might actually make it into the log or not... log.info(">>> Shutting down managed UPnP service..."); // First stop the registry and announce BYEBYE on the transport getRegistry().shutdown(); disableRouterEvent.fire(new DisableRouter()); getConfiguration().shutdown(); log.info("<<< Managed UPnP service shutdown completed"); } @ApplicationScoped static class RegistryListenerAdapter implements RegistryListener { @Inject @Any Event<RemoteDeviceDiscovery> remoteDeviceDiscoveryEvent; @Inject @Any Event<FailedRemoteDeviceDiscovery> failedRemoteDeviceDiscoveryEvent; @Inject @Any Event<LocalDeviceDiscovery> localDeviceDiscoveryEvent; @Inject @Any
Event<RegistryShutdown> registryShutdownEvent;
9
2023-11-10 14:28:40+00:00
16k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/managers/DevotionManager.java
[ { "identifier": "Deity", "path": "src/main/java/me/xidentified/devotions/Deity.java", "snippet": "public class Deity {\n private final Devotions plugin;\n // Getter methods below\n @Getter public final String name;\n @Getter private final String lore;\n @Getter private final String alignm...
import me.xidentified.devotions.Deity; import me.xidentified.devotions.Devotions; import me.xidentified.devotions.storage.DevotionData; import me.xidentified.devotions.storage.DevotionStorage; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Formatter; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import static org.bukkit.Bukkit.getServer;
11,327
package me.xidentified.devotions.managers; public class DevotionManager { private final Devotions plugin;
package me.xidentified.devotions.managers; public class DevotionManager { private final Devotions plugin;
private final DevotionStorage devotionStorage;
2
2023-11-10 07:03:24+00:00
16k
SplitfireUptown/datalinkx
flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/outputformat/BaseRichOutputFormat.java
[ { "identifier": "ErrorLimitConfig", "path": "flinkx/flinkx-core/src/main/java/com/dtstack/flinkx/config/ErrorLimitConfig.java", "snippet": "public class ErrorLimitConfig extends AbstractConfig {\n\n public static final String KEY_ERROR_RECORD_LIMIT = \"record\";\n public static final String KEY_ER...
import com.dtstack.flinkx.config.ErrorLimitConfig; import com.dtstack.flinkx.config.RestoreConfig; import com.dtstack.flinkx.constants.Metrics; import com.dtstack.flinkx.exception.WriteRecordException; import com.dtstack.flinkx.latch.BaseLatch; import com.dtstack.flinkx.latch.LocalLatch; import com.dtstack.flinkx.latch.MetricLatch; import com.dtstack.flinkx.log.DtLogger; import com.dtstack.flinkx.metrics.AccumulatorCollector; import com.dtstack.flinkx.metrics.BaseMetric; import com.dtstack.flinkx.metrics.RateCounter; import com.dtstack.flinkx.restore.FormatState; import com.dtstack.flinkx.util.ExceptionUtil; import com.dtstack.flinkx.util.GsonUtil; import com.dtstack.flinkx.util.UrlUtil; import com.dtstack.flinkx.writer.DirtyDataManager; import com.dtstack.flinkx.writer.ErrorLimiter; import com.google.gson.reflect.TypeToken; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.flink.api.common.accumulators.LongCounter; import org.apache.flink.api.common.io.CleanupWhenUnsuccessful; import org.apache.flink.configuration.Configuration; import org.apache.flink.streaming.api.operators.StreamingRuntimeContext; import org.apache.flink.types.Row; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import static com.dtstack.flinkx.writer.WriteErrorTypes.ERR_FORMAT_TRANSFORM; import static com.dtstack.flinkx.writer.WriteErrorTypes.ERR_NULL_POINTER; import static com.dtstack.flinkx.writer.WriteErrorTypes.ERR_PRIMARY_CONFLICT;
12,217
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.outputformat; /** * Abstract Specification for all the OutputFormat defined in flinkx plugins * * Company: www.dtstack.com * @author huyifan.zju@163.com */ public abstract class BaseRichOutputFormat extends org.apache.flink.api.common.io.RichOutputFormat<Row> implements CleanupWhenUnsuccessful { protected final Logger LOG = LoggerFactory.getLogger(getClass()); protected String formatId; public static final String RUNNING_STATE = "RUNNING"; public static final int LOG_PRINT_INTERNAL = 2000; /** Dirty data manager */ protected DirtyDataManager dirtyDataManager; /** Dirty data storage path */ protected String dirtyPath; /** The hadoop config for dirty data storage */ protected Map<String,Object> dirtyHadoopConfig; /** The source table field names */ protected List<String> srcFieldNames; /** 批量提交条数 */ protected int batchInterval = 1; /** 存储用于批量写入的数据 */ protected List<Row> rows = new ArrayList(); /** 总记录数 */ protected LongCounter numWriteCounter; /** snapshot 中记录的总记录数 */ protected LongCounter snapshotWriteCounter; /** 错误记录数 */ protected LongCounter errCounter; /** Number of null pointer errors */ protected LongCounter nullErrCounter; /** Number of primary key conflict errors */ protected LongCounter duplicateErrCounter; /** Number of type conversion errors */ protected LongCounter conversionErrCounter; /** Number of other errors */ protected LongCounter otherErrCounter; /** 错误限制 */ protected ErrorLimiter errorLimiter; protected LongCounter bytesWriteCounter; protected LongCounter durationCounter; /** 错误阈值 */ protected Integer errors; /** 错误比例阈值 */ protected Double errorRatio; /** 批异常重试机制 */ protected String errorTryPlan; /** 任务名 */ protected String jobName = "defaultJobName"; /** 监控api根路径 */ protected String monitorUrl; /** 子任务编号 */ protected int taskNumber; /** 环境上下文 */ protected StreamingRuntimeContext context; /** 子任务数量 */ protected int numTasks; protected String jobId; protected RestoreConfig restoreConfig; protected FormatState formatState; protected Object initState; protected transient BaseMetric outputMetric; protected AccumulatorCollector accumulatorCollector; private long startTime; protected boolean initAccumulatorAndDirty = true;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flinkx.outputformat; /** * Abstract Specification for all the OutputFormat defined in flinkx plugins * * Company: www.dtstack.com * @author huyifan.zju@163.com */ public abstract class BaseRichOutputFormat extends org.apache.flink.api.common.io.RichOutputFormat<Row> implements CleanupWhenUnsuccessful { protected final Logger LOG = LoggerFactory.getLogger(getClass()); protected String formatId; public static final String RUNNING_STATE = "RUNNING"; public static final int LOG_PRINT_INTERNAL = 2000; /** Dirty data manager */ protected DirtyDataManager dirtyDataManager; /** Dirty data storage path */ protected String dirtyPath; /** The hadoop config for dirty data storage */ protected Map<String,Object> dirtyHadoopConfig; /** The source table field names */ protected List<String> srcFieldNames; /** 批量提交条数 */ protected int batchInterval = 1; /** 存储用于批量写入的数据 */ protected List<Row> rows = new ArrayList(); /** 总记录数 */ protected LongCounter numWriteCounter; /** snapshot 中记录的总记录数 */ protected LongCounter snapshotWriteCounter; /** 错误记录数 */ protected LongCounter errCounter; /** Number of null pointer errors */ protected LongCounter nullErrCounter; /** Number of primary key conflict errors */ protected LongCounter duplicateErrCounter; /** Number of type conversion errors */ protected LongCounter conversionErrCounter; /** Number of other errors */ protected LongCounter otherErrCounter; /** 错误限制 */ protected ErrorLimiter errorLimiter; protected LongCounter bytesWriteCounter; protected LongCounter durationCounter; /** 错误阈值 */ protected Integer errors; /** 错误比例阈值 */ protected Double errorRatio; /** 批异常重试机制 */ protected String errorTryPlan; /** 任务名 */ protected String jobName = "defaultJobName"; /** 监控api根路径 */ protected String monitorUrl; /** 子任务编号 */ protected int taskNumber; /** 环境上下文 */ protected StreamingRuntimeContext context; /** 子任务数量 */ protected int numTasks; protected String jobId; protected RestoreConfig restoreConfig; protected FormatState formatState; protected Object initState; protected transient BaseMetric outputMetric; protected AccumulatorCollector accumulatorCollector; private long startTime; protected boolean initAccumulatorAndDirty = true;
protected RateCounter rateCounter;
10
2023-11-16 02:22:52+00:00
16k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/AllTests.java
[ { "identifier": "DiffBlockXPathTest", "path": "core/src/test/java/com/exadel/etoolbox/anydiff/comparison/DiffBlockXPathTest.java", "snippet": "public class DiffBlockXPathTest {\n\n @Test\n public void shouldReportHtmlPath() throws IOException {\n try (\n InputStream leftInput...
import com.exadel.etoolbox.anydiff.comparison.DiffBlockXPathTest; import com.exadel.etoolbox.anydiff.comparison.DiffCountTest; import com.exadel.etoolbox.anydiff.comparison.DiffTaskTest; import com.exadel.etoolbox.anydiff.comparison.DiffTest; import com.exadel.etoolbox.anydiff.comparison.FragmentTest; import com.exadel.etoolbox.anydiff.comparison.MarkedStringTest; import com.exadel.etoolbox.anydiff.comparison.SpacesHandlingTest; import com.exadel.etoolbox.anydiff.comparison.preprocessor.PreprocessorsTest; import com.exadel.etoolbox.anydiff.runner.DiffRunnerTest; import com.exadel.etoolbox.anydiff.runner.FilterHelperTest; import com.exadel.etoolbox.anydiff.runner.FiltersTest; import org.junit.runner.RunWith; import org.junit.runners.Suite;
14,081
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class, DiffRunnerTest.class, DiffTaskTest.class,
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff; @RunWith(Suite.class) @Suite.SuiteClasses({ DiffTest.class, DiffRunnerTest.class, DiffTaskTest.class,
DiffCountTest.class,
1
2023-11-16 14:29:45+00:00
16k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/screen/AttachmentScreen.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMa...
import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.gui.screen.inventory.InventoryScreen; import net.minecraft.client.network.play.ClientPlayNetHandler; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Inventory; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.vector.Quaternion; import net.minecraft.util.math.vector.Vector3f; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import org.lwjgl.opengl.GL11; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.Gunscraft; import sheridan.gunscraft.container.AttachmentContainer; import sheridan.gunscraft.items.attachments.GenericAttachment; import sheridan.gunscraft.items.attachments.IGenericAttachment; import sheridan.gunscraft.items.attachments.util.GunAttachmentSlot; import sheridan.gunscraft.items.attachments.util.NBTAttachmentsMap; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.network.PacketHandler; import sheridan.gunscraft.network.packets.GiveBackItemPacket; import sheridan.gunscraft.network.packets.SetAttachmentPacket; import java.util.List;
13,730
package sheridan.gunscraft.screen; public class AttachmentScreen extends ContainerScreen<AttachmentContainer> { public static final ResourceLocation BACK_GROUND = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/attachment_screen.png"); private static final ResourceLocation DRAG_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/drag_button.png"); private static final ResourceLocation RESET_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/reset_button.png"); private final TranslationTextComponent title = new TranslationTextComponent("container.gunscraft.attachments"); private ItemStack heldStack; @Override public void onClose() { if (attachmentInventory != null) { ItemStack attachment = attachmentInventory.getStackInSlot(0); if (!attachment.isEmpty()) { PacketHandler.CommonChannel.sendToServer(new GiveBackItemPacket(Item.getIdFromItem(attachment.getItem()), attachment.getCount())); } } super.onClose(); } private IInventory inventory; private IInventory attachmentInventory; private List<GunAttachmentSlot> slots; private int selectedIndex = 0; private GunAttachmentSlot selectedSlot; private IGenericGun gun; private int maxIndex; private AttachmentContainer container; private boolean isMouseDruggingModel = false; private float modelRX; private float modelRY; private float tempModelRX; private float tempModelRY; private float dragStartX; private float dragStartY; private float dragX; private float dragY; private float tempDragX; private float tempDragY; private float scaleZoom; private float zoomMax = 50f; private float zoomMin = -50f; private boolean isResetBtnDown = false; private boolean isDragBtnDown = false; public AttachmentScreen(AttachmentContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) { super(screenContainer, inv, titleIn); this.inventory = screenContainer.playerInventory; this.attachmentInventory = screenContainer.attachmentInventory; this.container = screenContainer; } @Override public boolean mouseScrolled(double mouseX, double mouseY, double delta) { if (isMouseInModelArea(mouseX, mouseY)) { scaleZoom += delta; if (scaleZoom > zoomMax) { scaleZoom = zoomMax; } if (scaleZoom < zoomMin) { scaleZoom = zoomMin; } return false; } return super.mouseScrolled(mouseX, mouseY, delta); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (slots != null && slots.size() >= 1) { switch (keyCode) { case 263: selectedIndex = selectedIndex - 1 < 0 ? maxIndex : selectedIndex - 1; break; case 262: selectedIndex ++; break; case 265: handleAttachmentChange(true); break; case 264: handleAttachmentChange(false); break; } } return super.keyPressed(keyCode, scanCode, modifiers); } private void handleAttachmentChange(boolean install) { if (install) { ItemStack stack = attachmentInventory.getStackInSlot(0); System.out.println("000"); if (stack.getItem() instanceof IGenericAttachment) { System.out.println("111"); IGenericAttachment attachment = (IGenericAttachment) stack.getItem(); String slotName = selectedSlot.name; ItemStack gunStack = this.minecraft.player.getHeldItemMainhand(); if (gunStack.getItem() instanceof IGenericGun) { IGenericGun gun = (IGenericGun) gunStack.getItem(); if (NBTAttachmentsMap.set(slotName, attachment.getID(), gunStack, gun) != null) { PacketHandler.CommonChannel.sendToServer(new SetAttachmentPacket(attachment.getID(), slotName)); attachmentInventory.setInventorySlotContents(0, ItemStack.EMPTY); attachmentInventory.markDirty(); } } } } else { ItemStack gunStack = this.minecraft.player.getHeldItemMainhand(); if (gunStack.getItem() instanceof IGenericGun) { IGenericGun gun = (IGenericGun) gunStack.getItem();
package sheridan.gunscraft.screen; public class AttachmentScreen extends ContainerScreen<AttachmentContainer> { public static final ResourceLocation BACK_GROUND = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/attachment_screen.png"); private static final ResourceLocation DRAG_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/drag_button.png"); private static final ResourceLocation RESET_BUTTON = new ResourceLocation(Gunscraft.MOD_ID, "textures/gui/screen/reset_button.png"); private final TranslationTextComponent title = new TranslationTextComponent("container.gunscraft.attachments"); private ItemStack heldStack; @Override public void onClose() { if (attachmentInventory != null) { ItemStack attachment = attachmentInventory.getStackInSlot(0); if (!attachment.isEmpty()) { PacketHandler.CommonChannel.sendToServer(new GiveBackItemPacket(Item.getIdFromItem(attachment.getItem()), attachment.getCount())); } } super.onClose(); } private IInventory inventory; private IInventory attachmentInventory; private List<GunAttachmentSlot> slots; private int selectedIndex = 0; private GunAttachmentSlot selectedSlot; private IGenericGun gun; private int maxIndex; private AttachmentContainer container; private boolean isMouseDruggingModel = false; private float modelRX; private float modelRY; private float tempModelRX; private float tempModelRY; private float dragStartX; private float dragStartY; private float dragX; private float dragY; private float tempDragX; private float tempDragY; private float scaleZoom; private float zoomMax = 50f; private float zoomMin = -50f; private boolean isResetBtnDown = false; private boolean isDragBtnDown = false; public AttachmentScreen(AttachmentContainer screenContainer, PlayerInventory inv, ITextComponent titleIn) { super(screenContainer, inv, titleIn); this.inventory = screenContainer.playerInventory; this.attachmentInventory = screenContainer.attachmentInventory; this.container = screenContainer; } @Override public boolean mouseScrolled(double mouseX, double mouseY, double delta) { if (isMouseInModelArea(mouseX, mouseY)) { scaleZoom += delta; if (scaleZoom > zoomMax) { scaleZoom = zoomMax; } if (scaleZoom < zoomMin) { scaleZoom = zoomMin; } return false; } return super.mouseScrolled(mouseX, mouseY, delta); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (slots != null && slots.size() >= 1) { switch (keyCode) { case 263: selectedIndex = selectedIndex - 1 < 0 ? maxIndex : selectedIndex - 1; break; case 262: selectedIndex ++; break; case 265: handleAttachmentChange(true); break; case 264: handleAttachmentChange(false); break; } } return super.keyPressed(keyCode, scanCode, modifiers); } private void handleAttachmentChange(boolean install) { if (install) { ItemStack stack = attachmentInventory.getStackInSlot(0); System.out.println("000"); if (stack.getItem() instanceof IGenericAttachment) { System.out.println("111"); IGenericAttachment attachment = (IGenericAttachment) stack.getItem(); String slotName = selectedSlot.name; ItemStack gunStack = this.minecraft.player.getHeldItemMainhand(); if (gunStack.getItem() instanceof IGenericGun) { IGenericGun gun = (IGenericGun) gunStack.getItem(); if (NBTAttachmentsMap.set(slotName, attachment.getID(), gunStack, gun) != null) { PacketHandler.CommonChannel.sendToServer(new SetAttachmentPacket(attachment.getID(), slotName)); attachmentInventory.setInventorySlotContents(0, ItemStack.EMPTY); attachmentInventory.markDirty(); } } } } else { ItemStack gunStack = this.minecraft.player.getHeldItemMainhand(); if (gunStack.getItem() instanceof IGenericGun) { IGenericGun gun = (IGenericGun) gunStack.getItem();
IGenericAttachment attachment = NBTAttachmentsMap.set(selectedSlot.name, GenericAttachment.NONE, gunStack, gun);
3
2023-11-14 14:00:55+00:00
16k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/fragments/APKExplorerFragment.java
[ { "identifier": "TextEditorActivity", "path": "app/src/main/java/com/threethan/questpatcher/activities/TextEditorActivity.java", "snippet": "public class TextEditorActivity extends AppCompatActivity {\n\n private static final String find0 = \"android:extractNativeLibs=\\\"false\\\"\";\n private st...
import android.annotation.SuppressLint; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import androidx.activity.OnBackPressedCallback; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.appcompat.widget.PopupMenu; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.threethan.questpatcher.R; import com.threethan.questpatcher.activities.TextEditorActivity; import com.threethan.questpatcher.adapters.APKExplorerAdapter; import com.threethan.questpatcher.utils.APKEditorUtils; import com.threethan.questpatcher.utils.APKExplorer; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.tasks.DeleteFile; import com.threethan.questpatcher.utils.tasks.DeleteProject; import com.threethan.questpatcher.utils.tasks.ExportToStorage; import com.threethan.questpatcher.utils.tasks.SignAPK; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textview.MaterialTextView; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.util.Objects; import in.sunilpaulmathew.sCommon.CommonUtils.sCommonUtils; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils; import in.sunilpaulmathew.sCommon.PermissionUtils.sPermissionUtils;
10,812
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 05, 2021 */ public class APKExplorerFragment extends androidx.fragment.app.Fragment { private MaterialTextView mTitle; private LinearLayoutCompat mProgressLayout; private RecyclerView mRecyclerView; private APKExplorerAdapter mRecycleViewAdapter; private AppCompatImageButton saveBtn; public static APKExplorerFragment current; public void fail() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.already_patched)); alertDialog.show(); } public void failManifest() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.no_manifest)); alertDialog.show(); } public void succeed() { saveBtn.callOnClick(); } @SuppressLint("StringFormatInvalid") @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apkexplorer, container, false); AppCompatImageButton mBack = mRootView.findViewById(R.id.back); AppCompatImageButton mSave = mRootView.findViewById(R.id.save); // EDITED saveBtn = mSave; AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort); mTitle = mRootView.findViewById(R.id.title); mProgressLayout = mRootView.findViewById(R.id.progress_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); Common.setAppID(new File(Common.getPath()).getName()); mTitle.setText(getString(R.string.root)); mBack.setOnClickListener(v -> retainDialog()); mSave.setOnClickListener(v -> new SignAPK(requireActivity()).execute()); if (APKEditorUtils.isFullVersion(requireActivity())) { mSave.setVisibility(View.VISIBLE); }
package com.threethan.questpatcher.fragments; /* * Created by APK Explorer & Editor <apkeditor@protonmail.com> on March 05, 2021 */ public class APKExplorerFragment extends androidx.fragment.app.Fragment { private MaterialTextView mTitle; private LinearLayoutCompat mProgressLayout; private RecyclerView mRecyclerView; private APKExplorerAdapter mRecycleViewAdapter; private AppCompatImageButton saveBtn; public static APKExplorerFragment current; public void fail() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.already_patched)); alertDialog.show(); } public void failManifest() { AlertDialog alertDialog = new MaterialAlertDialogBuilder(requireActivity()) .setNegativeButton(R.string.cancel, (DialogInterface.OnClickListener) (d, w) -> { requireActivity().finish(); d.dismiss(); }).create(); alertDialog.setTitle(R.string.cancelling); alertDialog.setMessage(getString(R.string.no_manifest)); alertDialog.show(); } public void succeed() { saveBtn.callOnClick(); } @SuppressLint("StringFormatInvalid") @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View mRootView = inflater.inflate(R.layout.fragment_apkexplorer, container, false); AppCompatImageButton mBack = mRootView.findViewById(R.id.back); AppCompatImageButton mSave = mRootView.findViewById(R.id.save); // EDITED saveBtn = mSave; AppCompatImageButton mSortButton = mRootView.findViewById(R.id.sort); mTitle = mRootView.findViewById(R.id.title); mProgressLayout = mRootView.findViewById(R.id.progress_layout); mRecyclerView = mRootView.findViewById(R.id.recycler_view); Common.setAppID(new File(Common.getPath()).getName()); mTitle.setText(getString(R.string.root)); mBack.setOnClickListener(v -> retainDialog()); mSave.setOnClickListener(v -> new SignAPK(requireActivity()).execute()); if (APKEditorUtils.isFullVersion(requireActivity())) { mSave.setVisibility(View.VISIBLE); }
mRecyclerView.setLayoutManager(new GridLayoutManager(requireActivity(), APKExplorer.getSpanCount(requireActivity())));
3
2023-11-18 15:13:30+00:00
16k
martin-bian/DimpleBlog
dimple-system/src/main/java/com/dimple/modules/quartz/service/impl/QuartzJobServiceImpl.java
[ { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) ...
import cn.hutool.core.util.IdUtil; import com.dimple.exception.BadRequestException; import com.dimple.modules.quartz.domain.QuartzJob; import com.dimple.modules.quartz.domain.QuartzLog; import com.dimple.modules.quartz.repository.QuartzJobRepository; import com.dimple.modules.quartz.repository.QuartzLogRepository; import com.dimple.modules.quartz.service.QuartzJobService; import com.dimple.modules.quartz.service.dto.JobQueryCriteria; import com.dimple.modules.quartz.utils.QuartzManage; import com.dimple.utils.FileUtil; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import com.dimple.utils.StringUtils; import com.dimple.utils.ValidationUtil; import lombok.RequiredArgsConstructor; import org.quartz.CronExpression; import org.springframework.data.domain.Pageable; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set;
13,762
package com.dimple.modules.quartz.service.impl; /** * @className: QuartzJobServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @RequiredArgsConstructor @Service(value = "quartzJobService") public class QuartzJobServiceImpl implements QuartzJobService { private final QuartzJobRepository quartzJobRepository;
package com.dimple.modules.quartz.service.impl; /** * @className: QuartzJobServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @RequiredArgsConstructor @Service(value = "quartzJobService") public class QuartzJobServiceImpl implements QuartzJobService { private final QuartzJobRepository quartzJobRepository;
private final QuartzLogRepository quartzLogRepository;
4
2023-11-10 03:30:36+00:00
16k
LazyCoder0101/LazyCoder
ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/component/extendscompoment/customvariable/CustomVariableTextFieldForMuti.java
[ { "identifier": "CodeGenerationFrameHolder", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/CodeGenerationFrameHolder.java", "snippet": "public class CodeGenerationFrameHolder extends GeneralHolder {\n\n //public static final Color currentAdditiveColor = new Color(...
import com.lazycoder.uicodegeneration.component.CodeGenerationFrameHolder; import com.lazycoder.uicodegeneration.component.operation.component.CodeGenerationComponentInterface; import com.lazycoder.uicodegeneration.component.operation.component.CustomVariableMutipleInputBox; import com.lazycoder.uicodegeneration.generalframe.variable.AbstractVariable; import com.lazycoder.uicodegeneration.generalframe.variable.CustomVariable; import com.lazycoder.uicodegeneration.generalframe.variable.holder.AbstractVariableHolder; import com.lazycoder.uicodegeneration.generalframe.variable.holder.CustomVariableHolder; import com.lazycoder.utils.StringUtil; import com.lazycoder.utils.swing.LazyCoderOptionPane; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.ArrayList; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener;
14,379
package com.lazycoder.uicodegeneration.component.operation.component.extendscompoment.customvariable; /** * 内部的变量输入框 * * @author admin */ public class CustomVariableTextFieldForMuti extends JTextField { /** * */ private static final long serialVersionUID = 7821943593668414212L; private CustomVariableParam customVariableParam; private CustomVariable customVariable; private CustomVariableMutipleInputBox CustomVariableMutipleInputBox = null; public CustomVariableTextFieldForMuti(CustomVariableParam customVariableParam, CustomVariable customVariable) { super(); this.CustomVariableMutipleInputBox = customVariableParam.getCustomVariableMutipleInoutBox(); // TODO Auto-generated constructor stub this.customVariableParam = customVariableParam; this.customVariable = customVariable; String defaultNameTemp = customVariableParam.getShowVariableName(); if (defaultNameTemp != null && "".equals(defaultNameTemp.trim()) == false) { if (this.customVariable.isAllowDuplicateNames()) {//允许变量名重复 String defaultName = defaultNameTemp; customVariable.setVariableValue(defaultName); setText(defaultName); } else {//变量名不能重复
package com.lazycoder.uicodegeneration.component.operation.component.extendscompoment.customvariable; /** * 内部的变量输入框 * * @author admin */ public class CustomVariableTextFieldForMuti extends JTextField { /** * */ private static final long serialVersionUID = 7821943593668414212L; private CustomVariableParam customVariableParam; private CustomVariable customVariable; private CustomVariableMutipleInputBox CustomVariableMutipleInputBox = null; public CustomVariableTextFieldForMuti(CustomVariableParam customVariableParam, CustomVariable customVariable) { super(); this.CustomVariableMutipleInputBox = customVariableParam.getCustomVariableMutipleInoutBox(); // TODO Auto-generated constructor stub this.customVariableParam = customVariableParam; this.customVariable = customVariable; String defaultNameTemp = customVariableParam.getShowVariableName(); if (defaultNameTemp != null && "".equals(defaultNameTemp.trim()) == false) { if (this.customVariable.isAllowDuplicateNames()) {//允许变量名重复 String defaultName = defaultNameTemp; customVariable.setVariableValue(defaultName); setText(defaultName); } else {//变量名不能重复
String defaultName = CodeGenerationComponentInterface.getDeafaultVariableName(this.CustomVariableMutipleInputBox, defaultNameTemp);
1
2023-11-16 11:55:06+00:00
16k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/ksx4506/KSDeviceContextBase.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put n...
import kr.or.kashi.hde.PacketSchedule; import kr.or.kashi.hde.HomeDevice; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import android.content.Context; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.base.PropertyTask; import kr.or.kashi.hde.base.PropertyValue; import kr.or.kashi.hde.DeviceContextBase; import kr.or.kashi.hde.DeviceStatePollee; import kr.or.kashi.hde.HomeAddress; import kr.or.kashi.hde.HomePacket; import kr.or.kashi.hde.MainContext;
12,745
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /* * [KS X 4506] The base class of device context. */ public abstract class KSDeviceContextBase extends DeviceContextBase { private static final String TAG = "KSDeviceContextBase"; private static final boolean DBG = true; public static final int CMD_STATUS_REQ = 0x01; public static final int CMD_STATUS_RSP = 0x81; public static final int CMD_CHARACTERISTIC_REQ = 0x0F; public static final int CMD_CHARACTERISTIC_RSP = 0x8F; public static final int CMD_SINGLE_CONTROL_REQ = 0x41; public static final int CMD_SINGLE_CONTROL_RSP = 0xC1; public static final int CMD_GROUP_CONTROL_REQ = 0x42; public static final int CAP_STATUS_SINGLE = (1 << 0); public static final int CAP_STATUS_MULTI = (1 << 1); public static final int CAP_CHARAC_SINGLE = (1 << 2); public static final int CAP_CHARAC_MULTI = (1 << 3); private final MainContext mMainContext; private boolean mCharacteristicRetrieved = false; private PacketSchedule mAutoCharacReqSchedule = null; private PacketSchedule mAutoStatusReqSchedule = null; private int mAutoStatusReqScheduleError = 0; protected PropertyTask mSingleControlTask = new PropertyTask() { @Override
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde.ksx4506; /* * [KS X 4506] The base class of device context. */ public abstract class KSDeviceContextBase extends DeviceContextBase { private static final String TAG = "KSDeviceContextBase"; private static final boolean DBG = true; public static final int CMD_STATUS_REQ = 0x01; public static final int CMD_STATUS_RSP = 0x81; public static final int CMD_CHARACTERISTIC_REQ = 0x0F; public static final int CMD_CHARACTERISTIC_RSP = 0x8F; public static final int CMD_SINGLE_CONTROL_REQ = 0x41; public static final int CMD_SINGLE_CONTROL_RSP = 0xC1; public static final int CMD_GROUP_CONTROL_REQ = 0x42; public static final int CAP_STATUS_SINGLE = (1 << 0); public static final int CAP_STATUS_MULTI = (1 << 1); public static final int CAP_CHARAC_SINGLE = (1 << 2); public static final int CAP_CHARAC_MULTI = (1 << 3); private final MainContext mMainContext; private boolean mCharacteristicRetrieved = false; private PacketSchedule mAutoCharacReqSchedule = null; private PacketSchedule mAutoStatusReqSchedule = null; private int mAutoStatusReqScheduleError = 0; protected PropertyTask mSingleControlTask = new PropertyTask() { @Override
public boolean execTask(PropertyMap reqProps, PropertyMap outProps) {
0
2023-11-10 01:19:44+00:00
16k
xLorey/FluxLoader
src/main/java/io/xlorey/FluxLoader/client/core/StateManager.java
[ { "identifier": "FluxLogoState", "path": "src/main/java/io/xlorey/FluxLoader/client/states/FluxLogoState.java", "snippet": "public class FluxLogoState extends GameState {\n\n /**\n * Current transparency value\n */\n private float alpha = 0.0f;\n\n /**\n * Logo display time\n */...
import io.xlorey.FluxLoader.client.states.FluxLogoState; import io.xlorey.FluxLoader.utils.Logger; import zombie.GameWindow; import zombie.gameStates.GameState; import zombie.gameStates.TISLogoState; import java.util.List;
12,991
package io.xlorey.FluxLoader.client.core; /** * Game state manager */ public class StateManager { /** * Initializing and adding the FluxLoader logo to display when loading the game */ private static void initLogoState() {
package io.xlorey.FluxLoader.client.core; /** * Game state manager */ public class StateManager { /** * Initializing and adding the FluxLoader logo to display when loading the game */ private static void initLogoState() {
List<GameState> states = GameWindow.states.States;
2
2023-11-16 09:05:44+00:00
16k
EmonerRobotics/2023Robot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb por...
import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.IntakeConstants; import frc.robot.commands.AutoElevator; import frc.robot.commands.AutoIntake; import frc.robot.commands.DriveWithJoysticks; import frc.robot.commands.GetInRange; import frc.robot.commands.IntakeCommand; import frc.robot.commands.LiftCommand; import frc.robot.commands.PneumaticCommand; import frc.robot.commands.AutoElevator.ElevatorPosition; import frc.robot.commands.AutoIntake.IntakePosition; import frc.robot.commands.GetInRange.LimelightPositionCheck; import frc.robot.commands.autonomous.AutoBalance; import frc.robot.commands.autonomous.AutoCommand; import frc.robot.commands.autonomous.OnePieceCharge; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.LiftSubsystem; import frc.robot.subsystems.LimelightSubsystem; import frc.robot.subsystems.PneumaticSubsystem; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils; import com.pathplanner.lib.server.PathPlannerServer;
11,963
// 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 { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * 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() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2). whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive)); //with Y or 4 button goes to the top new JoystickButton(joystick2, IntakeConstants.TopLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenD, IntakePosition.STRAIGHT))); //with B or 2 button goes to the human closes intake and goes to down new JoystickButton(joystick2, IntakeConstants.HumanPB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.HUMANPH , ElevatorPosition.HUMANP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenHD, IntakePosition.STRAIGHTHD), new PneumaticCommand(pneumaticSubsystem, true, false), new WaitCommand(1), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH , ElevatorPosition.GROUND))); //with A or 1 button goes to the down new JoystickButton(joystick2, IntakeConstants.GroundLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH, ElevatorPosition.GROUND) )); new JoystickButton(joystick2, 3). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.MIDH, ElevatorPosition.MIDDLE), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeHalfOpenD, IntakePosition.HALF) )); //Pneumatic new JoystickButton(joystick2, IntakeConstants.SolenoidOnB). onTrue(new PneumaticCommand(pneumaticSubsystem, true, false)); //aciyor new JoystickButton(joystick2, IntakeConstants.SolenoidOffB). onTrue(new PneumaticCommand(pneumaticSubsystem, false, true)); //kapatiyor // Pose Estimation new JoystickButton(joystick1, 6) .onTrue(new InstantCommand(driveCommand::resetFieldOrientation)); new JoystickButton(joystick1, 7) .onTrue(new InstantCommand(() -> poseEstimation.resetPose( new Pose2d( poseEstimation.getEstimatedPose().getTranslation(), new Rotation2d())))); // Driving new JoystickButton(joystick1, 1) .whileTrue(new RunCommand( drivetrain::setX, drivetrain)); new JoystickButton(joystick1, 3) .whileTrue(autoBalanceCommand); } public Command getAutonomousCommand() { Pose2d startingPose = startingPosition.getPose(); return new SequentialCommandGroup( new InstantCommand(() -> poseEstimation.resetPose(startingPose)), new OnePieceCharge(),
// 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 { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift public static final LiftSubsystem liftSubsystem = new LiftSubsystem(); public static final ShuffleboardTab driveSettingsTab = Shuffleboard.getTab("Drive Settings"); public static final ShuffleboardTab autoTab = Shuffleboard.getTab("Auto"); public static final ShuffleboardTab swerveTab = Shuffleboard.getTab("Swerve"); public static final Joystick joystick1 = new Joystick(0); public static final Joystick joystick2 = new Joystick(IntakeConstants.AngleController); public static final Drivetrain drivetrain = new Drivetrain(); public static final PoseEstimation poseEstimation = new PoseEstimation(); public static final SendableChooser<String> drivePresetsChooser = new SendableChooser<>(); public static Field2d field = new Field2d(); public static Field2d nodeSelector = new Field2d(); private final FieldObject2d startingPosition = field.getObject("Starting Position"); private final FieldObject2d autoBalanceStartingPosition = field.getObject("Auto Balance Starting Position"); private DriveWithJoysticks driveCommand = new DriveWithJoysticks(drivetrain, poseEstimation, joystick1); private AutoBalance autoBalanceCommand = new AutoBalance(drivetrain); public static SendableChooser<String> autoSelector; //private static AutoElevator autoElevator; /** The container for the robot. Contains subsystems, OI devices, and commands. */ public RobotContainer() { //autoElevator = new AutoElevator(liftSubsystem, 0); //Intake intakeSubsystem.setDefaultCommand(new IntakeCommand(intakeSubsystem, () -> -joystick2.getRawAxis(IntakeConstants.AngleController))); //Pneumatic //pneumaticSubsystem.setDefaultCommand(new PneumaticCommand(pneumaticSubsystem, false, true)); //Lift liftSubsystem.setDefaultCommand(new LiftCommand(liftSubsystem, () -> -joystick2.getRawAxis(5))); if (!DriverStation.isFMSAttached()) { PathPlannerServer.startServer(5811); } drivetrain.setDefaultCommand(driveCommand); if (autoBalanceStartingPosition.getPoses().isEmpty()) { autoBalanceStartingPosition.setPose(AllianceUtils.allianceToField(new Pose2d(new Translation2d(0,0),new Rotation2d()))); } configureBindings(); autoSelector = new SendableChooser<>(); autoSelector.setDefaultOption("grid1", "grid1"); // 1 kup en yukari kisa taxi //autoSelector.setDefaultOption("grid2", "grid2"); // 1 kup en yukari kisa taxi denge //autoSelector.setDefaultOption("grid3", "grid3"); // 1 kup en yukari ortadan denge //autoSelector.setDefaultOption("grid4", "grid4"); //1 kup en yukari uzun taxi denge //autoSelector.setDefaultOption("grid5", "grid5"); //1 kup en yukari uzun taxi } /** * 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() { //setPoint type is inches //limelight sets 111 cm new JoystickButton(joystick1, 2). whileTrue(new GetInRange(drivetrain, poseEstimation, limelightSubsystem, 44, LimelightPositionCheck.fiftyFive)); //with Y or 4 button goes to the top new JoystickButton(joystick2, IntakeConstants.TopLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenD, IntakePosition.STRAIGHT))); //with B or 2 button goes to the human closes intake and goes to down new JoystickButton(joystick2, IntakeConstants.HumanPB). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.HUMANPH , ElevatorPosition.HUMANP), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeStraightOpenHD, IntakePosition.STRAIGHTHD), new PneumaticCommand(pneumaticSubsystem, true, false), new WaitCommand(1), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH , ElevatorPosition.GROUND))); //with A or 1 button goes to the down new JoystickButton(joystick2, IntakeConstants.GroundLevelB). toggleOnTrue(new SequentialCommandGroup( new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED), new AutoElevator(liftSubsystem, Constants.LiftMeasurements.GROUNDH, ElevatorPosition.GROUND) )); new JoystickButton(joystick2, 3). toggleOnTrue(new SequentialCommandGroup( new AutoElevator(liftSubsystem, Constants.LiftMeasurements.MIDH, ElevatorPosition.MIDDLE), new AutoIntake(intakeSubsystem, Constants.IntakeMeasurements.IntakeHalfOpenD, IntakePosition.HALF) )); //Pneumatic new JoystickButton(joystick2, IntakeConstants.SolenoidOnB). onTrue(new PneumaticCommand(pneumaticSubsystem, true, false)); //aciyor new JoystickButton(joystick2, IntakeConstants.SolenoidOffB). onTrue(new PneumaticCommand(pneumaticSubsystem, false, true)); //kapatiyor // Pose Estimation new JoystickButton(joystick1, 6) .onTrue(new InstantCommand(driveCommand::resetFieldOrientation)); new JoystickButton(joystick1, 7) .onTrue(new InstantCommand(() -> poseEstimation.resetPose( new Pose2d( poseEstimation.getEstimatedPose().getTranslation(), new Rotation2d())))); // Driving new JoystickButton(joystick1, 1) .whileTrue(new RunCommand( drivetrain::setX, drivetrain)); new JoystickButton(joystick1, 3) .whileTrue(autoBalanceCommand); } public Command getAutonomousCommand() { Pose2d startingPose = startingPosition.getPose(); return new SequentialCommandGroup( new InstantCommand(() -> poseEstimation.resetPose(startingPose)), new OnePieceCharge(),
AutoCommand.makeAutoCommand(drivetrain, poseEstimation, autoSelector.getSelected()),
12
2023-11-18 14:02:20+00:00
16k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/core/items/types/slayer/zombie/items/AxeOfTheShredded.java
[ { "identifier": "SkyBlock", "path": "src/main/java/com/sweattypalms/skyblock/SkyBlock.java", "snippet": "public final class SkyBlock extends JavaPlugin {\n\n private static SkyBlock instance;\n\n public static SkyBlock getInstance() {\n return instance;\n }\n\n public boolean debug = ...
import com.sweattypalms.skyblock.SkyBlock; import com.sweattypalms.skyblock.core.events.def.SkyblockInteractEvent; import com.sweattypalms.skyblock.core.events.def.SkyblockPlayerDamageEntityEvent; import com.sweattypalms.skyblock.core.helpers.MozangStuff; import com.sweattypalms.skyblock.core.items.builder.Rarity; import com.sweattypalms.skyblock.core.items.builder.SkyblockItem; import com.sweattypalms.skyblock.core.items.builder.SkyblockItemType; import com.sweattypalms.skyblock.core.items.builder.abilities.Ability; import com.sweattypalms.skyblock.core.items.builder.abilities.IHasAbility; import com.sweattypalms.skyblock.core.items.builder.abilities.TriggerType; import com.sweattypalms.skyblock.core.items.builder.abilities.types.DamageAbility; import com.sweattypalms.skyblock.core.items.builder.abilities.types.ICooldown; import com.sweattypalms.skyblock.core.items.builder.abilities.types.ITriggerableAbility; import com.sweattypalms.skyblock.core.items.builder.abilities.types.IUsageCost; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.player.sub.stats.Stats; import com.sweattypalms.skyblock.core.helpers.Tuple; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.entity.ArmorStand; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.inventory.ItemStack; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.EulerAngle; import org.bukkit.util.Vector; import java.util.*;
10,938
package com.sweattypalms.skyblock.core.items.types.slayer.zombie.items; public class AxeOfTheShredded extends SkyblockItem implements IHasAbility { public static final String ID = "axe_of_the_shredded"; private static final Map<Stats, Double> stats = new HashMap<>(Map.of( Stats.DAMAGE, 140d, Stats.STRENGTH, 115d )); public AxeOfTheShredded() { super( ID, "Axe of the Shredded", Material.DIAMOND_AXE, List.of( "$7Heal $c50" + Stats.HEALTH.getSymbol() + "$7per hit.", "$7Deal $a+250% $7damage to Zombies.", "$7Receive $a+25% $7less damage", "$7from Zombies when held." ), stats, Rarity.LEGENDARY, SkyblockItemType.SWORD ); } @Override public List<Ability> getAbilities() { return List.of( new ThrowAbility() ); } public static class ThrowAbility implements ITriggerableAbility, IUsageCost, ICooldown { /** * Format: <stacks>:<last used> * The AOTS combo expires after 2 seconds of not using it * The stacks are used to calculate the damage and mana cost */ private static final HashMap<UUID, String> combo = new HashMap<>(); private static final int OVER_COOLDOWN = 2000; /** * Format: <stacks>:<last used> * * @param toFormat the string to format * @return the formatted string; Tuple<stacks, last used> */ private static Tuple<Integer, Long> fmt(String toFormat) { String[] split = toFormat.split(":"); return new Tuple<>(Integer.parseInt(split[0]), Long.parseLong(split[1])); }
package com.sweattypalms.skyblock.core.items.types.slayer.zombie.items; public class AxeOfTheShredded extends SkyblockItem implements IHasAbility { public static final String ID = "axe_of_the_shredded"; private static final Map<Stats, Double> stats = new HashMap<>(Map.of( Stats.DAMAGE, 140d, Stats.STRENGTH, 115d )); public AxeOfTheShredded() { super( ID, "Axe of the Shredded", Material.DIAMOND_AXE, List.of( "$7Heal $c50" + Stats.HEALTH.getSymbol() + "$7per hit.", "$7Deal $a+250% $7damage to Zombies.", "$7Receive $a+25% $7less damage", "$7from Zombies when held." ), stats, Rarity.LEGENDARY, SkyblockItemType.SWORD ); } @Override public List<Ability> getAbilities() { return List.of( new ThrowAbility() ); } public static class ThrowAbility implements ITriggerableAbility, IUsageCost, ICooldown { /** * Format: <stacks>:<last used> * The AOTS combo expires after 2 seconds of not using it * The stacks are used to calculate the damage and mana cost */ private static final HashMap<UUID, String> combo = new HashMap<>(); private static final int OVER_COOLDOWN = 2000; /** * Format: <stacks>:<last used> * * @param toFormat the string to format * @return the formatted string; Tuple<stacks, last used> */ private static Tuple<Integer, Long> fmt(String toFormat) { String[] split = toFormat.split(":"); return new Tuple<>(Integer.parseInt(split[0]), Long.parseLong(split[1])); }
private static void updateCombo(SkyblockPlayer skyblockPlayer) {
14
2023-11-15 15:05:58+00:00
16k
HanGyeolee/AndroidPdfWriter
android-pdf-writer/src/androidTest/java/com/hangyeolee/androidpdfwriter/PDFTableTest.java
[ { "identifier": "PDFGridLayout", "path": "android-pdf-writer/src/main/java/com/hangyeolee/androidpdfwriter/components/PDFGridLayout.java", "snippet": "public class PDFGridLayout extends PDFLayout{\n int rows, columns;\n\n ArrayList<Integer> span;\n\n final int[] gaps;\n final Rect childMargi...
import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import androidx.test.ext.junit.runners.AndroidJUnit4; import androidx.test.platform.app.InstrumentationRegistry; import com.hangyeolee.androidpdfwriter.components.PDFGridLayout; import com.hangyeolee.androidpdfwriter.components.PDFH1; import com.hangyeolee.androidpdfwriter.components.PDFH3; import com.hangyeolee.androidpdfwriter.components.PDFImage; import com.hangyeolee.androidpdfwriter.components.PDFLinearLayout; import com.hangyeolee.androidpdfwriter.utils.Anchor; import com.hangyeolee.androidpdfwriter.utils.DPI; import com.hangyeolee.androidpdfwriter.utils.Fit; import com.hangyeolee.androidpdfwriter.utils.Orientation; import com.hangyeolee.androidpdfwriter.utils.Paper; import com.hangyeolee.androidpdfwriter.utils.StandardDirectory; import com.hangyeolee.androidpdfwriter.utils.TextAlign; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.InputStream;
11,098
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f) .setFit(Fit.CONTAIN))
package com.hangyeolee.androidpdfwriter; @RunWith(AndroidJUnit4.class) public class PDFTableTest { Context context; PDFBuilder<PDFLinearLayout> builder; /** * The first page of the pdf file that is output by executing the code below is as follows: * com.hangyeolee.androidpdfwriter.test.R.drawable.pdftabletest_resultimage */ @Before public void setUp() { context = InstrumentationRegistry.getInstrumentation().getTargetContext(); InputStream stream = InstrumentationRegistry.getInstrumentation().getContext().getResources().openRawResource(com.hangyeolee.androidpdfwriter.test.R.drawable.test); Bitmap b = BitmapFactory.decodeStream(stream); builder = new PDFBuilder<>(Paper.A4); builder.setPagePadding(30, 30); { builder.root = PDFLinearLayout.build() .setOrientation(Orientation.Column) .setBackgroundColor(Color.BLUE) .addChild(PDFImage.build(b) .setSize(null, 200f) .setFit(Fit.CONTAIN))
.addChild(PDFH1.build("제목")
1
2023-11-15 08:05:28+00:00
16k
Hikaito/Fox-Engine
src/system/gui/project/ProjectEditorFunctions.java
[ { "identifier": "FileOperations", "path": "src/system/backbone/FileOperations.java", "snippet": "public class FileOperations {\n\n // region file editing functions--------------------------------------------\n // fixme add redo and undo as appropriate\n\n //removes extension from file name\n ...
import system.backbone.FileOperations; import system.project.treeElements.ProjectFolderInterface; import system.project.ProjectManager; import system.setting.CoreGlobal; import system.Program; import system.gui.GuiOperations; import system.backbone.ImageOperations; import system.backbone.EventE; import system.gui.WarningWindow; import system.project.treeElements.*; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.LinkedList;
12,840
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); int treeIndex = parent.getIndex(select); parent.remove(select); parent.insert(select, treeIndex+1); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(select); } }); } // if button is diabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } //endregion // make button for deleting objects public static JButton makeRemove(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Delete Element"); //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //invoke action with warning WarningWindow.warningWindow("Are you sure you want to delete this node?", new DeleteEvent(select, tree, caller)); } }); return button; } // action enactor for removing an element from the tree public static class DeleteEvent implements EventE { DefaultMutableTreeNode select; JTree tree; ProjectEditor caller; public DeleteEvent(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ this.select = select; this.tree = tree; this.caller = caller; } @Override public void enact() { ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); DefaultMutableTreeNode treeParent = (DefaultMutableTreeNode) select.getParent(); //get parent kid list LinkedList<ProjectUnitCore> parentKids; ProjectUnitCore parent = core.getParent(); if (parent instanceof ProjectFolderInterface) parentKids = ((ProjectFolderInterface)parent).getChildren(); else return; // copy children to parent if (core instanceof ProjectFolder){ //copy project children------------------------ LinkedList<ProjectUnitCore> children = ((ProjectFolder) core).getChildren(); while(children.size() != 0){ ProjectUnitCore child = children.removeFirst(); child.setParent(core.getParent()); parentKids.addLast(child); //add first element to end of parent } //copy tree children------------------------ while(select.getChildCount() != 0){ DefaultMutableTreeNode kid = (DefaultMutableTreeNode) select.getFirstChild(); //get first child select.remove(0); //remove first child treeParent.add(kid); //add child to parent } } //remove from real tree parentKids.remove(core); //remove from fake tree treeParent.remove(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } } //endregion //region file properties-------------------------------------- // file selection // generate title text field public static JPanel makeFileSelectionField(DefaultMutableTreeNode unit, EventE event){ //create panel JPanel panel = new JPanel(); panel.setBackground(Color.white); //get core if (!(unit.getUserObject() instanceof ProjectFile)) return panel; // exit early if wrong type of file ProjectFile core = (ProjectFile) unit.getUserObject(); // get core // create file panel.add(new JLabel(core.getPath())); // create button JButton button = new JButton("Change"); panel.add(button); // action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // select file
package system.gui.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectEditorFunctions { //region shared properties-------------------------------------- //generate title label public static JLabel makeTitle(ProjectUnitCore unit){ return new JLabel(unit.getTitle()); } // generate title text field public static JTextField makeTitleField(DefaultMutableTreeNode unit, JTree tree){ ProjectUnitCore obj = (ProjectUnitCore) unit.getUserObject(); JTextField title = new JTextField(20); //generate text field with preferred size title.setText(obj.getTitle()); // action title.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // update unit title obj.setTitle(title.getText()); //update tree title tree.updateUI(); } }); return title; } //region movement of layers============================================= // make button for moving objects public static JButton makeMoveIn(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Into Folder"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); ProjectUnitCore sibling = null; // generate parent children LinkedList<ProjectUnitCore> children = null; if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); // get parent else enabled = false; //should be impossible // continue if children if (children != null){ int coreIndex = children.indexOf(core); // if index isn't base, continue if (coreIndex == 0) enabled = false; else{ sibling = children.get(coreIndex - 1); //check if folder if (!(sibling instanceof ProjectFolder)) enabled = false; } } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; ProjectFolder folderSibling = (ProjectFolder) sibling; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move in greater tree finalChildren.remove(core); //remove object folderSibling.getChildren().addLast(core); //add to sibling core.setParent(folderSibling); //set sibling as parent // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); DefaultMutableTreeNode sibling = select.getPreviousSibling(); parent.remove(select); sibling.add(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } }); } // if button is disabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } // make button for moving objects public static JButton makeMoveOut(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Out Of Folder"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); LinkedList<ProjectUnitCore> children = null; LinkedList<ProjectUnitCore> olderChildren = null; //get parent ProjectUnitCore parent = core.getParent(); if (parent instanceof ProjectRoot) enabled = false; //if parent is root, disable moving out else{ //generate children of grandparent if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); //prepare folder else enabled = false; //should be impossible //generate older children if (parent.getParent() instanceof ProjectFolderInterface) olderChildren = ((ProjectFolderInterface) parent.getParent()).getChildren(); //case root else enabled = false; //should be impossible } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; LinkedList<ProjectUnitCore> finalOlderChildren = olderChildren; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move out in greater tree finalChildren.remove(core); finalOlderChildren.addLast(core); core.setParent(parent.getParent()); //set parent // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); DefaultMutableTreeNode grandparent = (DefaultMutableTreeNode) parent.getParent(); parent.remove(select); grandparent.add(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } }); } // if button is diabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } // make button for moving objects public static JButton makeMoveUp(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Up"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); // generate parent children LinkedList<ProjectUnitCore> children = null; if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); else enabled = false; //should be impossible // continue if children if (children != null){ int coreIndex = children.indexOf(core); // if index isn't base, continue if (coreIndex == 0) enabled = false; } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move in greater tree int coreIndex = finalChildren.indexOf(core); //get index finalChildren.remove(core); //remove object finalChildren.add(coreIndex - 1, core); //add as lower index // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); int treeIndex = parent.getIndex(select); parent.remove(select); parent.insert(select, treeIndex-1); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(select); } }); } // if button is diabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } // make button for moving objects public static JButton makeMoveDown(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Move Element Down"); // disable if illegal----------------------- boolean enabled = true; // get core [current layer] ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); // generate parent children LinkedList<ProjectUnitCore> children = null; if (core.getParent() instanceof ProjectFolderInterface) children = ((ProjectFolderInterface) core.getParent()).getChildren(); //case root else enabled = false; //should be impossible // continue if children if (children != null){ int coreIndex = children.indexOf(core); // if index isn't end, continue if (coreIndex == children.size() - 1) enabled = false; } //if button is enabled, add action-------------------- if (enabled){ //effectively final variables LinkedList<ProjectUnitCore> finalChildren = children; //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // move in greater tree int coreIndex = finalChildren.indexOf(core); //get index finalChildren.remove(core); //remove object finalChildren.add(coreIndex + 1, core); //add as lower index // move in gui tree DefaultMutableTreeNode parent = (DefaultMutableTreeNode) select.getParent(); int treeIndex = parent.getIndex(select); parent.remove(select); parent.insert(select, treeIndex+1); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(select); } }); } // if button is diabled, instead make it look disabled else{ button.setBackground(Color.GRAY); } return button; } //endregion // make button for deleting objects public static JButton makeRemove(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ // create button JButton button = new JButton("Delete Element"); //button action: on selection button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //invoke action with warning WarningWindow.warningWindow("Are you sure you want to delete this node?", new DeleteEvent(select, tree, caller)); } }); return button; } // action enactor for removing an element from the tree public static class DeleteEvent implements EventE { DefaultMutableTreeNode select; JTree tree; ProjectEditor caller; public DeleteEvent(DefaultMutableTreeNode select, JTree tree, ProjectEditor caller){ this.select = select; this.tree = tree; this.caller = caller; } @Override public void enact() { ProjectUnitCore core = (ProjectUnitCore) select.getUserObject(); DefaultMutableTreeNode treeParent = (DefaultMutableTreeNode) select.getParent(); //get parent kid list LinkedList<ProjectUnitCore> parentKids; ProjectUnitCore parent = core.getParent(); if (parent instanceof ProjectFolderInterface) parentKids = ((ProjectFolderInterface)parent).getChildren(); else return; // copy children to parent if (core instanceof ProjectFolder){ //copy project children------------------------ LinkedList<ProjectUnitCore> children = ((ProjectFolder) core).getChildren(); while(children.size() != 0){ ProjectUnitCore child = children.removeFirst(); child.setParent(core.getParent()); parentKids.addLast(child); //add first element to end of parent } //copy tree children------------------------ while(select.getChildCount() != 0){ DefaultMutableTreeNode kid = (DefaultMutableTreeNode) select.getFirstChild(); //get first child select.remove(0); //remove first child treeParent.add(kid); //add child to parent } } //remove from real tree parentKids.remove(core); //remove from fake tree treeParent.remove(select); //redraw tree tree.updateUI(); //redraw editor caller.regenerateEditorPane(null); } } //endregion //region file properties-------------------------------------- // file selection // generate title text field public static JPanel makeFileSelectionField(DefaultMutableTreeNode unit, EventE event){ //create panel JPanel panel = new JPanel(); panel.setBackground(Color.white); //get core if (!(unit.getUserObject() instanceof ProjectFile)) return panel; // exit early if wrong type of file ProjectFile core = (ProjectFile) unit.getUserObject(); // get core // create file panel.add(new JLabel(core.getPath())); // create button JButton button = new JButton("Change"); panel.add(button); // action button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // select file
String file = FileOperations.selectFile(Program.getProjectPath()); // select file from project path
4
2023-11-12 21:12:21+00:00
16k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/events/packets/PacketBlockAction.java
[ { "identifier": "GrimAPI", "path": "src/main/java/ac/grim/grimac/GrimAPI.java", "snippet": "@Getter\npublic enum GrimAPI {\n INSTANCE;\n\n private final PlayerDataManager playerDataManager = new PlayerDataManager();\n private final InitManager initManager = new InitManager();\n private final...
import ac.grim.grimac.GrimAPI; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.data.ShulkerData; import ac.grim.grimac.utils.nmsutil.Materials; import io.github.retrooper.packetevents.event.PacketListenerAbstract; import io.github.retrooper.packetevents.event.PacketListenerPriority; import io.github.retrooper.packetevents.event.impl.PacketPlaySendEvent; import io.github.retrooper.packetevents.packettype.PacketType; import io.github.retrooper.packetevents.packetwrappers.play.out.blockaction.WrappedPacketOutBlockAction; import io.github.retrooper.packetevents.utils.vector.Vector3i;
13,608
package ac.grim.grimac.events.packets; // If a player doesn't get this packet, then they don't know the shulker box is currently opened // Meaning if a player enters a chunk with an opened shulker box, they see the shulker box as closed. // // Exempting the player on shulker boxes is an option... but then you have people creating PvP arenas // on shulker boxes to get high lenience. // // Due to the difficulty of cross version shulker box public class PacketBlockAction extends PacketListenerAbstract { public PacketBlockAction() { super(PacketListenerPriority.MONITOR); } @Override public void onPacketPlaySend(PacketPlaySendEvent event) { byte packetID = event.getPacketId(); if (packetID == PacketType.Play.Server.BLOCK_ACTION) { GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getPlayer()); if (player == null) return; WrappedPacketOutBlockAction blockAction = new WrappedPacketOutBlockAction(event.getNMSPacket()); Vector3i blockPos = blockAction.getBlockPosition();
package ac.grim.grimac.events.packets; // If a player doesn't get this packet, then they don't know the shulker box is currently opened // Meaning if a player enters a chunk with an opened shulker box, they see the shulker box as closed. // // Exempting the player on shulker boxes is an option... but then you have people creating PvP arenas // on shulker boxes to get high lenience. // // Due to the difficulty of cross version shulker box public class PacketBlockAction extends PacketListenerAbstract { public PacketBlockAction() { super(PacketListenerPriority.MONITOR); } @Override public void onPacketPlaySend(PacketPlaySendEvent event) { byte packetID = event.getPacketId(); if (packetID == PacketType.Play.Server.BLOCK_ACTION) { GrimPlayer player = GrimAPI.INSTANCE.getPlayerDataManager().getPlayer(event.getPlayer()); if (player == null) return; WrappedPacketOutBlockAction blockAction = new WrappedPacketOutBlockAction(event.getNMSPacket()); Vector3i blockPos = blockAction.getBlockPosition();
if (Materials.checkFlag(blockAction.getBlockType(), Materials.SHULKER)) {
3
2023-11-11 05:14:12+00:00
16k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/app/AppActivity.java
[ { "identifier": "TitleBarAction", "path": "app/src/main/java/com/buaa/food/action/TitleBarAction.java", "snippet": "public interface TitleBarAction extends OnTitleBarListener {\n\n @Nullable\n TitleBar getTitleBar();\n\n /**\n * 左项被点击\n *\n * @param view 被点击的左项View\n */\n ...
import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StringRes; import com.buaa.food.action.TitleBarAction; import com.buaa.food.action.ToastAction; import com.buaa.food.http.model.HttpData; import com.buaa.food.ui.dialog.WaitDialog; import com.gyf.immersionbar.ImmersionBar; import com.hjq.bar.TitleBar; import com.hjq.base.BaseActivity; import com.hjq.base.BaseDialog; import com.buaa.food.R; import com.hjq.http.listener.OnHttpListener; import okhttp3.Call;
13,061
package com.buaa.food.app; public abstract class AppActivity extends BaseActivity implements ToastAction, TitleBarAction, OnHttpListener<Object> { /** 标题栏对象 */ private TitleBar mTitleBar; /** 状态栏沉浸 */ private ImmersionBar mImmersionBar; /** 加载对话框 */
package com.buaa.food.app; public abstract class AppActivity extends BaseActivity implements ToastAction, TitleBarAction, OnHttpListener<Object> { /** 标题栏对象 */ private TitleBar mTitleBar; /** 状态栏沉浸 */ private ImmersionBar mImmersionBar; /** 加载对话框 */
private BaseDialog mDialog;
5
2023-11-14 10:04:26+00:00
16k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/model/block/BlockModelRenderer.java
[ { "identifier": "DragonFly", "path": "src/main/java/useless/dragonfly/DragonFly.java", "snippet": "public class DragonFly implements GameStartEntrypoint {\n public static final String MOD_ID = \"dragonfly\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\tpublic static fi...
import net.minecraft.client.Minecraft; import net.minecraft.client.render.RenderBlockCache; import net.minecraft.client.render.RenderBlocks; import net.minecraft.client.render.Tessellator; import net.minecraft.client.render.block.color.BlockColorDispatcher; import net.minecraft.client.render.block.model.BlockModelRenderBlocks; import net.minecraft.core.block.Block; import net.minecraft.core.util.helper.Side; import net.minecraft.core.world.WorldSource; import org.lwjgl.opengl.GL11; import useless.dragonfly.DragonFly; import useless.dragonfly.mixins.mixin.accessor.RenderBlocksAccessor; import useless.dragonfly.model.block.data.PositionData; import useless.dragonfly.model.block.processed.BlockCube; import useless.dragonfly.model.block.processed.BlockFace; import useless.dragonfly.model.block.processed.BlockModel; import useless.dragonfly.utilities.vector.Vector3f; import java.awt.*; import java.lang.reflect.Field; import static useless.dragonfly.utilities.vector.Vector3f.origin;
10,932
float scale = 8f/3; xScale = (float) displayData.scale[2] * scale; yScale = (float) displayData.scale[1] * scale; zScale = (float) displayData.scale[0] * scale; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) -displayData.rotation[2] + 180; yRot = (float) displayData.rotation[1] + 45; zRot = (float) -displayData.rotation[0] - 100; break; case "gui": default: xScale = (float) displayData.scale[2] * 1.6f; yScale = (float) displayData.scale[1] * 1.6f; zScale = (float) displayData.scale[0] * 1.6f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0] - 30; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; } Tessellator tessellator = Tessellator.instance; GL11.glEnable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glRotatef(yRot, 0, 1, 0); GL11.glRotatef(xRot, 1, 0, 0); GL11.glRotatef(zRot, 0, 0, 1); GL11.glTranslatef(-xOffset, -yOffset, -zOffset); GL11.glScalef(xScale, yScale, zScale); if (modelDragonFly.baseModel.blockCubes != null){ tessellator.startDrawingQuads(); GL11.glColor4f(brightness, brightness, brightness, 1); for (BlockCube cube: modelDragonFly.baseModel.blockCubes) { for (BlockFace face: cube.getFaces().values()) { tessellator.setNormal(face.getSide().getOffsetX(), face.getSide().getOffsetY(), face.getSide().getOffsetZ()); float r = 1; float g = 1; float b = 1; if (face.useTint()){ int color = BlockColorDispatcher.getInstance().getDispatch(block).getFallbackColor(meta); r = (float)(color >> 16 & 0xFF) / 255.0f; g = (float)(color >> 8 & 0xFF) / 255.0f; b = (float)(color & 0xFF) / 255.0f; } renderModelFaceWithColor(face, 0, 0, 0, r * brightness, g * brightness, b * brightness); } } tessellator.draw(); } GL11.glFrontFace(GL11.GL_CCW); // Deleting this breaks rendering for the whole world GL11.glDisable(GL11.GL_CULL_FACE); // Deleting this causes render issues on vanilla transparent blocks GL11.glTranslatef(xOffset, yOffset, zOffset); } public static boolean renderModelNormal(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { BlockModelRenderer.rotationX = rotationX; BlockModelRenderer.rotationY = rotationY; if (rotationX % 90 != 0 || rotationY % 90 != 0) throw new IllegalArgumentException("Rotation must be a multiple of 90!!"); boolean didRender; if (mc.isAmbientOcclusionEnabled() && model.getAO()) { didRender = renderStandardModelWithAmbientOcclusion(model, block, x, y, z); } else { didRender = renderStandardModelWithColorMultiplier(model, block, x, y, z, 1, 1, 1); } BlockModelRenderer.rotationX = 0; BlockModelRenderer.rotationY = 0; return didRender; } public static boolean renderModelNoCulling(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { renderAllFaces = true; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); renderAllFaces = false; return result; } public static boolean renderModelBlockUsingTexture(BlockModel model, Block block, int x, int y, int z, int textureIndex, int rotationX, int rotationY) { overrideBlockTexture = textureIndex; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); overrideBlockTexture = -1; return result; } public static boolean renderStandardModelWithAmbientOcclusion(BlockModel model, Block block, int x, int y, int z) { enableAO = true; rba().getCache().setupCache(block, rba().getBlockAccess(), x, y, z); boolean somethingRendered = false; for (BlockCube cube: model.blockCubes) { for (Side side: DragonFly.sides) { somethingRendered |= renderModelSide(model, cube, block, x, y, z, side); } } enableAO = false; return somethingRendered; } public static boolean renderModelSide(BlockModel model, BlockCube cube, Block block, int x, int y, int z, Side side) { BlockFace blockFace = cube.getFaceFromSide(side, rotationX, rotationY); if (blockFace == null) return false; if (!renderAllFaces){ if (!renderSide(model, cube, side, x, y, z)) return false; } RenderBlockCache cache = rba().getCache(); int sideOffX = side.getOffsetX(); int sideOffY = side.getOffsetY(); int sideOffZ = side.getOffsetZ();
package useless.dragonfly.model.block; public class BlockModelRenderer { public static Minecraft mc = Minecraft.getMinecraft(Minecraft.class); private static boolean enableAO = false; private static boolean renderAllFaces = false; private static float colorRedTopRight; private static float colorRedBottomRight; private static float colorRedBottomLeft; private static float colorGreenTopRight; private static float colorRedTopLeft; private static float colorGreenBottomRight; private static float colorGreenBottomLeft; private static float colorGreenTopLeft; private static float colorBlueTopRight; private static float colorBlueBottomRight; private static float colorBlueBottomLeft; private static float colorBlueTopLeft; private static int overrideBlockTexture = -1; private static int rotationX = 0; private static int rotationY = 0; public static void renderModelInventory(BlockModelDragonFly modelDragonFly, Block block, int meta, float brightness){ int off = (int) ((System.currentTimeMillis()/20) % 360); float xOffset; float yOffset; float zOffset; float xScale; float yScale; float zScale; float xRot; float yRot; float zRot; PositionData displayData = modelDragonFly.baseModel.getDisplayPosition(DragonFly.renderState); switch (DragonFly.renderState) { case "ground": xScale = (float) displayData.scale[2] * 4; yScale = (float) displayData.scale[1] * 4; zScale = (float) displayData.scale[0] * 4; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1]; zRot = (float) displayData.rotation[2]; break; case "head": GL11.glFrontFace(GL11.GL_CW); xScale = (float) displayData.scale[0]; yScale = (float) displayData.scale[1]; zScale = (float) displayData.scale[2]; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[0] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[2] / 16f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1] + 180; zRot = (float) displayData.rotation[2]; break; case "firstperson_righthand": xScale = (float) displayData.scale[2] * 2.5f; yScale = (float) displayData.scale[1] * 2.5f; zScale = (float) displayData.scale[0] * 2.5f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 8f; yOffset -= (float) displayData.translation[1] / 8f; zOffset -= (float) displayData.translation[0] / 8f; xRot = (float) displayData.rotation[0]; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; break; case "thirdperson_righthand": GL11.glFrontFace(GL11.GL_CW); float scale = 8f/3; xScale = (float) displayData.scale[2] * scale; yScale = (float) displayData.scale[1] * scale; zScale = (float) displayData.scale[0] * scale; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) -displayData.rotation[2] + 180; yRot = (float) displayData.rotation[1] + 45; zRot = (float) -displayData.rotation[0] - 100; break; case "gui": default: xScale = (float) displayData.scale[2] * 1.6f; yScale = (float) displayData.scale[1] * 1.6f; zScale = (float) displayData.scale[0] * 1.6f; xOffset = 0.5f * xScale; yOffset = 0.5f * yScale; zOffset = 0.5f * zScale; xOffset -= (float) displayData.translation[2] / 16f; yOffset -= (float) displayData.translation[1] / 16f; zOffset -= (float) displayData.translation[0] / 16f; xRot = (float) displayData.rotation[0] - 30; yRot = (float) displayData.rotation[1] + 45; zRot = (float) displayData.rotation[2]; } Tessellator tessellator = Tessellator.instance; GL11.glEnable(GL11.GL_CULL_FACE); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glRotatef(yRot, 0, 1, 0); GL11.glRotatef(xRot, 1, 0, 0); GL11.glRotatef(zRot, 0, 0, 1); GL11.glTranslatef(-xOffset, -yOffset, -zOffset); GL11.glScalef(xScale, yScale, zScale); if (modelDragonFly.baseModel.blockCubes != null){ tessellator.startDrawingQuads(); GL11.glColor4f(brightness, brightness, brightness, 1); for (BlockCube cube: modelDragonFly.baseModel.blockCubes) { for (BlockFace face: cube.getFaces().values()) { tessellator.setNormal(face.getSide().getOffsetX(), face.getSide().getOffsetY(), face.getSide().getOffsetZ()); float r = 1; float g = 1; float b = 1; if (face.useTint()){ int color = BlockColorDispatcher.getInstance().getDispatch(block).getFallbackColor(meta); r = (float)(color >> 16 & 0xFF) / 255.0f; g = (float)(color >> 8 & 0xFF) / 255.0f; b = (float)(color & 0xFF) / 255.0f; } renderModelFaceWithColor(face, 0, 0, 0, r * brightness, g * brightness, b * brightness); } } tessellator.draw(); } GL11.glFrontFace(GL11.GL_CCW); // Deleting this breaks rendering for the whole world GL11.glDisable(GL11.GL_CULL_FACE); // Deleting this causes render issues on vanilla transparent blocks GL11.glTranslatef(xOffset, yOffset, zOffset); } public static boolean renderModelNormal(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { BlockModelRenderer.rotationX = rotationX; BlockModelRenderer.rotationY = rotationY; if (rotationX % 90 != 0 || rotationY % 90 != 0) throw new IllegalArgumentException("Rotation must be a multiple of 90!!"); boolean didRender; if (mc.isAmbientOcclusionEnabled() && model.getAO()) { didRender = renderStandardModelWithAmbientOcclusion(model, block, x, y, z); } else { didRender = renderStandardModelWithColorMultiplier(model, block, x, y, z, 1, 1, 1); } BlockModelRenderer.rotationX = 0; BlockModelRenderer.rotationY = 0; return didRender; } public static boolean renderModelNoCulling(BlockModel model, Block block, int x, int y, int z, int rotationX, int rotationY) { renderAllFaces = true; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); renderAllFaces = false; return result; } public static boolean renderModelBlockUsingTexture(BlockModel model, Block block, int x, int y, int z, int textureIndex, int rotationX, int rotationY) { overrideBlockTexture = textureIndex; boolean result = renderModelNormal(model, block, x, y, z, rotationX, rotationY); overrideBlockTexture = -1; return result; } public static boolean renderStandardModelWithAmbientOcclusion(BlockModel model, Block block, int x, int y, int z) { enableAO = true; rba().getCache().setupCache(block, rba().getBlockAccess(), x, y, z); boolean somethingRendered = false; for (BlockCube cube: model.blockCubes) { for (Side side: DragonFly.sides) { somethingRendered |= renderModelSide(model, cube, block, x, y, z, side); } } enableAO = false; return somethingRendered; } public static boolean renderModelSide(BlockModel model, BlockCube cube, Block block, int x, int y, int z, Side side) { BlockFace blockFace = cube.getFaceFromSide(side, rotationX, rotationY); if (blockFace == null) return false; if (!renderAllFaces){ if (!renderSide(model, cube, side, x, y, z)) return false; } RenderBlockCache cache = rba().getCache(); int sideOffX = side.getOffsetX(); int sideOffY = side.getOffsetY(); int sideOffZ = side.getOffsetZ();
Vector3f vMin = cube.getMin().rotateAroundX(origin, rotationX).rotateAroundY(origin, rotationY);
7
2023-11-16 01:10:52+00:00
16k
AntonyCheng/ai-bi
src/main/java/top/sharehome/springbootinittemplate/config/captcha/service/impl/CaptchaServiceImpl.java
[ { "identifier": "CaptchaCondition", "path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/condition/CaptchaCondition.java", "snippet": "public class CaptchaCondition implements Condition {\n\n @Override\n public boolean matches(ConditionContext context, AnnotatedTypeMetadata m...
import cn.hutool.captcha.AbstractCaptcha; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.core.util.ReflectUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Conditional; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.stereotype.Service; import top.sharehome.springbootinittemplate.config.captcha.condition.CaptchaCondition; import top.sharehome.springbootinittemplate.config.captcha.model.CaptchaCreate; import top.sharehome.springbootinittemplate.config.captcha.properties.CaptchaProperties; import top.sharehome.springbootinittemplate.config.captcha.properties.enums.CaptchaType; import top.sharehome.springbootinittemplate.config.captcha.service.CaptchaService; import top.sharehome.springbootinittemplate.common.base.ReturnCode; import top.sharehome.springbootinittemplate.config.bean.SpringContextHolder; import top.sharehome.springbootinittemplate.exception.customize.CustomizeReturnException; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants; import javax.annotation.Resource; import java.util.UUID;
13,870
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override
package top.sharehome.springbootinittemplate.config.captcha.service.impl; /** * 验证码服务实现类 * * @author AntonyCheng */ @EnableConfigurationProperties(CaptchaProperties.class) @Service @Conditional(CaptchaCondition.class) public class CaptchaServiceImpl implements CaptchaService { @Resource private CaptchaProperties captchaProperties; @Override
public CaptchaCreate createCaptcha() {
1
2023-11-12 07:49:59+00:00
16k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/controller/HrmSalaryArchivesController.java
[ { "identifier": "OperationLog", "path": "common/common-log/src/main/java/com/kakarote/common/log/entity/OperationLog.java", "snippet": "@Getter\n@Setter\npublic class OperationLog {\n //操作对象\n private Object operationObject;\n //操作详情\n private String operationInfo;\n\n private BehaviorEnu...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.ListUtil; import com.kakarote.common.log.annotation.OperateLog; import com.kakarote.common.log.entity.OperationLog; import com.kakarote.common.log.entity.OperationResult; import com.kakarote.common.log.enums.ApplyEnum; import com.kakarote.common.log.enums.BehaviorEnum; import com.kakarote.common.log.enums.OperateObjectEnum; import com.kakarote.core.common.Result; import com.kakarote.core.common.enums.SystemCodeEnum; import com.kakarote.core.entity.BasePage; import com.kakarote.core.exception.CrmException; import com.kakarote.hrm.entity.BO.*; import com.kakarote.hrm.entity.DTO.ExcelTemplateOption; import com.kakarote.hrm.entity.PO.HrmSalaryArchivesOption; import com.kakarote.hrm.entity.VO.*; import com.kakarote.hrm.service.IHrmSalaryArchivesOptionService; import com.kakarote.hrm.service.IHrmSalaryArchivesService; import com.kakarote.hrm.utils.SalaryExcelUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors;
13,461
@PostMapping("/cancelChangeSalary/{id}") @ApiOperation("取消调薪") public Result cancelChangeSalary(@PathVariable("id") Long id) { salaryArchivesService.cancelChangeSalary(id); return Result.ok(); } @PostMapping("/deleteChangeSalary/{id}") @ApiOperation("删除调薪") public Result deleteChangeSalary(@PathVariable("id") Long id) { salaryArchivesService.deleteChangeSalary(id); return Result.ok(); } @PostMapping("/queryBatchChangeOption") @ApiOperation("查询批量调薪项") public Result<List<ChangeSalaryOptionVO>> queryBatchChangeOption() { List<ChangeSalaryOptionVO> list = salaryArchivesService.queryBatchChangeOption(); return Result.ok(list); } @PostMapping("/batchChangeSalaryRecord") @ApiOperation("批量调薪") @OperateLog(apply = ApplyEnum.HRM, object = OperateObjectEnum.HRM_SALARY_ARCHIVES, behavior = BehaviorEnum.CHANGE_SALARY) public OperationResult<Map<String, Object>> batchChangeSalaryRecord(@RequestBody BatchChangeSalaryRecordBO batchChangeSalaryRecordBO) { Map<String, Object> result = salaryArchivesService.batchChangeSalaryRecord(batchChangeSalaryRecordBO); List<OperationLog> operationLog = (List<OperationLog>) result.get("operationLog"); result.remove("operationLog"); return OperationResult.ok(result, operationLog); } @PostMapping("/downLoadFixTemplate") @ApiOperation("下载定薪模板") public void downLoadFixTemplate(@RequestBody QuerySalaryArchivesListBO querySalaryArchivesListBO, HttpServletResponse response) throws IOException { List<ExcelTemplateOption> templateOptionList = salaryArchivesService.queryFixSalaryExcelExportOption(); querySalaryArchivesListBO.setPageType(0); querySalaryArchivesListBO.setStatus(11); List<QuerySalaryArchivesListVO> employeeList = salaryArchivesService.querySalaryArchivesList(querySalaryArchivesListBO).getList(); try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("fixTemplate.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(inputStream); ServletOutputStream out = response.getOutputStream()) { int colNum = 7; int rowNum = 7; XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row5 = sheet.getRow(5); XSSFRow row6 = sheet.getRow(6); for (ExcelTemplateOption categoryOption : templateOptionList) { List<ExcelTemplateOption> optionList = categoryOption.getOptionList(); if (CollUtil.isEmpty(optionList)) { continue; } if (optionList.size() > 1) { sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row5.getRowNum(), colNum, colNum + optionList.size() - 1)); } SalaryExcelUtil.createHeadCell(wb, row5, colNum, categoryOption.getName()); for (int i = 0; i < optionList.size(); i++) { ExcelTemplateOption option = optionList.get(i); SalaryExcelUtil.createHeadCell(wb, row6, colNum + i, option.getName()); } colNum += optionList.size(); } sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row6.getRowNum(), colNum, colNum)); SalaryExcelUtil.createHeadCell(wb, row5, colNum, "备注"); for (int i = 0; i < employeeList.size(); i++) { QuerySalaryArchivesListVO employeeArchives = employeeList.get(i); XSSFRow row = sheet.createRow(rowNum + i); SalaryExcelUtil.createBodyCell(wb, row, 0, employeeArchives.getEmployeeName()); SalaryExcelUtil.createBodyCell(wb, row, 1, employeeArchives.getJobNumber()); SalaryExcelUtil.createBodyCell(wb, row, 2, employeeArchives.getDeptName()); SalaryExcelUtil.createBodyCell(wb, row, 3, employeeArchives.getPost()); } response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=fixSalaryTemplate.xlsx"); wb.write(out); } } @PostMapping("/exportFixSalaryRecord") @ApiOperation("导入定薪") public Result<Long> exportFixSalaryRecord(@RequestParam("file") MultipartFile multipartFile) { Long messageId = salaryArchivesService.exportFixSalaryRecord(multipartFile); return Result.ok(messageId); } @PostMapping("/downLoadChangeTemplate") @ApiOperation("下载调薪模板") public void downLoadChangeTemplate(@RequestBody QuerySalaryArchivesListBO querySalaryArchivesListBO, HttpServletResponse response) { List<ExcelTemplateOption> templateOptionList = salaryArchivesService.queryChangeSalaryExcelExportOption(); querySalaryArchivesListBO.setPageType(0); querySalaryArchivesListBO.setStatus(11); List<QuerySalaryArchivesListVO> employeeList = salaryArchivesService.querySalaryArchivesList(querySalaryArchivesListBO).getList(); try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("changeTemplate.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(inputStream); ServletOutputStream out = response.getOutputStream()) { int colNum = 12; int rowNum = 7; XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row5 = sheet.getRow(5); XSSFRow row6 = sheet.getRow(6); Map<Integer, Integer> codeIndexMap = new HashMap<>(); for (ExcelTemplateOption categoryOption : templateOptionList) { sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row5.getRowNum(), colNum, colNum + 1)); SalaryExcelUtil.createHeadCell(wb, row5, colNum, categoryOption.getName()); SalaryExcelUtil.createHeadCell(wb, row6, colNum, "调整前"); SalaryExcelUtil.createHeadCell(wb, row6, colNum + 1, "调整后"); codeIndexMap.put(categoryOption.getCode(), colNum); colNum += 2; } sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row6.getRowNum(), colNum, colNum)); SalaryExcelUtil.createHeadCell(wb, row5, colNum, "备注"); for (int i = 0; i < employeeList.size(); i++) { QuerySalaryArchivesListVO employeeArchives = employeeList.get(i); XSSFRow row = sheet.createRow(rowNum + i); SalaryExcelUtil.createBodyCell(wb, row, 0, employeeArchives.getEmployeeName()); SalaryExcelUtil.createBodyCell(wb, row, 1, employeeArchives.getJobNumber()); SalaryExcelUtil.createBodyCell(wb, row, 2, employeeArchives.getDeptName()); SalaryExcelUtil.createBodyCell(wb, row, 3, employeeArchives.getPost());
package com.kakarote.hrm.controller; /** * <p> * 薪资档案表 前端控制器 * </p> * * @author hmb * @since 2020-11-05 */ @RestController @RequestMapping("/hrmSalaryArchives") @Api(tags = "薪资档案") public class HrmSalaryArchivesController { @Autowired private IHrmSalaryArchivesService salaryArchivesService; @Autowired private IHrmSalaryArchivesOptionService archivesOptionService; @PostMapping("/querySalaryArchivesList") @ApiOperation("查询薪资档案列表") public Result<BasePage<QuerySalaryArchivesListVO>> querySalaryArchivesList(@RequestBody QuerySalaryArchivesListBO querySalaryArchivesListBO) { BasePage<QuerySalaryArchivesListVO> page = salaryArchivesService.querySalaryArchivesList(querySalaryArchivesListBO); return Result.ok(page); } @PostMapping("/querySalaryArchivesById/{employeeId}") @ApiOperation("查询薪资档案信息") public Result<QuerySalaryArchivesByIdVO> querySalaryArchivesById(@PathVariable("employeeId") Long employeeId) { QuerySalaryArchivesByIdVO querySalaryArchivesByIdVO = salaryArchivesService.querySalaryArchivesById(employeeId); return Result.ok(querySalaryArchivesByIdVO); } @PostMapping("/queryChangeRecordList/{employeeId}") @ApiOperation("查询调薪记录列表") public Result<List<QueryChangeRecordListVO>> queryChangeRecordList(@PathVariable("employeeId") Long employeeId) { List<QueryChangeRecordListVO> list = salaryArchivesService.queryChangeRecordList(employeeId); return Result.ok(list); } @PostMapping("/setFixSalaryRecord") @ApiOperation("单个定薪") @OperateLog(apply = ApplyEnum.HRM, object = OperateObjectEnum.HRM_SALARY_ARCHIVES, behavior = BehaviorEnum.FIX_SALARY) public Result setFixSalaryRecord(@RequestBody SetFixSalaryRecordBO setFixSalaryRecordBO) { OperationLog operationLog = salaryArchivesService.setFixSalaryRecord(setFixSalaryRecordBO); return OperationResult.ok(operationLog); } @PostMapping("/queryFixSalaryRecordById/{id}") @ApiOperation("查询定薪记录详情") public Result<FixSalaryRecordDetailVO> queryFixSalaryRecordById(@PathVariable("id") Long id) { FixSalaryRecordDetailVO data = salaryArchivesService.queryFixSalaryRecordById(id); return Result.ok(data); } @PostMapping("/queryChangeOptionByTemplateId") @ApiOperation("查询调薪项的值(单个调薪使用)") public Result<QueryChangeOptionValueVO> queryChangeOptionValue(@RequestBody QueryChangeOptionValueBO changeOptionValueBO) { QueryChangeOptionValueVO data = salaryArchivesService.queryChangeOptionValue(changeOptionValueBO); return Result.ok(data); } @PostMapping("/setChangeSalaryRecord") @ApiOperation("单个调薪") @OperateLog(apply = ApplyEnum.HRM, object = OperateObjectEnum.HRM_SALARY_ARCHIVES, behavior = BehaviorEnum.CHANGE_SALARY) public Result setChangeSalaryRecord(@RequestBody SetChangeSalaryRecordBO setChangeSalaryRecordBO) { OperationLog operationLog = salaryArchivesService.setChangeSalaryRecord(setChangeSalaryRecordBO); return OperationResult.ok(ListUtil.toList(operationLog)); } @PostMapping("/queryChangeSalaryRecordById/{id}") @ApiOperation("查询调薪记录详情") public Result<ChangeSalaryRecordDetailVO> queryChangeSalaryRecordById(@PathVariable("id") Long id) { ChangeSalaryRecordDetailVO data = salaryArchivesService.queryChangeSalaryRecordById(id); return Result.ok(data); } @PostMapping("/cancelChangeSalary/{id}") @ApiOperation("取消调薪") public Result cancelChangeSalary(@PathVariable("id") Long id) { salaryArchivesService.cancelChangeSalary(id); return Result.ok(); } @PostMapping("/deleteChangeSalary/{id}") @ApiOperation("删除调薪") public Result deleteChangeSalary(@PathVariable("id") Long id) { salaryArchivesService.deleteChangeSalary(id); return Result.ok(); } @PostMapping("/queryBatchChangeOption") @ApiOperation("查询批量调薪项") public Result<List<ChangeSalaryOptionVO>> queryBatchChangeOption() { List<ChangeSalaryOptionVO> list = salaryArchivesService.queryBatchChangeOption(); return Result.ok(list); } @PostMapping("/batchChangeSalaryRecord") @ApiOperation("批量调薪") @OperateLog(apply = ApplyEnum.HRM, object = OperateObjectEnum.HRM_SALARY_ARCHIVES, behavior = BehaviorEnum.CHANGE_SALARY) public OperationResult<Map<String, Object>> batchChangeSalaryRecord(@RequestBody BatchChangeSalaryRecordBO batchChangeSalaryRecordBO) { Map<String, Object> result = salaryArchivesService.batchChangeSalaryRecord(batchChangeSalaryRecordBO); List<OperationLog> operationLog = (List<OperationLog>) result.get("operationLog"); result.remove("operationLog"); return OperationResult.ok(result, operationLog); } @PostMapping("/downLoadFixTemplate") @ApiOperation("下载定薪模板") public void downLoadFixTemplate(@RequestBody QuerySalaryArchivesListBO querySalaryArchivesListBO, HttpServletResponse response) throws IOException { List<ExcelTemplateOption> templateOptionList = salaryArchivesService.queryFixSalaryExcelExportOption(); querySalaryArchivesListBO.setPageType(0); querySalaryArchivesListBO.setStatus(11); List<QuerySalaryArchivesListVO> employeeList = salaryArchivesService.querySalaryArchivesList(querySalaryArchivesListBO).getList(); try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("fixTemplate.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(inputStream); ServletOutputStream out = response.getOutputStream()) { int colNum = 7; int rowNum = 7; XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row5 = sheet.getRow(5); XSSFRow row6 = sheet.getRow(6); for (ExcelTemplateOption categoryOption : templateOptionList) { List<ExcelTemplateOption> optionList = categoryOption.getOptionList(); if (CollUtil.isEmpty(optionList)) { continue; } if (optionList.size() > 1) { sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row5.getRowNum(), colNum, colNum + optionList.size() - 1)); } SalaryExcelUtil.createHeadCell(wb, row5, colNum, categoryOption.getName()); for (int i = 0; i < optionList.size(); i++) { ExcelTemplateOption option = optionList.get(i); SalaryExcelUtil.createHeadCell(wb, row6, colNum + i, option.getName()); } colNum += optionList.size(); } sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row6.getRowNum(), colNum, colNum)); SalaryExcelUtil.createHeadCell(wb, row5, colNum, "备注"); for (int i = 0; i < employeeList.size(); i++) { QuerySalaryArchivesListVO employeeArchives = employeeList.get(i); XSSFRow row = sheet.createRow(rowNum + i); SalaryExcelUtil.createBodyCell(wb, row, 0, employeeArchives.getEmployeeName()); SalaryExcelUtil.createBodyCell(wb, row, 1, employeeArchives.getJobNumber()); SalaryExcelUtil.createBodyCell(wb, row, 2, employeeArchives.getDeptName()); SalaryExcelUtil.createBodyCell(wb, row, 3, employeeArchives.getPost()); } response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=fixSalaryTemplate.xlsx"); wb.write(out); } } @PostMapping("/exportFixSalaryRecord") @ApiOperation("导入定薪") public Result<Long> exportFixSalaryRecord(@RequestParam("file") MultipartFile multipartFile) { Long messageId = salaryArchivesService.exportFixSalaryRecord(multipartFile); return Result.ok(messageId); } @PostMapping("/downLoadChangeTemplate") @ApiOperation("下载调薪模板") public void downLoadChangeTemplate(@RequestBody QuerySalaryArchivesListBO querySalaryArchivesListBO, HttpServletResponse response) { List<ExcelTemplateOption> templateOptionList = salaryArchivesService.queryChangeSalaryExcelExportOption(); querySalaryArchivesListBO.setPageType(0); querySalaryArchivesListBO.setStatus(11); List<QuerySalaryArchivesListVO> employeeList = salaryArchivesService.querySalaryArchivesList(querySalaryArchivesListBO).getList(); try (InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("changeTemplate.xlsx"); XSSFWorkbook wb = new XSSFWorkbook(inputStream); ServletOutputStream out = response.getOutputStream()) { int colNum = 12; int rowNum = 7; XSSFSheet sheet = wb.getSheetAt(0); XSSFRow row5 = sheet.getRow(5); XSSFRow row6 = sheet.getRow(6); Map<Integer, Integer> codeIndexMap = new HashMap<>(); for (ExcelTemplateOption categoryOption : templateOptionList) { sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row5.getRowNum(), colNum, colNum + 1)); SalaryExcelUtil.createHeadCell(wb, row5, colNum, categoryOption.getName()); SalaryExcelUtil.createHeadCell(wb, row6, colNum, "调整前"); SalaryExcelUtil.createHeadCell(wb, row6, colNum + 1, "调整后"); codeIndexMap.put(categoryOption.getCode(), colNum); colNum += 2; } sheet.addMergedRegion(new CellRangeAddress(row5.getRowNum(), row6.getRowNum(), colNum, colNum)); SalaryExcelUtil.createHeadCell(wb, row5, colNum, "备注"); for (int i = 0; i < employeeList.size(); i++) { QuerySalaryArchivesListVO employeeArchives = employeeList.get(i); XSSFRow row = sheet.createRow(rowNum + i); SalaryExcelUtil.createBodyCell(wb, row, 0, employeeArchives.getEmployeeName()); SalaryExcelUtil.createBodyCell(wb, row, 1, employeeArchives.getJobNumber()); SalaryExcelUtil.createBodyCell(wb, row, 2, employeeArchives.getDeptName()); SalaryExcelUtil.createBodyCell(wb, row, 3, employeeArchives.getPost());
Map<Integer, Map<Integer, String>> collect = archivesOptionService.lambdaQuery().eq(HrmSalaryArchivesOption::getEmployeeId, employeeArchives.getEmployeeId()).list()
10
2023-10-17 05:49:52+00:00
16k
djkcyl/Shamrock
qqinterface/src/main/java/com/tencent/mobileqq/profilecard/processor/IRequestProfileCardCallback.java
[ { "identifier": "Card", "path": "qqinterface/src/main/java/com/tencent/mobileqq/data/Card.java", "snippet": "public class Card {\n public static final long BIRTHDAY_INVALID = 0;\n public static final int CONSTELLATION_INVALID = 0;\n public static final short FEMALE = 1;\n public static final...
import android.os.Bundle; import android.util.SparseArray; import com.tencent.mobileqq.data.Card; import com.tencent.mobileqq.profilecard.entity.BusinessReqBuffer; import com.tencent.mobileqq.profilecard.entity.BusinessRespBuffer; import java.util.ArrayList; import SummaryCard.RespHead; import SummaryCard.RespSummaryCard; import tencent.im.oidb.cmd0x5eb.oidb_0x5eb;
11,466
package com.tencent.mobileqq.profilecard.processor; public interface IRequestProfileCardCallback { void onProcessProfile0x5eb(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, oidb_0x5eb.UdcUinData oidb_0x5eb_udcuindata); void onProcessProfileCard(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard); void onProcessProfileService(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, SparseArray<BusinessRespBuffer> sparseArray);
package com.tencent.mobileqq.profilecard.processor; public interface IRequestProfileCardCallback { void onProcessProfile0x5eb(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, oidb_0x5eb.UdcUinData oidb_0x5eb_udcuindata); void onProcessProfileCard(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard); void onProcessProfileService(Bundle bundle, Card card, RespHead respHead, RespSummaryCard respSummaryCard, SparseArray<BusinessRespBuffer> sparseArray);
void onRequestProfileCard(Bundle bundle, ArrayList<BusinessReqBuffer> arrayList, ArrayList<Integer> arrayList2);
1
2023-10-20 10:43:47+00:00
16k
trpc-group/trpc-java
trpc-demo/trpc-java-demo/src/main/java/com/tencent/trpc/demo/example/config/ClientTest.java
[ { "identifier": "ConfigManager", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/ConfigManager.java", "snippet": "public class ConfigManager {\n\n private static final Logger logger = LoggerFactory.getLogger(ServerConfig.class);\n private static ConfigManager instance = new ConfigMan...
import com.tencent.trpc.core.common.ConfigManager; import com.tencent.trpc.core.common.config.BackendConfig; import com.tencent.trpc.core.common.config.ConsumerConfig; import com.tencent.trpc.core.rpc.RpcClientContext; import com.tencent.trpc.demo.proto.GreeterServiceAPI; import com.tencent.trpc.demo.proto.HelloRequestProtocol; import java.util.concurrent.TimeUnit;
10,843
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.demo.example.config; public class ClientTest { public static void main(String[] args) throws Exception { try { // start global config manager ConfigManager.getInstance().start(); int times = 5; System.out.println("=================tcp test==================="); testTrpc(times); System.out.println("=================tcp test done==================="); System.out.println("=================http test==================="); testHttp(times); System.out.println("=================http test done==================="); } finally { // stop global config manager ConfigManager.getInstance().stop(); } } private static void testTrpc(int times) throws Exception { // setup remote service interface
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.demo.example.config; public class ClientTest { public static void main(String[] args) throws Exception { try { // start global config manager ConfigManager.getInstance().start(); int times = 5; System.out.println("=================tcp test==================="); testTrpc(times); System.out.println("=================tcp test done==================="); System.out.println("=================http test==================="); testHttp(times); System.out.println("=================http test done==================="); } finally { // stop global config manager ConfigManager.getInstance().stop(); } } private static void testTrpc(int times) throws Exception { // setup remote service interface
ConsumerConfig<GreeterServiceAPI> consumerConfig = new ConsumerConfig<>();
2
2023-10-19 10:54:11+00:00
16k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/entity/Snake.java
[ { "identifier": "ClimbingAnimal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ClimbingAnimal.java", "snippet": "public abstract class ClimbingAnimal extends Animal {\n private static final EntityDataAccessor<Byte> CLIMB_FLAG = SynchedEntityData.defineId(ClimbingAn...
import com.starfish_studios.naturalist.common.entity.core.ClimbingAnimal; import com.starfish_studios.naturalist.common.entity.core.SleepingAnimal; import com.starfish_studios.naturalist.common.entity.core.ai.goal.SearchForItemsGoal; import com.starfish_studios.naturalist.common.entity.core.ai.goal.SleepGoal; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import com.starfish_studios.naturalist.core.registry.NaturalistSoundEvents; import com.starfish_studios.naturalist.core.registry.NaturalistTags; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.tags.BlockTags; import net.minecraft.util.RandomSource; import net.minecraft.util.TimeUtil; import net.minecraft.util.valueproviders.UniformInt; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.effect.MobEffectInstance; import net.minecraft.world.effect.MobEffects; import net.minecraft.world.entity.*; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.*; import net.minecraft.world.entity.ai.goal.target.HurtByTargetGoal; import net.minecraft.world.entity.ai.goal.target.NearestAttackableTargetGoal; import net.minecraft.world.entity.ai.goal.target.ResetUniversalAngerTargetGoal; import net.minecraft.world.entity.ai.targeting.TargetingConditions; import net.minecraft.world.entity.animal.Animal; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.world.entity.monster.Slime; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.crafting.Ingredient; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.gameevent.GameEvent; import net.minecraft.world.level.pathfinder.Path; import software.bernie.geckolib3.core.AnimationState; import software.bernie.geckolib3.core.IAnimatable; import software.bernie.geckolib3.core.PlayState; import software.bernie.geckolib3.core.builder.AnimationBuilder; import software.bernie.geckolib3.core.controller.AnimationController; import software.bernie.geckolib3.core.event.SoundKeyframeEvent; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.manager.AnimationData; import software.bernie.geckolib3.core.manager.AnimationFactory; import software.bernie.geckolib3.util.GeckoLibUtil; import javax.annotation.Nullable; import java.util.List; import java.util.UUID;
12,197
this.eat(false); } if (this.isEating()) { if (!this.level.isClientSide && this.getEatCounter() > 6000) { if (!this.getMainHandItem().isEmpty()) { if (!this.level.isClientSide) { this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY); this.gameEvent(GameEvent.EAT); } } this.eat(false); return; } this.setEatCounter(this.getEatCounter() + 1); } } // EATING @Override public boolean canTakeItem(ItemStack pItemstack) { EquipmentSlot slot = getEquipmentSlotForItem(pItemstack); if (!this.getItemBySlot(slot).isEmpty()) { return false; } else { return slot == EquipmentSlot.MAINHAND && super.canTakeItem(pItemstack); } } @Override protected void pickUpItem(ItemEntity pItemEntity) { ItemStack stack = pItemEntity.getItem(); if (this.getMainHandItem().isEmpty() && FOOD_ITEMS.test(stack)) { this.onItemPickup(pItemEntity); this.setItemSlot(EquipmentSlot.MAINHAND, stack); this.handDropChances[EquipmentSlot.MAINHAND.getIndex()] = 2.0F; this.take(pItemEntity, stack.getCount()); pItemEntity.discard(); } } @Override public boolean hurt(DamageSource pSource, float pAmount) { if (!this.getMainHandItem().isEmpty() && !this.level.isClientSide) { ItemEntity itemEntity = new ItemEntity(this.level, this.getX() + this.getLookAngle().x, this.getY() + 1.0D, this.getZ() + this.getLookAngle().z, this.getMainHandItem()); itemEntity.setPickUpDelay(80); itemEntity.setThrower(this.getUUID()); this.playSound(SoundEvents.FOX_SPIT, 1.0F, 1.0F); this.level.addFreshEntity(itemEntity); this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY); } return super.hurt(pSource, pAmount); } // MOVEMENT @Override protected float getClimbSpeedMultiplier() { return 0.5F; } @Override public float getSpeed() { return this.getMainHandItem().isEmpty() ? super.getSpeed() : super.getSpeed() * 0.5F; } // SLEEPING @Override public boolean canSleep() { long dayTime = this.level.getDayTime(); if (this.isAngry() || this.level.isWaterAt(this.blockPosition())) { return false; } else if (dayTime > 18000 && dayTime < 23000) { return false; } else return dayTime > 12000 && dayTime < 28000; } @Override public void setSleeping(boolean sleeping) { this.entityData.set(SLEEPING, sleeping); } @Override public boolean isSleeping() { return this.entityData.get(SLEEPING); } // ANGER @Override public void startPersistentAngerTimer() { this.setRemainingPersistentAngerTime(PERSISTENT_ANGER_TIME.sample(this.random)); } @Override public void setRemainingPersistentAngerTime(int pTime) { this.entityData.set(REMAINING_ANGER_TIME, pTime); } @Override public int getRemainingPersistentAngerTime() { return this.entityData.get(REMAINING_ANGER_TIME); } @Override public void setPersistentAngerTarget(@Nullable UUID pTarget) { this.persistentAngerTarget = pTarget; } @Nullable @Override public UUID getPersistentAngerTarget() { return this.persistentAngerTarget; } // SNAKE VARIANTS @Override public boolean doHurtTarget(Entity pEntity) {
package com.starfish_studios.naturalist.common.entity; public class Snake extends ClimbingAnimal implements SleepingAnimal, NeutralMob, IAnimatable { private final AnimationFactory factory = GeckoLibUtil.createFactory(this); private static final Ingredient FOOD_ITEMS = Ingredient.of(NaturalistTags.ItemTags.SNAKE_TEMPT_ITEMS); private static final Ingredient TAME_ITEMS = Ingredient.of(NaturalistTags.ItemTags.SNAKE_TAME_ITEMS); private static final UniformInt PERSISTENT_ANGER_TIME = TimeUtil.rangeOfSeconds(20, 39); private static final EntityDataAccessor<Integer> REMAINING_ANGER_TIME = SynchedEntityData.defineId(Snake.class, EntityDataSerializers.INT); private static final EntityDataAccessor<Boolean> SLEEPING = SynchedEntityData.defineId(Snake.class, EntityDataSerializers.BOOLEAN); private static final EntityDataAccessor<Integer> EAT_COUNTER = SynchedEntityData.defineId(Snake.class, EntityDataSerializers.INT); @Nullable private UUID persistentAngerTarget; public Snake(EntityType<? extends Animal> entityType, Level level) { super(entityType, level); this.setCanPickUpLoot(true); } // ATTRIBUTES/GOALS/LOGIC public static AttributeSupplier.Builder createAttributes() { return createMobAttributes().add(Attributes.MAX_HEALTH, 10.0D).add(Attributes.FOLLOW_RANGE, 20.0D).add(Attributes.MOVEMENT_SPEED, 0.18D).add(Attributes.ATTACK_DAMAGE, 6.0D); } @Override protected void registerGoals() { super.registerGoals(); this.goalSelector.addGoal(0, new FloatGoal(this)); this.goalSelector.addGoal(1, new SnakeMeleeAttackGoal(this, 1.75D, true)); this.goalSelector.addGoal(2, new SearchForItemsGoal(this, 1.2F, FOOD_ITEMS, 8.0D, 8.0D)); this.goalSelector.addGoal(3, new SleepGoal<>(this)); this.goalSelector.addGoal(4, new WaterAvoidingRandomStrollGoal(this, 1.0D)); this.goalSelector.addGoal(5, new LookAtPlayerGoal(this, Player.class, 6.0F)); this.goalSelector.addGoal(6, new RandomLookAroundGoal(this)); // this.goalSelector.addGoal(7, new SitWhenOrderedToGoal(this)); // this.goalSelector.addGoal(8, new FollowOwnerGoal(this, 1.0D, 10.0F, 2.0F, false)); this.targetSelector.addGoal(1, new HurtByTargetGoal(this)); this.targetSelector.addGoal(2, new NearestAttackableTargetGoal<>(this, Player.class, 10, true, false, this::isAngryAt)); this.targetSelector.addGoal(3, new NearestAttackableTargetGoal<>(this, Mob.class, 5, true, false, livingEntity -> livingEntity.getType().is(NaturalistTags.EntityTypes.SNAKE_HOSTILES) || (livingEntity instanceof Slime slime && slime.isTiny()))); this.targetSelector.addGoal(4, new ResetUniversalAngerTargetGoal<>(this, false)); } @Nullable @Override public AgeableMob getBreedOffspring(ServerLevel p_146743_, AgeableMob p_146744_) { return null; } public static boolean checkSnakeSpawnRules(EntityType<Snake> entityType, LevelAccessor level, MobSpawnType type, BlockPos pos, RandomSource random) { return level.getBlockState(pos.below()).is(BlockTags.RABBITS_SPAWNABLE_ON) && isBrightEnoughToSpawn(level, pos); } @Override public SpawnGroupData finalizeSpawn(ServerLevelAccessor pLevel, DifficultyInstance pDifficulty, MobSpawnType pReason, @Nullable SpawnGroupData pSpawnData, @Nullable CompoundTag pDataTag) { this.populateDefaultEquipmentSlots(random, pDifficulty); return super.finalizeSpawn(pLevel, pDifficulty, pReason, pSpawnData, pDataTag); } @Override protected void populateDefaultEquipmentSlots(RandomSource random, DifficultyInstance pDifficulty) { if (random.nextFloat() < 0.2F) { float chance = random.nextFloat(); ItemStack stack; if (chance < 0.05F) { stack = new ItemStack(Items.RABBIT_FOOT); } else if (chance < 0.1F) { stack = new ItemStack(Items.SLIME_BALL); } else if (chance < 0.15F) { stack = new ItemStack(Items.FEATHER); } else if (chance < 0.3F) { stack = new ItemStack(Items.RABBIT); } else { stack = new ItemStack(Items.CHICKEN); } this.setItemSlot(EquipmentSlot.MAINHAND, stack); } } @Override public boolean isFood(ItemStack pStack) { return FOOD_ITEMS.test(pStack); } public boolean isTameFood(ItemStack pStack) { return TAME_ITEMS.test(pStack); } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(SLEEPING, false); this.entityData.define(EAT_COUNTER, 0); this.entityData.define(REMAINING_ANGER_TIME, 0); } @Override public void readAdditionalSaveData(CompoundTag pCompound) { super.readAdditionalSaveData(pCompound); this.readPersistentAngerSaveData(this.level, pCompound); } @Override public void addAdditionalSaveData(CompoundTag pCompound) { super.addAdditionalSaveData(pCompound); this.addPersistentAngerSaveData(pCompound); } public boolean isEating() { return this.entityData.get(EAT_COUNTER) > 0; } public void eat(boolean eat) { this.entityData.set(EAT_COUNTER, eat ? 1 : 0); } private int getEatCounter() { return this.entityData.get(EAT_COUNTER); } private void setEatCounter(int amount) { this.entityData.set(EAT_COUNTER, amount); } @Override public void aiStep() { super.aiStep(); if (!this.level.isClientSide) { this.updatePersistentAnger((ServerLevel)this.level, true); } if (this.isSleeping() || this.isImmobile()) { this.jumping = false; this.xxa = 0.0F; this.zza = 0.0F; } this.handleEating(); if (!this.getMainHandItem().isEmpty()) { if (this.isAngry()) { this.stopBeingAngry(); } } if (this.canRattle() && !this.isSleeping()) { this.playSound(NaturalistSoundEvents.SNAKE_RATTLE.get(), 0.15F, 1.0F); } } private void handleEating() { if (!this.isEating() && !this.isSleeping() && !this.getMainHandItem().isEmpty()) { this.eat(true); } else if (this.getMainHandItem().isEmpty()) { this.eat(false); } if (this.isEating()) { if (!this.level.isClientSide && this.getEatCounter() > 6000) { if (!this.getMainHandItem().isEmpty()) { if (!this.level.isClientSide) { this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY); this.gameEvent(GameEvent.EAT); } } this.eat(false); return; } this.setEatCounter(this.getEatCounter() + 1); } } // EATING @Override public boolean canTakeItem(ItemStack pItemstack) { EquipmentSlot slot = getEquipmentSlotForItem(pItemstack); if (!this.getItemBySlot(slot).isEmpty()) { return false; } else { return slot == EquipmentSlot.MAINHAND && super.canTakeItem(pItemstack); } } @Override protected void pickUpItem(ItemEntity pItemEntity) { ItemStack stack = pItemEntity.getItem(); if (this.getMainHandItem().isEmpty() && FOOD_ITEMS.test(stack)) { this.onItemPickup(pItemEntity); this.setItemSlot(EquipmentSlot.MAINHAND, stack); this.handDropChances[EquipmentSlot.MAINHAND.getIndex()] = 2.0F; this.take(pItemEntity, stack.getCount()); pItemEntity.discard(); } } @Override public boolean hurt(DamageSource pSource, float pAmount) { if (!this.getMainHandItem().isEmpty() && !this.level.isClientSide) { ItemEntity itemEntity = new ItemEntity(this.level, this.getX() + this.getLookAngle().x, this.getY() + 1.0D, this.getZ() + this.getLookAngle().z, this.getMainHandItem()); itemEntity.setPickUpDelay(80); itemEntity.setThrower(this.getUUID()); this.playSound(SoundEvents.FOX_SPIT, 1.0F, 1.0F); this.level.addFreshEntity(itemEntity); this.setItemSlot(EquipmentSlot.MAINHAND, ItemStack.EMPTY); } return super.hurt(pSource, pAmount); } // MOVEMENT @Override protected float getClimbSpeedMultiplier() { return 0.5F; } @Override public float getSpeed() { return this.getMainHandItem().isEmpty() ? super.getSpeed() : super.getSpeed() * 0.5F; } // SLEEPING @Override public boolean canSleep() { long dayTime = this.level.getDayTime(); if (this.isAngry() || this.level.isWaterAt(this.blockPosition())) { return false; } else if (dayTime > 18000 && dayTime < 23000) { return false; } else return dayTime > 12000 && dayTime < 28000; } @Override public void setSleeping(boolean sleeping) { this.entityData.set(SLEEPING, sleeping); } @Override public boolean isSleeping() { return this.entityData.get(SLEEPING); } // ANGER @Override public void startPersistentAngerTimer() { this.setRemainingPersistentAngerTime(PERSISTENT_ANGER_TIME.sample(this.random)); } @Override public void setRemainingPersistentAngerTime(int pTime) { this.entityData.set(REMAINING_ANGER_TIME, pTime); } @Override public int getRemainingPersistentAngerTime() { return this.entityData.get(REMAINING_ANGER_TIME); } @Override public void setPersistentAngerTarget(@Nullable UUID pTarget) { this.persistentAngerTarget = pTarget; } @Nullable @Override public UUID getPersistentAngerTarget() { return this.persistentAngerTarget; } // SNAKE VARIANTS @Override public boolean doHurtTarget(Entity pEntity) {
if ((this.getType().equals(NaturalistEntityTypes.CORAL_SNAKE.get()) || this.getType().equals(NaturalistEntityTypes.RATTLESNAKE.get())) && pEntity instanceof LivingEntity living) {
4
2023-10-16 21:54:32+00:00
16k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/ActionRecyclerListFragment.java
[ { "identifier": "DBHelper", "path": "app/src/main/java/cn/wq/myandroidtoolspro/helper/DBHelper.java", "snippet": "public class DBHelper extends SQLiteOpenHelper {\n\tprivate static final String DB_NAME = \"actions.db\";\n\tprivate static final int DB_VERSION = 10;\n\tpublic static final String ACTION_TA...
import android.app.Activity; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.LoaderManager; import android.support.v4.content.AsyncTaskLoader; import android.support.v4.content.Loader; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Filter; import android.widget.Filterable; import android.widget.TextView; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.helper.DBHelper; import cn.wq.myandroidtoolspro.helper.Utils; import cn.wq.myandroidtoolspro.model.ActionEntry; import cn.wq.myandroidtoolspro.model.ReceiverEntry; import cn.wq.myandroidtoolspro.recyclerview.base.SearchRecyclerListFragment;
13,504
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ActionRecyclerListFragment extends SearchRecyclerListFragment implements LoaderManager.LoaderCallbacks<List<ActionEntry>>{ public static final String ANDROID_RESOURCES = "http://schemas.android.com/apk/res/android"; private ActionAdapter actionAdapter; private int clicked_pos = -1; private FinishReceiver mReceiver; private static boolean isAllShown; //需要等两外两个加载完成才能开始加载数据库 private boolean isPrepared; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } private class FinishReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent data) {
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ActionRecyclerListFragment extends SearchRecyclerListFragment implements LoaderManager.LoaderCallbacks<List<ActionEntry>>{ public static final String ANDROID_RESOURCES = "http://schemas.android.com/apk/res/android"; private ActionAdapter actionAdapter; private int clicked_pos = -1; private FinishReceiver mReceiver; private static boolean isAllShown; //需要等两外两个加载完成才能开始加载数据库 private boolean isPrepared; private Context mContext; @Override public void onAttach(Context context) { super.onAttach(context); mContext = context; } private class FinishReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent data) {
if (Utils.ACTION_RECEIVER_FINISH.equals(data.getAction())) {
1
2023-10-18 14:32:49+00:00
16k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/impl/Oceanbase4Dc.java
[ { "identifier": "CalculationMode", "path": "internal/otel-dc/src/main/java/com/instana/dc/CalculationMode.java", "snippet": "public enum CalculationMode {\n DIRECT,\n RATE\n}" }, { "identifier": "DcException", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcException.java", ...
import com.instana.dc.CalculationMode; import com.instana.dc.DcException; import com.instana.dc.DcUtil; import com.instana.dc.rdb.AbstractDbDc; import io.opentelemetry.api.OpenTelemetry; import java.sql.Connection; import java.sql.SQLException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static com.instana.agent.sensorsdk.semconv.SemanticAttributes.SQL_TEXT; import static com.instana.dc.rdb.DbDcUtil.*; import static com.instana.dc.rdb.impl.Oceanbase4Util.*;
12,525
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class Oceanbase4Dc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(Oceanbase4Dc.class.getName()); boolean isCluster = false; boolean isTenant = false; public Oceanbase4Dc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException, DcException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } try (Connection conn = getConnection()) { setDbVersion(getSimpleStringWithSql(conn, DB_VERSION_SQL)); if (this.getDbEntityType().equals(TYPE_CLUSTER)) { isCluster = true; this.setDbTenantId("1"); this.setDbTenantName("sys"); } else if (getDbEntityType().equals(TYPE_TENANT)) { isTenant = true; String tId = getDbTenantId(); String tName = getDbTenantName(); if (tId == null) { if (tName == null) { throw new DcException(DB_TENANT_ID + " or " + DB_TENANT_NAME + " must be provided!"); } setDbTenantId(getSimpleStringWithSql(conn, DB_TENANT_NAME2ID_SQL.replace(TENANT_HOLDER, tName))); } else if (tName == null) { setDbTenantName(getSimpleStringWithSql(conn, DB_TENANT_ID2NAME_SQL.replace(TENANT_HOLDER, tId))); } } else { throw new DcException("Unsupported entity type of Oceanbase"); } } } @Override public void registerMetrics() { super.registerMetrics(); getRawMetric(DB_TRANSACTION_RATE_NAME).setCalculationMode(CalculationMode.RATE); getRawMetric(DB_SQL_RATE_NAME).setCalculationMode(CalculationMode.RATE); getRawMetric(DB_IO_READ_RATE_NAME).setCalculationMode(CalculationMode.RATE); getRawMetric(DB_IO_WRITE_RATE_NAME).setCalculationMode(CalculationMode.RATE); } @Override public void collectData() { logger.info("Start to collect metrics"); try (Connection conn = getConnection()) { getRawMetric(DB_STATUS_NAME).setValue(1); getRawMetric(DB_INSTANCE_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, INSTANCE_COUNT_SQL)); getRawMetric(DB_INSTANCE_ACTIVE_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, INSTANCE_ACTIVE_COUNT_SQL)); if (isCluster) { getRawMetric(DB_SESSION_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, SESSION_COUNT_SQL0)); getRawMetric(DB_SESSION_ACTIVE_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, SESSION_ACTIVE_COUNT_SQL0)); getRawMetric(DB_TRANSACTION_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, TRANSACTION_COUNT_SQL0)); getRawMetric(DB_TRANSACTION_RATE_NAME).setValue(getSimpleMetricWithSql(conn, TRANSACTION_COUNT_SQL0)); getRawMetric(DB_TRANSACTION_LATENCY_NAME).setValue(getSimpleMetricWithSql(conn, TRANSACTION_LATENCY_SQL0)); getRawMetric(DB_SQL_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, SQL_COUNT_SQL0)); getRawMetric(DB_SQL_RATE_NAME).setValue(getSimpleMetricWithSql(conn, SQL_COUNT_SQL0)); getRawMetric(DB_IO_READ_RATE_NAME).setValue(getSimpleMetricWithSql(conn, IO_READ_COUNT_SQL0)); getRawMetric(DB_IO_WRITE_RATE_NAME).setValue(getSimpleMetricWithSql(conn, IO_WRITE_COUNT_SQL0)); getRawMetric(DB_TASK_WAIT_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, TASK_WAIT_COUNT_SQL0)); getRawMetric(DB_TASK_AVG_WAIT_TIME_NAME).setValue(getSimpleMetricWithSql(conn, TASK_AVG_WAIT_TIME_SQL0)); getRawMetric(DB_CACHE_HIT_NAME).setValue(getMetricWithSql(conn, CACHE_HIT_SQL0, DB_CACHE_HIT_KEY));
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb.impl; public class Oceanbase4Dc extends AbstractDbDc { private static final Logger logger = Logger.getLogger(Oceanbase4Dc.class.getName()); boolean isCluster = false; boolean isTenant = false; public Oceanbase4Dc(Map<String, String> properties, String dbSystem, String dbDriver) throws SQLException, DcException { super(properties, dbSystem, dbDriver); setDbPassword(DcUtil.base64Decode(getDbPassword())); if (getServiceInstanceId() == null) { setServiceInstanceId(getDbAddress() + ":" + getDbPort() + "@" + getDbName()); } try (Connection conn = getConnection()) { setDbVersion(getSimpleStringWithSql(conn, DB_VERSION_SQL)); if (this.getDbEntityType().equals(TYPE_CLUSTER)) { isCluster = true; this.setDbTenantId("1"); this.setDbTenantName("sys"); } else if (getDbEntityType().equals(TYPE_TENANT)) { isTenant = true; String tId = getDbTenantId(); String tName = getDbTenantName(); if (tId == null) { if (tName == null) { throw new DcException(DB_TENANT_ID + " or " + DB_TENANT_NAME + " must be provided!"); } setDbTenantId(getSimpleStringWithSql(conn, DB_TENANT_NAME2ID_SQL.replace(TENANT_HOLDER, tName))); } else if (tName == null) { setDbTenantName(getSimpleStringWithSql(conn, DB_TENANT_ID2NAME_SQL.replace(TENANT_HOLDER, tId))); } } else { throw new DcException("Unsupported entity type of Oceanbase"); } } } @Override public void registerMetrics() { super.registerMetrics(); getRawMetric(DB_TRANSACTION_RATE_NAME).setCalculationMode(CalculationMode.RATE); getRawMetric(DB_SQL_RATE_NAME).setCalculationMode(CalculationMode.RATE); getRawMetric(DB_IO_READ_RATE_NAME).setCalculationMode(CalculationMode.RATE); getRawMetric(DB_IO_WRITE_RATE_NAME).setCalculationMode(CalculationMode.RATE); } @Override public void collectData() { logger.info("Start to collect metrics"); try (Connection conn = getConnection()) { getRawMetric(DB_STATUS_NAME).setValue(1); getRawMetric(DB_INSTANCE_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, INSTANCE_COUNT_SQL)); getRawMetric(DB_INSTANCE_ACTIVE_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, INSTANCE_ACTIVE_COUNT_SQL)); if (isCluster) { getRawMetric(DB_SESSION_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, SESSION_COUNT_SQL0)); getRawMetric(DB_SESSION_ACTIVE_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, SESSION_ACTIVE_COUNT_SQL0)); getRawMetric(DB_TRANSACTION_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, TRANSACTION_COUNT_SQL0)); getRawMetric(DB_TRANSACTION_RATE_NAME).setValue(getSimpleMetricWithSql(conn, TRANSACTION_COUNT_SQL0)); getRawMetric(DB_TRANSACTION_LATENCY_NAME).setValue(getSimpleMetricWithSql(conn, TRANSACTION_LATENCY_SQL0)); getRawMetric(DB_SQL_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, SQL_COUNT_SQL0)); getRawMetric(DB_SQL_RATE_NAME).setValue(getSimpleMetricWithSql(conn, SQL_COUNT_SQL0)); getRawMetric(DB_IO_READ_RATE_NAME).setValue(getSimpleMetricWithSql(conn, IO_READ_COUNT_SQL0)); getRawMetric(DB_IO_WRITE_RATE_NAME).setValue(getSimpleMetricWithSql(conn, IO_WRITE_COUNT_SQL0)); getRawMetric(DB_TASK_WAIT_COUNT_NAME).setValue(getSimpleMetricWithSql(conn, TASK_WAIT_COUNT_SQL0)); getRawMetric(DB_TASK_AVG_WAIT_TIME_NAME).setValue(getSimpleMetricWithSql(conn, TASK_AVG_WAIT_TIME_SQL0)); getRawMetric(DB_CACHE_HIT_NAME).setValue(getMetricWithSql(conn, CACHE_HIT_SQL0, DB_CACHE_HIT_KEY));
getRawMetric(DB_SQL_ELAPSED_TIME_NAME).setValue(getMetricWithSql(conn, SQL_ELAPSED_TIME_SQL0, DB_SQL_ELAPSED_TIME_KEY, SQL_TEXT.getKey()));
4
2023-10-23 01:16:38+00:00
16k
histevehu/12306
business/src/main/java/com/steve/train/business/service/DailyTrainCarriageService.java
[ { "identifier": "DailyTrainCarriage", "path": "business/src/main/java/com/steve/train/business/domain/DailyTrainCarriage.java", "snippet": "public class DailyTrainCarriage {\n private Long id;\n\n private Date date;\n\n private String trainCode;\n\n private Integer index;\n\n private Stri...
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.ObjUtil; import cn.hutool.core.util.ObjectUtil; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.steve.train.business.domain.DailyTrainCarriage; import com.steve.train.business.domain.DailyTrainCarriageExample; import com.steve.train.business.domain.TrainCarriage; import com.steve.train.business.mapper.DailyTrainCarriageMapper; import com.steve.train.business.req.DailyTrainCarriageQueryReq; import com.steve.train.business.req.DailyTrainCarriageSaveReq; import com.steve.train.business.resp.DailyTrainCarriageQueryResp; import com.steve.train.common.enums.SeatColEnum; import com.steve.train.common.resp.PageResp; import com.steve.train.common.util.SnowFlakeUtil; import jakarta.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List;
11,447
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-11-01 10:47:36 * @description: 每日车箱服务(FreeMarker生成) */ @Service public class DailyTrainCarriageService { private static final Logger LOG = LoggerFactory.getLogger(DailyTrainCarriageService.class); @Resource private DailyTrainCarriageMapper dailyTrainCarriageMapper; @Resource private TrainCarriageService trainCarriageService; public void save(DailyTrainCarriageSaveReq req) { DateTime now = DateTime.now(); // 自动计算出列数和总座位数 List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType()); req.setColCount(seatColEnums.size()); req.setSeatCount(req.getColCount() * req.getRowCount());
package com.steve.train.business.service; /* * @author : Steve Hu * @date : 2023-11-01 10:47:36 * @description: 每日车箱服务(FreeMarker生成) */ @Service public class DailyTrainCarriageService { private static final Logger LOG = LoggerFactory.getLogger(DailyTrainCarriageService.class); @Resource private DailyTrainCarriageMapper dailyTrainCarriageMapper; @Resource private TrainCarriageService trainCarriageService; public void save(DailyTrainCarriageSaveReq req) { DateTime now = DateTime.now(); // 自动计算出列数和总座位数 List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType()); req.setColCount(seatColEnums.size()); req.setSeatCount(req.getColCount() * req.getRowCount());
DailyTrainCarriage dailyTrainCarriage = BeanUtil.copyProperties(req, DailyTrainCarriage.class);
0
2023-10-23 01:20:56+00:00
16k
team-moabam/moabam-BE
src/main/java/com/moabam/api/application/room/RoomService.java
[ { "identifier": "RoomType", "path": "src/main/java/com/moabam/api/domain/room/RoomType.java", "snippet": "public enum RoomType {\n\n\tMORNING,\n\tNIGHT\n}" }, { "identifier": "ErrorMessage", "path": "src/main/java/com/moabam/global/error/model/ErrorMessage.java", "snippet": "@Getter\n@Re...
import static com.moabam.api.domain.room.RoomType.*; import static com.moabam.global.error.model.ErrorMessage.*; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.room.mapper.ParticipantMapper; import com.moabam.api.application.room.mapper.RoomMapper; import com.moabam.api.application.room.mapper.RoutineMapper; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.RoomType; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.DailyMemberCertificationRepository; import com.moabam.api.domain.room.repository.ParticipantRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CreateRoomRequest; import com.moabam.api.dto.room.EnterRoomRequest; import com.moabam.api.dto.room.ModifyRoomRequest; import com.moabam.global.common.util.ClockHolder; import com.moabam.global.error.exception.BadRequestException; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.global.error.exception.NotFoundException; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
12,040
return savedRoom.getId(); } @Transactional public void modifyRoom(Long memberId, Long roomId, ModifyRoomRequest modifyRoomRequest) { Participant participant = getParticipant(memberId, roomId); validateManagerAuthorization(participant); Room room = participant.getRoom(); room.changeTitle(modifyRoomRequest.title()); room.changeAnnouncement(modifyRoomRequest.announcement()); room.changePassword(modifyRoomRequest.password()); room.changeMaxCount(modifyRoomRequest.maxUserCount()); if (room.getCertifyTime() != modifyRoomRequest.certifyTime()) { validateChangeCertifyTime(roomId); } room.changeCertifyTime(modifyRoomRequest.certifyTime()); } @Transactional public void enterRoom(Long memberId, Long roomId, EnterRoomRequest enterRoomRequest) { Room room = roomRepository.findWithPessimisticLockByIdAndDeletedAtIsNull(roomId).orElseThrow( () -> new NotFoundException(ROOM_NOT_FOUND)); validateRoomEnter(memberId, enterRoomRequest.password(), room); Member member = memberService.findMember(memberId); member.enterRoom(room.getRoomType()); room.increaseCurrentUserCount(); Participant participant = ParticipantMapper.toParticipant(room, memberId); participantRepository.save(participant); } @Transactional public void exitRoom(Long memberId, Long roomId) { Participant participant = getParticipant(memberId, roomId); Room room = participant.getRoom(); validateRoomExit(participant, room); Member member = memberService.findMember(memberId); member.exitRoom(room.getRoomType()); participant.removeRoom(); participantRepository.flush(); participantRepository.delete(participant); if (!participant.isManager()) { room.decreaseCurrentUserCount(); return; } roomRepository.delete(room); } @Transactional public void mandateManager(Long managerId, Long roomId, Long memberId) { Participant managerParticipant = getParticipant(managerId, roomId); Participant memberParticipant = getParticipant(memberId, roomId); validateManagerAuthorization(managerParticipant); Room room = managerParticipant.getRoom(); Member member = memberService.findMember(memberParticipant.getMemberId()); room.changeManagerNickname(member.getNickname()); managerParticipant.disableManager(); memberParticipant.enableManager(); } @Transactional public void deportParticipant(Long managerId, Long roomId, Long memberId) { validateDeportParticipant(managerId, memberId); Participant managerParticipant = getParticipant(managerId, roomId); Participant memberParticipant = getParticipant(memberId, roomId); validateManagerAuthorization(managerParticipant); Room room = managerParticipant.getRoom(); memberParticipant.removeRoom(); participantRepository.flush(); participantRepository.delete(memberParticipant); room.decreaseCurrentUserCount(); Member member = memberService.findMember(memberId); member.exitRoom(room.getRoomType()); } public boolean checkIfParticipant(Long memberId, Long roomId) { try { getParticipant(memberId, roomId); return true; } catch (NotFoundException e) { return false; } } public Room findRoom(Long roomId) { return roomRepository.findById(roomId) .orElseThrow(() -> new NotFoundException(ROOM_NOT_FOUND)); } private void validateChangeCertifyTime(Long roomId) { if (certificationService.existsAnyMemberCertification(roomId, clockHolder.date())) { throw new BadRequestException(UNAVAILABLE_TO_CHANGE_CERTIFY_TIME); } } private Participant getParticipant(Long memberId, Long roomId) { return participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); } private void validateDeportParticipant(Long managerId, Long memberId) { if (managerId.equals(memberId)) { throw new BadRequestException(PARTICIPANT_DEPORT_ERROR); } } private void validateManagerAuthorization(Participant participant) { if (!participant.isManager()) {
package com.moabam.api.application.room; @Service @RequiredArgsConstructor @Slf4j @Transactional(readOnly = true) public class RoomService { private final RoomRepository roomRepository; private final RoutineRepository routineRepository; private final ParticipantRepository participantRepository; private final ParticipantSearchRepository participantSearchRepository; private final DailyMemberCertificationRepository dailyMemberCertificationRepository; private final CertificationService certificationService; private final MemberService memberService; private final ClockHolder clockHolder; @Transactional public Long createRoom(Long memberId, CreateRoomRequest createRoomRequest) { Room room = RoomMapper.toRoomEntity(createRoomRequest); List<Routine> routines = RoutineMapper.toRoutineEntities(room, createRoomRequest.routines()); Participant participant = ParticipantMapper.toParticipant(room, memberId); validateEnteredRoomCount(memberId, room.getRoomType()); Member member = memberService.findMember(memberId); member.enterRoom(room.getRoomType()); participant.enableManager(); room.changeManagerNickname(member.getNickname()); Room savedRoom = roomRepository.save(room); routineRepository.saveAll(routines); participantRepository.save(participant); return savedRoom.getId(); } @Transactional public void modifyRoom(Long memberId, Long roomId, ModifyRoomRequest modifyRoomRequest) { Participant participant = getParticipant(memberId, roomId); validateManagerAuthorization(participant); Room room = participant.getRoom(); room.changeTitle(modifyRoomRequest.title()); room.changeAnnouncement(modifyRoomRequest.announcement()); room.changePassword(modifyRoomRequest.password()); room.changeMaxCount(modifyRoomRequest.maxUserCount()); if (room.getCertifyTime() != modifyRoomRequest.certifyTime()) { validateChangeCertifyTime(roomId); } room.changeCertifyTime(modifyRoomRequest.certifyTime()); } @Transactional public void enterRoom(Long memberId, Long roomId, EnterRoomRequest enterRoomRequest) { Room room = roomRepository.findWithPessimisticLockByIdAndDeletedAtIsNull(roomId).orElseThrow( () -> new NotFoundException(ROOM_NOT_FOUND)); validateRoomEnter(memberId, enterRoomRequest.password(), room); Member member = memberService.findMember(memberId); member.enterRoom(room.getRoomType()); room.increaseCurrentUserCount(); Participant participant = ParticipantMapper.toParticipant(room, memberId); participantRepository.save(participant); } @Transactional public void exitRoom(Long memberId, Long roomId) { Participant participant = getParticipant(memberId, roomId); Room room = participant.getRoom(); validateRoomExit(participant, room); Member member = memberService.findMember(memberId); member.exitRoom(room.getRoomType()); participant.removeRoom(); participantRepository.flush(); participantRepository.delete(participant); if (!participant.isManager()) { room.decreaseCurrentUserCount(); return; } roomRepository.delete(room); } @Transactional public void mandateManager(Long managerId, Long roomId, Long memberId) { Participant managerParticipant = getParticipant(managerId, roomId); Participant memberParticipant = getParticipant(memberId, roomId); validateManagerAuthorization(managerParticipant); Room room = managerParticipant.getRoom(); Member member = memberService.findMember(memberParticipant.getMemberId()); room.changeManagerNickname(member.getNickname()); managerParticipant.disableManager(); memberParticipant.enableManager(); } @Transactional public void deportParticipant(Long managerId, Long roomId, Long memberId) { validateDeportParticipant(managerId, memberId); Participant managerParticipant = getParticipant(managerId, roomId); Participant memberParticipant = getParticipant(memberId, roomId); validateManagerAuthorization(managerParticipant); Room room = managerParticipant.getRoom(); memberParticipant.removeRoom(); participantRepository.flush(); participantRepository.delete(memberParticipant); room.decreaseCurrentUserCount(); Member member = memberService.findMember(memberId); member.exitRoom(room.getRoomType()); } public boolean checkIfParticipant(Long memberId, Long roomId) { try { getParticipant(memberId, roomId); return true; } catch (NotFoundException e) { return false; } } public Room findRoom(Long roomId) { return roomRepository.findById(roomId) .orElseThrow(() -> new NotFoundException(ROOM_NOT_FOUND)); } private void validateChangeCertifyTime(Long roomId) { if (certificationService.existsAnyMemberCertification(roomId, clockHolder.date())) { throw new BadRequestException(UNAVAILABLE_TO_CHANGE_CERTIFY_TIME); } } private Participant getParticipant(Long memberId, Long roomId) { return participantSearchRepository.findOne(memberId, roomId) .orElseThrow(() -> new NotFoundException(PARTICIPANT_NOT_FOUND)); } private void validateDeportParticipant(Long managerId, Long memberId) { if (managerId.equals(memberId)) { throw new BadRequestException(PARTICIPANT_DEPORT_ERROR); } } private void validateManagerAuthorization(Participant participant) { if (!participant.isManager()) {
throw new ForbiddenException(ROOM_MODIFY_UNAUTHORIZED_REQUEST);
18
2023-10-20 06:15:43+00:00
16k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/dropdown/DropdownMenuPopup.java
[ { "identifier": "CallBack", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/CallBack.java", "snippet": "public interface CallBack<T> {\n \n /**\n * Call.\n *\n * @param t the t\n */\n public void call(T t);\n}" }, { "identifier": "FxKit", "path": "BaseUI/src/main...
import com.xm2013.jfx.common.CallBack; import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.container.SimpleVScrollPane; import com.xm2013.jfx.control.base.ColorType; import com.xm2013.jfx.control.base.SizeType; import com.xm2013.jfx.control.icon.XmIcon; import javafx.animation.AnimationTimer; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyBooleanWrapper; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.geometry.*; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.control.ScrollBar; import javafx.scene.effect.BlurType; import javafx.scene.effect.DropShadow; import javafx.scene.input.MouseEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.SVGPath; import javafx.scene.text.Font; import javafx.stage.Popup; import javafx.stage.Screen; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
11,814
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.dropdown; /** * 下拉菜单的下拉部分 */ public class DropdownMenuPopup extends Popup { /** * 动画从上向下渐显 */ public final static int DIRECTION_BOTTOM = 1; /** * 动画从左向右渐显 */ public final static int DIRECTION_RIGHT = 2; //内容容器 private final VBox popupContentPane; //内容容器过高会显示滚动条 private final SimpleVScrollPane scrollPane; //是否分组显示,如果分组显示,则父级菜单为不可选,最多支持三级分组 private final boolean useGroup;
/* * MIT License * * Copyright (c) 2023 tuxming@sina.com / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.dropdown; /** * 下拉菜单的下拉部分 */ public class DropdownMenuPopup extends Popup { /** * 动画从上向下渐显 */ public final static int DIRECTION_BOTTOM = 1; /** * 动画从左向右渐显 */ public final static int DIRECTION_RIGHT = 2; //内容容器 private final VBox popupContentPane; //内容容器过高会显示滚动条 private final SimpleVScrollPane scrollPane; //是否分组显示,如果分组显示,则父级菜单为不可选,最多支持三级分组 private final boolean useGroup;
private final SizeType sizeType;
4
2023-10-17 08:57:08+00:00
16k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/treebank/PennTreebankReader.java
[ { "identifier": "Tree", "path": "src/berkeley_parser/edu/berkeley/nlp/syntax/Tree.java", "snippet": "public class Tree<L> implements Serializable, Comparable<Tree<L>>,\n\t\tIterable<Tree<L>> {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tL label;\n\n\tList<Tree<L>> children;\n\n\tpublic vo...
import java.io.BufferedReader; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.AbstractCollection; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import edu.berkeley.nlp.syntax.Tree; import edu.berkeley.nlp.syntax.Trees; import edu.berkeley.nlp.util.ConcatenationIterator;
14,316
package edu.berkeley.nlp.treebank; /** * @author Dan Klein */ public class PennTreebankReader { static class TreeCollection extends AbstractCollection<Tree<String>> { List<File> files; static class TreeIteratorIterator implements Iterator<Iterator<Tree<String>>> { Iterator<File> fileIterator; Iterator<Tree<String>> nextTreeIterator; public boolean hasNext() { return nextTreeIterator != null; } public Iterator<Tree<String>> next() { Iterator<Tree<String>> currentTreeIterator = nextTreeIterator; advance(); return currentTreeIterator; } public void remove() { throw new UnsupportedOperationException(); } private void advance() { nextTreeIterator = null; while (nextTreeIterator == null && fileIterator.hasNext()) { try { File file = fileIterator.next();
package edu.berkeley.nlp.treebank; /** * @author Dan Klein */ public class PennTreebankReader { static class TreeCollection extends AbstractCollection<Tree<String>> { List<File> files; static class TreeIteratorIterator implements Iterator<Iterator<Tree<String>>> { Iterator<File> fileIterator; Iterator<Tree<String>> nextTreeIterator; public boolean hasNext() { return nextTreeIterator != null; } public Iterator<Tree<String>> next() { Iterator<Tree<String>> currentTreeIterator = nextTreeIterator; advance(); return currentTreeIterator; } public void remove() { throw new UnsupportedOperationException(); } private void advance() { nextTreeIterator = null; while (nextTreeIterator == null && fileIterator.hasNext()) { try { File file = fileIterator.next();
nextTreeIterator = new Trees.PennTreeReader(
1
2023-10-22 13:13:22+00:00
16k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/client/renderer/entity/RenderEnderman.java
[ { "identifier": "Material", "path": "src/minecraft/net/minecraft/block/material/Material.java", "snippet": "public class Material\n{\n public static final Material air = new MaterialTransparent(MapColor.airColor);\n public static final Material grass = new Material(MapColor.grassColor);\n publi...
import java.util.Random; import net.minecraft.block.material.Material; import net.minecraft.client.model.ModelEnderman; import net.minecraft.client.renderer.entity.layers.LayerEndermanEyes; import net.minecraft.client.renderer.entity.layers.LayerHeldBlock; import net.minecraft.entity.monster.EntityEnderman; import net.minecraft.util.ResourceLocation;
11,001
package net.minecraft.client.renderer.entity; public class RenderEnderman extends RenderLiving<EntityEnderman> { private static final ResourceLocation endermanTextures = new ResourceLocation("textures/entity/enderman/enderman.png"); private ModelEnderman endermanModel; private Random rnd = new Random(); public RenderEnderman(RenderManager renderManagerIn) { super(renderManagerIn, new ModelEnderman(0.0F), 0.5F); this.endermanModel = (ModelEnderman)super.mainModel; this.addLayer(new LayerEndermanEyes(this)); this.addLayer(new LayerHeldBlock(this)); } public void doRender(EntityEnderman entity, double x, double y, double z, float entityYaw, float partialTicks) {
package net.minecraft.client.renderer.entity; public class RenderEnderman extends RenderLiving<EntityEnderman> { private static final ResourceLocation endermanTextures = new ResourceLocation("textures/entity/enderman/enderman.png"); private ModelEnderman endermanModel; private Random rnd = new Random(); public RenderEnderman(RenderManager renderManagerIn) { super(renderManagerIn, new ModelEnderman(0.0F), 0.5F); this.endermanModel = (ModelEnderman)super.mainModel; this.addLayer(new LayerEndermanEyes(this)); this.addLayer(new LayerHeldBlock(this)); } public void doRender(EntityEnderman entity, double x, double y, double z, float entityYaw, float partialTicks) {
this.endermanModel.isCarrying = entity.getHeldBlockState().getBlock().getMaterial() != Material.air;
0
2023-10-15 00:21:15+00:00
16k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/editors/data/formats/scripts/field/FieldScriptEditor.java
[ { "identifier": "PokeditorManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java", "snippet": "public class PokeditorManager extends PanelManager\n{\n private static final Dimension dimension = new Dimension(1200, 714);\n\n public static final FlatSVGIcon sheetE...
import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.text.*; import io.github.turtleisaac.nds4j.ui.ThemeUtils; import io.github.turtleisaac.pokeditor.formats.GenericFileData; import io.github.turtleisaac.pokeditor.formats.scripts.GenericScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.ScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.LevelScriptData; import io.github.turtleisaac.pokeditor.formats.scripts.antlr4.ScriptDataProducer; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gui.*; import io.github.turtleisaac.pokeditor.gui.PokeditorManager; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditor; import io.github.turtleisaac.pokeditor.gui.editors.data.DefaultDataEditorPanel; import io.github.turtleisaac.pokeditor.gui.editors.data.EditorDataModel; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.*; import io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.ScriptDocument; import io.github.turtleisaac.pokeditor.gui.sheets.tables.FormatModel; import net.miginfocom.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List;
14,143
{ panel2.setLayout(new MigLayout( "insets 0,hidemode 3", // columns "[grow,fill]", // rows "[]" + "[]" + "[]" + "[]" + "[]" + "[]" + "[]" + "[grow]" + "[]" + "[]" + "[]")); //---- configLabel ---- configLabel.setText(bundle.getString("FieldScriptEditor.configLabel.text")); configLabel.setFont(new Font(".AppleSystemUIFont", Font.PLAIN, 16)); panel2.add(configLabel, "cell 0 0"); //---- levelScriptTypeComboBox ---- levelScriptTypeComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "Variable Value", "Map Change", "Screen Reset", "Load Game" })); levelScriptTypeComboBox.addActionListener(e -> levelScriptTypeSelectionChanged(e)); panel2.add(levelScriptTypeComboBox, "cell 0 0"); //---- scriptLabel ---- scriptLabel.setText(bundle.getString("FieldScriptEditor.scriptLabel.text")); panel2.add(scriptLabel, "cell 0 2"); //---- scriptNoField ---- scriptNoField.setModel(new SpinnerNumberModel(0, 0, 65535, 1)); panel2.add(scriptNoField, "cell 0 3,aligny top,grow 100 0"); //---- variableLabel ---- variableLabel.setText(bundle.getString("FieldScriptEditor.variableLabel.text")); panel2.add(variableLabel, "cell 0 4,aligny top,growy 0"); panel2.add(variableField, "cell 0 5,aligny top,grow 100 0"); //---- valueLabel ---- valueLabel.setText(bundle.getString("FieldScriptEditor.valueLabel.text")); panel2.add(valueLabel, "cell 0 6,aligny top,growy 0"); //---- valueField ---- valueField.setModel(new SpinnerNumberModel(0, 0, 65535, 1)); panel2.add(valueField, "cell 0 7,aligny top,grow 100 0"); //---- confirmButton ---- confirmButton.setText(bundle.getString("FieldScriptEditor.confirmButton.text")); confirmButton.setIcon(new ImageIcon(getClass().getResource("/pokeditor/icons/tick.png"))); confirmButton.setEnabled(false); confirmButton.addActionListener(e -> confirmButtonActionPerformed(e)); panel2.add(confirmButton, "cell 0 8"); //---- discardButton ---- discardButton.setText(bundle.getString("FieldScriptEditor.discardButton.text")); discardButton.setIcon(new ImageIcon(getClass().getResource("/pokeditor/icons/cross.png"))); discardButton.setEnabled(false); discardButton.addActionListener(e -> discardButtonActionPerformed(e)); panel2.add(discardButton, "cell 0 8"); //---- paddingCheckbox ---- paddingCheckbox.setText(bundle.getString("FieldScriptEditor.paddingCheckbox.text")); panel2.add(paddingCheckbox, "cell 0 9"); //---- addButton ---- addButton.setText(bundle.getString("FieldScriptEditor.addButton.text")); addButton.setIcon(null); addButton.setEnabled(false); addButton.addActionListener(e -> addButtonActionPerformed(e)); panel2.add(addButton, "cell 0 10"); //---- removeButton ---- removeButton.setText(bundle.getString("FieldScriptEditor.removeButton.text")); removeButton.setIcon(null); removeButton.setEnabled(false); removeButton.addActionListener(e -> removeButtonActionPerformed(e)); panel2.add(removeButton, "cell 0 10"); } levelScriptPanel.add(panel2, "cell 0 0 1 11"); //======== scrollPane3 ======== { //---- levelScriptList ---- levelScriptList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); levelScriptList.addListSelectionListener(e -> levelScriptListValueChanged(e)); levelScriptList.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { levelScriptListMousePressed(e); } }); scrollPane3.setViewportView(levelScriptList); } levelScriptPanel.add(scrollPane3, "cell 1 0 1 11,grow"); levelScriptPanel.add(separator2, "cell 0 1"); } //---- labelListDisplayControlButtonGroup ---- labelListDisplayControlButtonGroup.add(displayOnlyScriptsRadioButton); labelListDisplayControlButtonGroup.add(displayOnlyLabelsRadioButton); labelListDisplayControlButtonGroup.add(displayOnlyActionLabelsRadioButton); // JFormDesigner - End of component initialization //GEN-END:initComponents @formatter:on } @Override public Class<GenericScriptData> getDataClass() { return GenericScriptData.class; } @Override
/* * Created by JFormDesigner */ package io.github.turtleisaac.pokeditor.gui.editors.data.formats.scripts.field; /** * @author turtleisaac */ public class FieldScriptEditor extends DefaultDataEditor<GenericScriptData, FieldScriptEditor.FieldScriptContents> { private DefaultListModel<GenericScriptData.ScriptComponent> levelScriptDataListModel = new DefaultListModel<>(); private DefaultListModel<String> labelDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> actionDisplayListModel = new DefaultListModel<>(); private DefaultListModel<String> scriptDisplayListModel = new DefaultListModel<>(); private boolean editMode; private GenericScriptData.ScriptComponent selected; public FieldScriptEditor(List<GenericScriptData> data, List<TextBankData> textBankData) { super(new FieldScriptModel(data, textBankData)); editMode = false; initComponents(); // FieldScriptEditorKit editorKit = new FieldScriptEditorKit(); StyledDocument document = new ScriptDocument(textPane1); textPane1.setDocument(document); textPane1.setBackground(new Color(58, 56, 77)); textPane1.setScrollPane(scrollPane1); textPane1.setForeground(Color.WHITE); levelScriptTypeComboBox.setSelectedIndex(0); paddingCheckbox.setSelected(true); levelScriptList.setModel(levelScriptDataListModel); levelScriptList.setSelectedIndex(-1); levelScriptListValueChanged(null); clearInputFields(); // valueField.addChangeListener(e -> paramFieldTextChange()); // scriptNoField.addChangeListener(e -> paramFieldTextChange()); // variableField.addChangeListener(e -> paramFieldTextChange()); removeButton.setEnabled(false); try { JTextPane numberPane = new JTextPane(); // numberPane.setBackground(textPane1.getBackground()); // numberPane.setForeground(textPane1.getForeground()); textPane1.setLineNumberPane(numberPane); scrollPane1.setRowHeaderView(numberPane); } catch(BadLocationException e) { throw new RuntimeException(e); } setIcons(); } private void setIcons() { addButton.setIcon(PokeditorManager.rowInsertIcon); removeButton.setIcon(PokeditorManager.rowRemoveIcon); confirmButton.setIcon(ThemeUtils.validIcon); discardButton.setIcon(ThemeUtils.reloadIcon); } @Override public void selectedIndexedChanged(int idx, ActionEvent e) { super.selectedIndexedChanged(idx, e); EditorDataModel<FieldScriptContents> model = getModel(); GenericScriptData data = (GenericScriptData) model.getValueFor(idx, null); // errorsList.removeAll(); if (data instanceof ScriptData scriptData) { remove(levelScriptPanel); add(fieldScriptPanel, "cell 1 0"); ScriptDocument document = new ScriptDocument(textPane1); textPane1.setScriptDocument(document); resetDisplayedFieldScriptData(scriptData); try { document.insertString(0, scriptData.toString(), document.getStyle("regular")); } catch (BadLocationException ble) { System.err.println("Couldn't insert initial text into text pane."); } scrollPane1.getVerticalScrollBar().setValue(0); } else if (data instanceof LevelScriptData) { remove(fieldScriptPanel); add(levelScriptPanel, "cell 1 0"); levelScriptDataListModel = new DefaultListModel<>(); levelScriptDataListModel.addAll(data); levelScriptList.setModel(levelScriptDataListModel); } updateUI(); // errorsList.setModel(listModel); } @Override public void addNewEntry() { ResourceBundle bundle = ResourceBundle.getBundle("pokeditor.sheet_panel"); String message = bundle.getString("FieldScriptEditor.newEntryDialog.text"); String fieldScript = bundle.getString("FieldScriptEditor.newEntryDialog.option1.text"); String levelScript = bundle.getString("FieldScriptEditor.newEntryDialog.option2.text"); Object selection = JOptionPane.showInputDialog(this, message, "PokEditor", JOptionPane.INFORMATION_MESSAGE, null, new Object[] {fieldScript, levelScript}, fieldScript); EditorDataModel<FieldScriptContents> model = getModel(); if (model instanceof FormatModel<?, ?> formatModel) { List<GenericFileData> data = (List<GenericFileData>) formatModel.getData(); int newIndex = data.size(); if (selection.equals(fieldScript)) { data.add(new ScriptData()); } else if (selection.equals(levelScript)) { data.add(new LevelScriptData()); } else return; selectedIndexedChanged(newIndex, null); updateUI(); } } @Override public void deleteCurrentEntry() { } private void resetDisplayedFieldScriptData(ScriptData scriptData) { labelDisplayListModel = new DefaultListModel<>(); scriptDisplayListModel = new DefaultListModel<>(); actionDisplayListModel = new DefaultListModel<>(); int scriptCount = 1; for (GenericScriptData.ScriptComponent component : scriptData) { if (component instanceof GenericScriptData.ScriptLabel label) { if (label.getScriptID() == -1) { String str = component.toString(); if (str.contains(" ")) str = str.split(" ")[1]; labelDisplayListModel.addElement(str); } else scriptDisplayListModel.addElement("Script " + scriptCount++); } else if (component instanceof ScriptData.ActionLabel actionLabel) { actionDisplayListModel.addElement(actionLabel.toString()); } } displayOnlyScriptsRadioButton.setSelected(true); labelDisplayList.setModel(scriptDisplayListModel); updateUI(); } private void saveScriptChangesButtonPressed(ActionEvent e) { if (textPane1.getDocument() instanceof ScriptDocument scriptDocument) { try { ScriptData data = scriptDocument.getScriptData(); JOptionPane.showMessageDialog(this, "Script file saved!", "Field Script Editor", JOptionPane.INFORMATION_MESSAGE); EditorDataModel<FieldScriptContents> model = getModel(); model.setValueFor(data, getSelectedIndex(), null); resetDisplayedFieldScriptData(data); } catch(BadLocationException ex) { throw new RuntimeException(ex); } catch(ScriptDataProducer.ScriptCompilationException ex) { DefaultListModel<String> errorListModel = new DefaultListModel<>(); for (Throwable throwable : ex.getSuppressed()) { errorListModel.addElement(throwable.getMessage()); System.err.println(throwable.getMessage()); } errorsList.setModel(errorListModel); } } } private void startEditingExistingLevelScriptTrigger() { if (levelScriptList.getSelectedIndex() != -1) { editMode = true; toggleEditModeStates(); selected = levelScriptList.getSelectedValue(); scriptNoField.requestFocus(); if (!(selected instanceof LevelScriptData.LevelScriptTrigger selectedTrigger)) return; scriptNoField.setValue(selectedTrigger.getScriptTriggered()); levelScriptTypeComboBox.setSelectedIndex(selectedTrigger.getTriggerType()-1); if (selectedTrigger.getTriggerType() == LevelScriptData.VARIABLE_VALUE) { LevelScriptData.VariableValueTrigger selectedTrigger1 = (LevelScriptData.VariableValueTrigger) selectedTrigger; variableField.setEnabled(true); valueField.setEnabled(true); variableField.setValue(selectedTrigger1.getVariableToWatch()); valueField.setValue(selectedTrigger1.getExpectedValue()); } else { variableField.setValue(0); valueField.setValue(0); variableField.setEnabled(false); valueField.setEnabled(false); } } else { editMode = false; toggleEditModeStates(); } SwingUtilities.updateComponentTreeUI(this); } private void levelScriptListValueChanged(ListSelectionEvent e) { removeButton.setEnabled(!levelScriptList.isSelectionEmpty()); } private boolean allFieldsNotNull() { return scriptNoField.getValue() != null && variableField.getValue() != null && valueField.getValue() != null; } private boolean anyFieldEmpty() { return false; } private void paramFieldTextChange() { if (allFieldsNotNull()) { if (((Integer) scriptNoField.getValue()) != -1 && levelScriptTypeComboBox.getSelectedIndex() + 1 != LevelScriptData.VARIABLE_VALUE) { if (!addButton.isEnabled() && !editMode) { addButton.setEnabled(true); } } else if (anyFieldEmpty()) { if (addButton.isEnabled()) { addButton.setEnabled(false); } } else //all are filled { if (!addButton.isEnabled() && !editMode) { addButton.setEnabled(true); } } SwingUtilities.updateComponentTreeUI(this); } } private void levelScriptListMousePressed(MouseEvent e) { if (e.isPopupTrigger()) { JPopupMenu menu = new JPopupMenu(); JMenuItem editItem = new JMenuItem("Edit selected trigger"); JMenuItem removeItem = new JMenuItem("Remove selected trigger"); editItem.addActionListener(e1 -> startEditingExistingLevelScriptTrigger()); removeItem.addActionListener(this::removeButtonActionPerformed); if (levelScriptDataListModel.isEmpty()) { menu.setEnabled(false); editItem.setEnabled(false); removeItem.setEnabled(false); } menu.add(editItem); menu.add(removeItem); menu.show(levelScriptList, e.getX(), e.getY()); } } private LevelScriptData.LevelScriptTrigger addTriggerToList() { try { LevelScriptData.LevelScriptTrigger built = buildTriggerFromFields(); if (levelScriptDataListModel.contains(built)) { if(!editMode) { throw new RuntimeException("Duplicate trigger"); } else { built = null; } } else { levelScriptDataListModel.addElement(built); } clearInputFields(); return built; } catch (RuntimeException ex) { JOptionPane.showMessageDialog(this, ex.getMessage(), "Level Script Editor Error", JOptionPane.ERROR_MESSAGE); // ex.printStackTrace(); } return null; } private LevelScriptData.LevelScriptTrigger buildTriggerFromFields() { int triggerType = levelScriptTypeComboBox.getSelectedIndex() + 1; Integer scriptID = null, variableID = null, varExpectedValue = null; ArrayList<String> errorFields = new ArrayList<>(); scriptID = (Integer) scriptNoField.getValue(); if (scriptID == -1) errorFields.add("Script ID"); if (triggerType == LevelScriptData.VARIABLE_VALUE) { variableID = (Integer) variableField.getValue(); varExpectedValue = (Integer) valueField.getValue(); if (variableID == -1) errorFields.add("Variable To Watch"); if (varExpectedValue == -1) errorFields.add("Expected Value"); } if (!errorFields.isEmpty()) throw new RuntimeException("The following errors exist with this level script: " + errorFields); if (triggerType == LevelScriptData.VARIABLE_VALUE) { return new LevelScriptData.VariableValueTrigger(scriptID, variableID, varExpectedValue); } else { return new LevelScriptData.MapScreenLoadTrigger(triggerType, scriptID); } } private void confirmButtonActionPerformed(ActionEvent e) { GenericScriptData.ScriptComponent built = addTriggerToList(); if (built != null) levelScriptDataListModel.remove(levelScriptList.getSelectedIndex()); int count = -1; for (LevelScriptData.LevelScriptTrigger lst : Arrays.stream(levelScriptDataListModel.toArray()).map(s -> (LevelScriptData.LevelScriptTrigger) s).toList()) { if (!lst.equals(built)) { count++; } } levelScriptList.setSelectedIndex(count + 1); editMode = false; toggleEditModeStates(); } private void clearInputFields() { valueField.setValue(0); variableField.setValue(0); scriptNoField.setValue(0); } private void discardButtonActionPerformed(ActionEvent e) { clearInputFields(); editMode = false; toggleEditModeStates(); } private void toggleEditModeStates() { if (editMode) { removeButton.setEnabled(false); addButton.setEnabled(false); confirmButton.setEnabled(true); discardButton.setEnabled(true); confirmButton.setVisible(true); discardButton.setVisible(true); paddingCheckbox.setEnabled(false); } else { addButton.setEnabled(true); removeButton.setEnabled(true); confirmButton.setEnabled(false); discardButton.setEnabled(false); confirmButton.setVisible(false); discardButton.setVisible(false); paddingCheckbox.setEnabled(true); } } private void addButtonActionPerformed(ActionEvent e) { addTriggerToList(); } private void removeButtonActionPerformed(ActionEvent e) { if (levelScriptList.getSelectedIndex() != -1) levelScriptDataListModel.remove(levelScriptList.getSelectedIndex()); } void changeFieldVisibility(boolean setting) { variableLabel.setVisible(setting); variableField.setVisible(setting); valueLabel.setVisible(setting); valueField.setVisible(setting); variableField.setEnabled(setting); valueField.setEnabled(setting); } private void levelScriptTypeSelectionChanged(ActionEvent e) { changeFieldVisibility(levelScriptTypeComboBox.getSelectedIndex() + 1 == LevelScriptData.VARIABLE_VALUE); } private void labelDisplayListSelectionChanged(ListSelectionEvent e) { textPane1.getHighlighter().removeAllHighlights(); if (!labelDisplayList.isSelectionEmpty()) { ScriptDocument document = textPane1.getScriptDocument(); String text = null; try { text = document.getText(0, document.getLength()); String toFind; if (labelDisplayList.getModel().equals(scriptDisplayListModel)) { toFind = "script(" + (labelDisplayList.getSelectedIndex()+1) + ")"; } else toFind = labelDisplayList.getSelectedValue() + ":"; int index = text.indexOf(toFind); ScriptPane.gotoStartOfLine(textPane1, ScriptPane.getLineAtOffset(textPane1, index)); DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW); textPane1.getHighlighter().addHighlight(index, index + toFind.length(), highlightPainter); } catch (BadLocationException ex) { throw new RuntimeException(ex); } } } private void labelListDisplayControlButtonPressed(ActionEvent e) { if (!((JRadioButton) e.getSource()).isSelected()) return; if (displayOnlyLabelsRadioButton.isSelected()) { labelDisplayList.setModel(labelDisplayListModel); } else if (displayOnlyActionLabelsRadioButton.isSelected()) { labelDisplayList.setModel(actionDisplayListModel); } else // only scripts { labelDisplayList.setModel(scriptDisplayListModel); } } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents @formatter:off // Generated using JFormDesigner non-commercial license ResourceBundle bundle = ResourceBundle.getBundle("pokeditor.sheet_panel"); fieldScriptPanel = new JPanel(); scrollPane1 = new JScrollPane(); textPane1 = new ScriptPane(); panel1 = new JPanel(); labelJumpListLabel = new JLabel(); displayOnlyScriptsRadioButton = new JRadioButton(); displayOnlyLabelsRadioButton = new JRadioButton(); displayOnlyActionLabelsRadioButton = new JRadioButton(); scriptsScrollPane = new JScrollPane(); labelDisplayList = new JList<>(); errorsLabel = new JLabel(); errorsScrollPane = new JScrollPane(); errorsList = new JList<>(); saveFieldScriptButton = new JButton(); levelScriptPanel = new JPanel(); panel2 = new JPanel(); configLabel = new JLabel(); levelScriptTypeComboBox = new JComboBox<>(); scriptLabel = new JLabel(); scriptNoField = new JSpinner(); variableLabel = new JLabel(); variableField = new HexadecimalSpinner(); valueLabel = new JLabel(); valueField = new JSpinner(); confirmButton = new JButton(); discardButton = new JButton(); paddingCheckbox = new JCheckBox(); addButton = new JButton(); removeButton = new JButton(); scrollPane3 = new JScrollPane(); levelScriptList = new JList<>(); separator2 = new JSeparator(); labelListDisplayControlButtonGroup = new ButtonGroup(); //======== this ======== setLayout(new MigLayout( "hidemode 3,alignx center", // columns "[fill]" + "[grow,fill]", // rows "[]")); //======== fieldScriptPanel ======== { fieldScriptPanel.setLayout(new MigLayout( "insets 0,hidemode 3", // columns "[fill]" + "[grow,fill]" + "[grow,fill]", // rows "[]" + "[]")); //======== scrollPane1 ======== { scrollPane1.setBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED)); //---- textPane1 ---- textPane1.setToolTipText("moo"); scrollPane1.setViewportView(textPane1); } fieldScriptPanel.add(scrollPane1, "cell 0 0,grow,width 500:500:1000,height 500:500:500"); //======== panel1 ======== { panel1.setLayout(new MigLayout( "insets 0 0 0 10,hidemode 3", // columns "[grow,fill]", // rows "[]" + "[]" + "[]unrel" + "[]" + "[]")); //---- labelJumpListLabel ---- labelJumpListLabel.setText(bundle.getString("FieldScriptEditor.labelJumpListLabel.text")); labelJumpListLabel.setFont(labelJumpListLabel.getFont().deriveFont(labelJumpListLabel.getFont().getSize() + 5f)); panel1.add(labelJumpListLabel, "cell 0 0"); //---- displayOnlyScriptsRadioButton ---- displayOnlyScriptsRadioButton.setText(bundle.getString("FieldScriptEditor.displayOnlyScriptsRadioButton.text")); displayOnlyScriptsRadioButton.addActionListener(e -> labelListDisplayControlButtonPressed(e)); panel1.add(displayOnlyScriptsRadioButton, "cell 0 1,alignx left,growx 0"); //---- displayOnlyLabelsRadioButton ---- displayOnlyLabelsRadioButton.setText(bundle.getString("FieldScriptEditor.displayOnlyLabelsRadioButton.text")); displayOnlyLabelsRadioButton.setSelected(true); displayOnlyLabelsRadioButton.addActionListener(e -> labelListDisplayControlButtonPressed(e)); panel1.add(displayOnlyLabelsRadioButton, "cell 0 1,alignx left,growx 0"); //---- displayOnlyActionLabelsRadioButton ---- displayOnlyActionLabelsRadioButton.setText(bundle.getString("FieldScriptEditor.displayOnlyActionLabelsRadioButton.text")); displayOnlyActionLabelsRadioButton.addActionListener(e -> labelListDisplayControlButtonPressed(e)); panel1.add(displayOnlyActionLabelsRadioButton, "cell 0 1"); //======== scriptsScrollPane ======== { //---- labelDisplayList ---- labelDisplayList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); labelDisplayList.addListSelectionListener(e -> labelDisplayListSelectionChanged(e)); scriptsScrollPane.setViewportView(labelDisplayList); } panel1.add(scriptsScrollPane, "cell 0 2"); //---- errorsLabel ---- errorsLabel.setText(bundle.getString("FieldScriptEditor.errorsLabel.text")); errorsLabel.setFont(errorsLabel.getFont().deriveFont(errorsLabel.getFont().getSize() + 5f)); panel1.add(errorsLabel, "cell 0 3"); //======== errorsScrollPane ======== { errorsScrollPane.setViewportView(errorsList); } panel1.add(errorsScrollPane, "cell 0 4"); } fieldScriptPanel.add(panel1, "cell 2 0,grow"); //---- saveFieldScriptButton ---- saveFieldScriptButton.setText(bundle.getString("FieldScriptEditor.saveFieldScriptButton.text")); saveFieldScriptButton.addActionListener(e -> saveScriptChangesButtonPressed(e)); fieldScriptPanel.add(saveFieldScriptButton, "cell 0 1"); } add(fieldScriptPanel, "cell 1 0"); //======== levelScriptPanel ======== { levelScriptPanel.setLayout(new MigLayout( "insets null 200 null null,hidemode 3,alignx center", // columns "[left]ind" + "[grow,fill]", // rows "[]" + "[]" + "[]" + "[]" + "[]" + "[]" + "[]" + "[grow]" + "[]" + "[]" + "[]")); //======== panel2 ======== { panel2.setLayout(new MigLayout( "insets 0,hidemode 3", // columns "[grow,fill]", // rows "[]" + "[]" + "[]" + "[]" + "[]" + "[]" + "[]" + "[grow]" + "[]" + "[]" + "[]")); //---- configLabel ---- configLabel.setText(bundle.getString("FieldScriptEditor.configLabel.text")); configLabel.setFont(new Font(".AppleSystemUIFont", Font.PLAIN, 16)); panel2.add(configLabel, "cell 0 0"); //---- levelScriptTypeComboBox ---- levelScriptTypeComboBox.setModel(new DefaultComboBoxModel<>(new String[] { "Variable Value", "Map Change", "Screen Reset", "Load Game" })); levelScriptTypeComboBox.addActionListener(e -> levelScriptTypeSelectionChanged(e)); panel2.add(levelScriptTypeComboBox, "cell 0 0"); //---- scriptLabel ---- scriptLabel.setText(bundle.getString("FieldScriptEditor.scriptLabel.text")); panel2.add(scriptLabel, "cell 0 2"); //---- scriptNoField ---- scriptNoField.setModel(new SpinnerNumberModel(0, 0, 65535, 1)); panel2.add(scriptNoField, "cell 0 3,aligny top,grow 100 0"); //---- variableLabel ---- variableLabel.setText(bundle.getString("FieldScriptEditor.variableLabel.text")); panel2.add(variableLabel, "cell 0 4,aligny top,growy 0"); panel2.add(variableField, "cell 0 5,aligny top,grow 100 0"); //---- valueLabel ---- valueLabel.setText(bundle.getString("FieldScriptEditor.valueLabel.text")); panel2.add(valueLabel, "cell 0 6,aligny top,growy 0"); //---- valueField ---- valueField.setModel(new SpinnerNumberModel(0, 0, 65535, 1)); panel2.add(valueField, "cell 0 7,aligny top,grow 100 0"); //---- confirmButton ---- confirmButton.setText(bundle.getString("FieldScriptEditor.confirmButton.text")); confirmButton.setIcon(new ImageIcon(getClass().getResource("/pokeditor/icons/tick.png"))); confirmButton.setEnabled(false); confirmButton.addActionListener(e -> confirmButtonActionPerformed(e)); panel2.add(confirmButton, "cell 0 8"); //---- discardButton ---- discardButton.setText(bundle.getString("FieldScriptEditor.discardButton.text")); discardButton.setIcon(new ImageIcon(getClass().getResource("/pokeditor/icons/cross.png"))); discardButton.setEnabled(false); discardButton.addActionListener(e -> discardButtonActionPerformed(e)); panel2.add(discardButton, "cell 0 8"); //---- paddingCheckbox ---- paddingCheckbox.setText(bundle.getString("FieldScriptEditor.paddingCheckbox.text")); panel2.add(paddingCheckbox, "cell 0 9"); //---- addButton ---- addButton.setText(bundle.getString("FieldScriptEditor.addButton.text")); addButton.setIcon(null); addButton.setEnabled(false); addButton.addActionListener(e -> addButtonActionPerformed(e)); panel2.add(addButton, "cell 0 10"); //---- removeButton ---- removeButton.setText(bundle.getString("FieldScriptEditor.removeButton.text")); removeButton.setIcon(null); removeButton.setEnabled(false); removeButton.addActionListener(e -> removeButtonActionPerformed(e)); panel2.add(removeButton, "cell 0 10"); } levelScriptPanel.add(panel2, "cell 0 0 1 11"); //======== scrollPane3 ======== { //---- levelScriptList ---- levelScriptList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); levelScriptList.addListSelectionListener(e -> levelScriptListValueChanged(e)); levelScriptList.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { levelScriptListMousePressed(e); } }); scrollPane3.setViewportView(levelScriptList); } levelScriptPanel.add(scrollPane3, "cell 1 0 1 11,grow"); levelScriptPanel.add(separator2, "cell 0 1"); } //---- labelListDisplayControlButtonGroup ---- labelListDisplayControlButtonGroup.add(displayOnlyScriptsRadioButton); labelListDisplayControlButtonGroup.add(displayOnlyLabelsRadioButton); labelListDisplayControlButtonGroup.add(displayOnlyActionLabelsRadioButton); // JFormDesigner - End of component initialization //GEN-END:initComponents @formatter:on } @Override public Class<GenericScriptData> getDataClass() { return GenericScriptData.class; } @Override
public Set<DefaultDataEditorPanel.DataEditorButtons> getEnabledToolbarButtons()
2
2023-10-15 05:00:57+00:00
16k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q10.java
[ { "identifier": "OLAPTerminal", "path": "code/src/main/java/benchmark/olap/OLAPTerminal.java", "snippet": "public class OLAPTerminal implements Runnable {\n // public static AtomicInteger DeliveryBG=new AtomicInteger(0);\n public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.qu...
import benchmark.olap.OLAPTerminal; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import static benchmark.oltp.OLTPClient.gloabalSysCurrentTime; import static config.CommonConfig.DB_OCEANBASE;
14,190
package benchmark.olap.query; public class Q10 extends baseQuery { private static Logger log = Logger.getLogger(Q10.class); public double k; public double b; private int dbType; public Q10(int dbType) throws ParseException { super();
package benchmark.olap.query; public class Q10 extends baseQuery { private static Logger log = Logger.getLogger(Q10.class); public double k; public double b; private int dbType; public Q10(int dbType) throws ParseException { super();
this.k = OLTPClient.k1;
1
2023-10-22 11:22:32+00:00
16k
AstroDev2023/2023-studio-1-but-better
source/core/src/main/com/csse3200/game/entities/factories/ProjectileFactory.java
[ { "identifier": "CombatStatsComponent", "path": "source/core/src/main/com/csse3200/game/components/combat/CombatStatsComponent.java", "snippet": "public class CombatStatsComponent extends Component {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(CombatStatsComponent.class);\n\tprivat...
import com.badlogic.gdx.graphics.g2d.Animation; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.Vector2; import com.csse3200.game.components.combat.CombatStatsComponent; import com.csse3200.game.components.combat.ProjectileAnimationController; import com.csse3200.game.components.combat.ProjectileComponent; import com.csse3200.game.components.combat.TouchAttackComponent; import com.csse3200.game.entities.Entity; import com.csse3200.game.physics.PhysicsLayer; import com.csse3200.game.physics.components.HitboxComponent; import com.csse3200.game.physics.components.PhysicsComponent; import com.csse3200.game.rendering.AnimationRenderComponent; import com.csse3200.game.services.ServiceLocator;
13,228
package com.csse3200.game.entities.factories; /** * The ProjectileFactory class is responsible for creating different types of projectile entities * used in the game. */ public class ProjectileFactory { /** * Constant for the flight event. */ private static final String FLIGHTEVENT = "flight"; private static final String IMPACTEVENT = "impact"; /** * Creates an oxygen eater projectile entity. * * @return The created oxygen eater projectile entity. */ public static Entity createOxygenEaterProjectile() { Entity projectile = createBaseProjectile(); AnimationRenderComponent animator = new AnimationRenderComponent( ServiceLocator.getResourceService().getAsset("images/projectiles/oxygen_eater_projectile.atlas", TextureAtlas.class), 16f ); animator.addAnimation(FLIGHTEVENT, 0.5f, Animation.PlayMode.LOOP); animator.addAnimation(IMPACTEVENT, 0.1f); projectile .addComponent(new CombatStatsComponent(1, 1)) .addComponent(new ProjectileComponent(2f))
package com.csse3200.game.entities.factories; /** * The ProjectileFactory class is responsible for creating different types of projectile entities * used in the game. */ public class ProjectileFactory { /** * Constant for the flight event. */ private static final String FLIGHTEVENT = "flight"; private static final String IMPACTEVENT = "impact"; /** * Creates an oxygen eater projectile entity. * * @return The created oxygen eater projectile entity. */ public static Entity createOxygenEaterProjectile() { Entity projectile = createBaseProjectile(); AnimationRenderComponent animator = new AnimationRenderComponent( ServiceLocator.getResourceService().getAsset("images/projectiles/oxygen_eater_projectile.atlas", TextureAtlas.class), 16f ); animator.addAnimation(FLIGHTEVENT, 0.5f, Animation.PlayMode.LOOP); animator.addAnimation(IMPACTEVENT, 0.1f); projectile .addComponent(new CombatStatsComponent(1, 1)) .addComponent(new ProjectileComponent(2f))
.addComponent(new TouchAttackComponent(PhysicsLayer.PLAYER, 10f, 0.25f))
3
2023-10-17 22:34:04+00:00
16k
moeinfatehi/PassiveDigger
src/burp/BurpExtender.java
[ { "identifier": "PassiveAnalyzer", "path": "src/PassiveDigger/PassiveAnalyzer.java", "snippet": "public class PassiveAnalyzer extends javax.swing.JPanel implements burp.IHttpListener{\n private static String extension_name=\"Analyzer\";\n private static Scanner sc;\n public static List<vulnerab...
import PassiveDigger.PassiveAnalyzer; import java.io.PrintWriter; import javax.swing.*; import PassiveDigger.menuItem; import PassiveDigger.tab;
10,951
package burp; public class BurpExtender extends JPanel implements IBurpExtender { public static IBurpExtenderCallbacks callbacks; static JScrollPane frame; public static PrintWriter output; public static String project_Name="PassiveDigger"; private static final String project_Version="2.0.0"; public BurpExtender() { // this.historyModel = (DefaultTableModel)mainPanel.historyTable.getModel(); } @Override public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks) { // keep a reference to our callbacks object this.callbacks = callbacks;
package burp; public class BurpExtender extends JPanel implements IBurpExtender { public static IBurpExtenderCallbacks callbacks; static JScrollPane frame; public static PrintWriter output; public static String project_Name="PassiveDigger"; private static final String project_Version="2.0.0"; public BurpExtender() { // this.historyModel = (DefaultTableModel)mainPanel.historyTable.getModel(); } @Override public void registerExtenderCallbacks(final IBurpExtenderCallbacks callbacks) { // keep a reference to our callbacks object this.callbacks = callbacks;
callbacks.registerHttpListener(new PassiveAnalyzer());
0
2023-10-23 12:13:00+00:00
16k
Spectrum3847/SpectrumTraining
src/main/java/frc/robot/swerve/Swerve.java
[ { "identifier": "Robot", "path": "src/main/java/frc/robot/Robot.java", "snippet": "public class Robot extends LoggedRobot {\n public static RobotConfig config;\n public static RobotTelemetry telemetry;\n\n /** Create a single static instance of all of your subsystems */\n public static Train...
import edu.wpi.first.math.Matrix; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.math.numbers.N1; import edu.wpi.first.math.numbers.N3; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Subsystem; import frc.robot.Robot; import frc.robot.RobotTelemetry; import frc.robot.swerve.configs.MUSICDISC2023; import frc.robot.swerve.configs.NOTEBLOCK2023; import frc.spectrumLib.swerve.Drivetrain; import frc.spectrumLib.swerve.Drivetrain.DriveState; import frc.spectrumLib.swerve.Request; import frc.spectrumLib.swerve.config.SwerveConfig; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; import java.util.function.DoubleSupplier; import java.util.function.Supplier; import org.littletonrobotics.junction.Logger;
11,917
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config; private final Drivetrain drivetrain; private final RotationController rotationController; private double OdometryUpdateFrequency = 250; private double targetHeading = 0; private ReadWriteLock m_stateLock = new ReentrantReadWriteLock(); private SwerveModuleState[] Setpoints = new SwerveModuleState[] {}; public Swerve() { RobotTelemetry.print("Swerve Subsystem Starting: "); // Choose the correct swerve configuration switch (Robot.config.getRobotType()) { case NOTEBLOCK: config = NOTEBLOCK2023.config; break; case MUSICDISC: config = MUSICDISC2023.config; break; case SIM: // runs in simulation OdometryUpdateFrequency = 50; config = NOTEBLOCK2023.config; break; default: config = NOTEBLOCK2023.config; break; } drivetrain = new Drivetrain(config, OdometryUpdateFrequency); rotationController = new RotationController(this); RobotTelemetry.print("Swerve Subsystem Initialized: "); } @Override public void periodic() { // Log measured states Logger.recordOutput("SwerveStates/Measured", drivetrain.getState().ModuleStates); // Log empty setpoint states when disabled if (DriverStation.isDisabled()) { Logger.recordOutput("SwerveStates/Setpoints", new SwerveModuleState[] {}); } else { // Log setpoint states Logger.recordOutput("SwerveStates/Setpoints", readSetpoints()); ; } // Log Odometry Pose Logger.recordOutput("Odometry/Robot", getPose()); } @Override public void simulationPeriodic() { drivetrain.updateSimState(0.02, 12); } // Returns a commmand that applies the given request to the drivetrain public Command applyRequest(Supplier<Request> requestSupplier) { return run(() -> setControlMode(requestSupplier.get())); } // Use this to control the swerve drive, set motors, etc. public void setControlMode(Request mode) { drivetrain.setControl(mode); }
package frc.robot.swerve; public class Swerve implements Subsystem { public final SwerveConfig config; private final Drivetrain drivetrain; private final RotationController rotationController; private double OdometryUpdateFrequency = 250; private double targetHeading = 0; private ReadWriteLock m_stateLock = new ReentrantReadWriteLock(); private SwerveModuleState[] Setpoints = new SwerveModuleState[] {}; public Swerve() { RobotTelemetry.print("Swerve Subsystem Starting: "); // Choose the correct swerve configuration switch (Robot.config.getRobotType()) { case NOTEBLOCK: config = NOTEBLOCK2023.config; break; case MUSICDISC: config = MUSICDISC2023.config; break; case SIM: // runs in simulation OdometryUpdateFrequency = 50; config = NOTEBLOCK2023.config; break; default: config = NOTEBLOCK2023.config; break; } drivetrain = new Drivetrain(config, OdometryUpdateFrequency); rotationController = new RotationController(this); RobotTelemetry.print("Swerve Subsystem Initialized: "); } @Override public void periodic() { // Log measured states Logger.recordOutput("SwerveStates/Measured", drivetrain.getState().ModuleStates); // Log empty setpoint states when disabled if (DriverStation.isDisabled()) { Logger.recordOutput("SwerveStates/Setpoints", new SwerveModuleState[] {}); } else { // Log setpoint states Logger.recordOutput("SwerveStates/Setpoints", readSetpoints()); ; } // Log Odometry Pose Logger.recordOutput("Odometry/Robot", getPose()); } @Override public void simulationPeriodic() { drivetrain.updateSimState(0.02, 12); } // Returns a commmand that applies the given request to the drivetrain public Command applyRequest(Supplier<Request> requestSupplier) { return run(() -> setControlMode(requestSupplier.get())); } // Use this to control the swerve drive, set motors, etc. public void setControlMode(Request mode) { drivetrain.setControl(mode); }
public DriveState getState() {
5
2023-10-23 17:01:53+00:00
16k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/cases/indicators/CaseIndicatorsService.java
[ { "identifier": "Messages", "path": "src/main/java/org/msh/etbm/commons/Messages.java", "snippet": "@Component\npublic class Messages {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(Messages.class);\n\n public static final String NOT_UNIQUE = \"NotUnique\";\n public static fi...
import org.apache.commons.collections.map.HashedMap; import org.msh.etbm.commons.Messages; import org.msh.etbm.commons.entities.EntityValidationException; import org.msh.etbm.commons.filters.Filter; import org.msh.etbm.commons.filters.FilterGroupData; import org.msh.etbm.commons.indicators.IndicatorGenerator; import org.msh.etbm.commons.indicators.IndicatorRequest; import org.msh.etbm.commons.indicators.indicator.IndicatorDataTable; import org.msh.etbm.commons.indicators.indicator.client.IndicatorData; import org.msh.etbm.commons.indicators.indicator.client.IndicatorDataConverter; import org.msh.etbm.commons.indicators.variables.VariableGroupData; import org.msh.etbm.commons.sqlquery.SQLQueryBuilder; import org.msh.etbm.services.cases.filters.CaseFilters; import org.msh.etbm.services.cases.filters.impl.ScopeFilter; import org.msh.etbm.services.cases.filters.impl.ScopeFilterValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.sql.DataSource; import javax.validation.Valid; import java.util.List; import java.util.Map; import java.util.stream.Collectors;
13,175
package org.msh.etbm.services.cases.indicators; /** * Generates case indicators * * Created by rmemoria on 10/9/16. */ @Service public class CaseIndicatorsService { @Autowired CaseFilters caseFilters; @Autowired DataSource dataSource; @Autowired Messages messages; @Autowired IndicatorGenerator indicatorGenerator; /** * Generate initialization data for a client to request indicators * @return */ public CaseIndicatorInitResponse getInitData() { List<FilterGroupData> filters = caseFilters.getFiltersData();
package org.msh.etbm.services.cases.indicators; /** * Generates case indicators * * Created by rmemoria on 10/9/16. */ @Service public class CaseIndicatorsService { @Autowired CaseFilters caseFilters; @Autowired DataSource dataSource; @Autowired Messages messages; @Autowired IndicatorGenerator indicatorGenerator; /** * Generate initialization data for a client to request indicators * @return */ public CaseIndicatorInitResponse getInitData() { List<FilterGroupData> filters = caseFilters.getFiltersData();
List<VariableGroupData> variables = caseFilters.getVariablesData();
9
2023-10-23 13:47:54+00:00
16k
weibocom/rill-flow
rill-flow-dag/olympicene-traversal/src/main/java/com/weibo/rill/flow/olympicene/traversal/runners/TimeCheckRunner.java
[ { "identifier": "Timeline", "path": "rill-flow-interfaces/src/main/java/com/weibo/rill/flow/interfaces/model/strategy/Timeline.java", "snippet": "@Setter\n@Getter\npublic class Timeline {\n private String timeoutInSeconds;\n private String suspenseIntervalSeconds;\n private String suspenseTimes...
import com.google.common.collect.Lists; import com.weibo.rill.flow.interfaces.model.strategy.Timeline; import com.weibo.rill.flow.interfaces.model.task.BaseTask; import com.weibo.rill.flow.interfaces.model.task.TaskInfo; import com.weibo.rill.flow.interfaces.model.task.TaskInvokeMsg; import com.weibo.rill.flow.interfaces.model.task.TaskStatus; import com.weibo.rill.flow.olympicene.core.constant.SystemConfig; import com.weibo.rill.flow.olympicene.core.lock.LockerKey; import com.weibo.rill.flow.olympicene.core.model.NotifyInfo; import com.weibo.rill.flow.olympicene.core.model.dag.DAG; import com.weibo.rill.flow.olympicene.core.model.dag.DAGInvokeMsg; import com.weibo.rill.flow.olympicene.core.model.dag.DAGStatus; import com.weibo.rill.flow.olympicene.core.runtime.DAGContextStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGInfoStorage; import com.weibo.rill.flow.olympicene.core.runtime.DAGStorageProcedure; import com.weibo.rill.flow.olympicene.traversal.DAGOperations; import com.weibo.rill.flow.olympicene.traversal.checker.TimeCheckMember; import com.weibo.rill.flow.olympicene.traversal.checker.TimeChecker; import com.weibo.rill.flow.olympicene.traversal.helper.ContextHelper; import com.weibo.rill.flow.olympicene.traversal.serialize.DAGTraversalSerializer; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.Optional;
12,209
/* * Copyright 2021-2023 Weibo, Inc. * * 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.weibo.rill.flow.olympicene.traversal.runners; @Slf4j public class TimeCheckRunner {
/* * Copyright 2021-2023 Weibo, Inc. * * 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.weibo.rill.flow.olympicene.traversal.runners; @Slf4j public class TimeCheckRunner {
private final TimeChecker timeChecker;
16
2023-11-03 03:46:01+00:00
16k
aliyun/alibabacloud-compute-nest-saas-boost
boost.server/src/main/java/org/example/service/impl/OrderServiceImpl.java
[ { "identifier": "BaseResult", "path": "boost.common/src/main/java/org/example/common/BaseResult.java", "snippet": "@Data\npublic class BaseResult<T> implements Serializable {\n private static final long serialVersionUID = 5680133981298179266L;\n\n /**\n * Status code.\n */\n protected S...
import com.alicloud.openservices.tablestore.model.search.sort.FieldSort; import com.alicloud.openservices.tablestore.model.search.sort.Sort.Sorter; import com.alicloud.openservices.tablestore.model.search.sort.SortOrder; import com.alipay.api.AlipayApiException; import com.aliyun.computenestsupplier20210521.models.CreateServiceInstanceResponse; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.example.common.BaseResult; import org.example.common.ListResult; import org.example.common.constant.ComputeNestConstants; import org.example.common.constant.OrderOtsConstant; import org.example.common.constant.PayPeriodUnit; import org.example.common.constant.TradeStatus; import org.example.common.dataobject.OrderDO; import org.example.common.dto.OrderDTO; import org.example.common.errorinfo.ErrorInfo; import org.example.common.exception.BizException; import org.example.common.helper.BaseOtsHelper.OtsFilter; import org.example.common.helper.OrderOtsHelper; import org.example.common.helper.ServiceInstanceLifeStyleHelper; import org.example.common.helper.WalletHelper; import org.example.common.model.ServiceMetadataModel; import org.example.common.model.UserInfoModel; import org.example.common.param.CreateOrderParam; import org.example.common.param.GetOrderParam; import org.example.common.param.GetServiceCostParam; import org.example.common.param.GetServiceMetadataParam; import org.example.common.param.ListOrdersParam; import org.example.common.param.RefundOrderParam; import org.example.common.param.UpdateServiceInstanceAttributeParam; import org.example.common.utils.BeanUtil; import org.example.common.utils.DateUtil; import org.example.common.utils.JsonUtil; import org.example.common.utils.UuidUtil; import org.example.service.AlipayService; import org.example.service.OrderService; import org.example.service.ServiceInstanceLifecycleService; import org.example.service.ServiceManager; import org.springframework.beans.BeanUtils; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD; import static org.example.common.constant.ComputeNestConstants.PAY_PERIOD_UNIT;
12,828
/* *Copyright (c) Alibaba Group; *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 org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override public BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException { Long accountId = userInfoModel.getAid() == null ? null : Long.parseLong(userInfoModel.getAid()); String orderId = UuidUtil.generateOrderId(accountId, param.getType().getValue(), userInfoModel.getSub()); Map<String, Object> nestParameters = (Map<String, Object>) JsonUtil.parseObjectCustom(param.getProductComponents(), Map.class); if (nestParameters == null) { return BaseResult.fail("product components can't be null."); } Long payPeriod = ((Number) nestParameters.remove(PAY_PERIOD)).longValue(); PayPeriodUnit payPeriodUnit = PayPeriodUnit.valueOf(String.valueOf(nestParameters.remove(PAY_PERIOD_UNIT)));
/* *Copyright (c) Alibaba Group; *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 org.example.service.impl; @Service @Slf4j public class OrderServiceImpl implements OrderService { @Resource private AlipayService alipayService; @Resource private OrderOtsHelper orderOtsHelper; @Resource private WalletHelper walletHelper; @Resource private ServiceInstanceLifecycleService serviceInstanceLifecycleService; @Resource private ServiceManager serviceManager; @Resource private ServiceInstanceLifeStyleHelper serviceInstanceLifeStyleHelper; private static final Integer DEFAULT_RETENTION_DAYS = 15; @Override public BaseResult<String> createOrder(UserInfoModel userInfoModel, CreateOrderParam param) throws AlipayApiException { Long accountId = userInfoModel.getAid() == null ? null : Long.parseLong(userInfoModel.getAid()); String orderId = UuidUtil.generateOrderId(accountId, param.getType().getValue(), userInfoModel.getSub()); Map<String, Object> nestParameters = (Map<String, Object>) JsonUtil.parseObjectCustom(param.getProductComponents(), Map.class); if (nestParameters == null) { return BaseResult.fail("product components can't be null."); } Long payPeriod = ((Number) nestParameters.remove(PAY_PERIOD)).longValue(); PayPeriodUnit payPeriodUnit = PayPeriodUnit.valueOf(String.valueOf(nestParameters.remove(PAY_PERIOD_UNIT)));
Object serviceInstanceIdObj = nestParameters.remove(ComputeNestConstants.SERVICE_INSTANCE_ID);
2
2023-11-01 08:19:34+00:00
16k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/fragments/home/HomeFragment.java
[ { "identifier": "ClassAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/group/ClassAdapter.java", "snippet": "public class ClassAdapter extends RecyclerView.Adapter<ClassAdapter.ClassViewHolder> {\n private final Context context;\n private final ArrayList<Group> classes;\n\n pub...
import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.daominh.quickmem.adapter.group.ClassAdapter; import com.daominh.quickmem.adapter.folder.FolderAdapter; import com.daominh.quickmem.adapter.flashcard.SetsAdapter; import com.daominh.quickmem.data.dao.FlashCardDAO; import com.daominh.quickmem.data.dao.FolderDAO; import com.daominh.quickmem.data.dao.GroupDAO; import com.daominh.quickmem.data.model.FlashCard; import com.daominh.quickmem.data.model.Folder; import com.daominh.quickmem.data.model.Group; import com.daominh.quickmem.databinding.FragmentHomeBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.create.CreateSetActivity; import com.daominh.quickmem.ui.activities.search.ViewSearchActivity; import org.jetbrains.annotations.NotNull; import java.util.ArrayList;
14,016
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter; private ArrayList<FlashCard> flashCards; private ArrayList<Folder> folders;
package com.daominh.quickmem.ui.fragments.home; public class HomeFragment extends Fragment { private FragmentHomeBinding binding; private UserSharePreferences userSharePreferences; private SetsAdapter setsAdapter; private FolderAdapter folderAdapter; private ClassAdapter classAdapter; private ArrayList<FlashCard> flashCards; private ArrayList<Folder> folders;
private ArrayList<Group> classes;
8
2023-11-07 16:56:39+00:00
16k
estkme-group/InfiLPA
core/src/main/java/com/infineon/esim/lpa/core/dtos/EuiccInfo.java
[ { "identifier": "PprIds", "path": "messages/src/main/java/com/gsma/sgp/messages/rspdefinitions/PprIds.java", "snippet": "public class PprIds extends BerBitString {\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic PprIds() {\n\t}\n\n\tpublic PprIds(byte[] code) {\n\t\tsuper(code);\n\t}\n...
import java.util.ArrayList; import java.util.List; import com.beanit.jasn1.ber.types.BerOctetString; import com.gsma.sgp.messages.rspdefinitions.PprIds; import com.gsma.sgp.messages.pkix1implicit88.SubjectKeyIdentifier; import com.gsma.sgp.messages.rspdefinitions.EUICCInfo2; import com.gsma.sgp.messages.rspdefinitions.VersionType; import com.infineon.esim.util.Log;
11,147
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.dtos; public class EuiccInfo { private static final String TAG = EuiccInfo.class.getName(); private String eid; private final String profileVersion; private final String svn; private final String euiccFirmwareVer; private final String globalplatformVersion; private final String sasAcreditationNumber; private final List<String> pkiIdsForSign; private final List<String> pkiIdsForVerify; private final PprIds forbiddenProfilePolicyRules; private final BerOctetString extCardResource; public EuiccInfo(EUICCInfo2 euiccInfo2) { this(null, euiccInfo2); } public EuiccInfo(String eid, EUICCInfo2 euiccInfo2) { this.eid = eid; this.profileVersion = versionTypeToString(euiccInfo2.getProfileVersion()); this.svn = versionTypeToString(euiccInfo2.getSvn()); this.euiccFirmwareVer = versionTypeToString(euiccInfo2.getEuiccFirmwareVer()); this.globalplatformVersion = versionTypeToString(euiccInfo2.getGlobalplatformVersion()); this.sasAcreditationNumber = euiccInfo2.getSasAcreditationNumber().toString(); this.pkiIdsForSign = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForSigning()); this.pkiIdsForVerify = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForVerification()); this.forbiddenProfilePolicyRules = euiccInfo2.getForbiddenProfilePolicyRules(); this.extCardResource = euiccInfo2.getExtCardResource(); } public void setEid(String eid) { this.eid = eid; } public String getEid() { return eid; } public String getProfileVersion() { return profileVersion; } public String getSvn() { return svn; } public String getEuiccFirmwareVer() { return euiccFirmwareVer; } public String getGlobalplatformVersion() { return globalplatformVersion; } public String getSasAcreditationNumber() { return sasAcreditationNumber; } public List<String> getPkiIdsForSign() { return pkiIdsForSign; } public List<String> getPkiIdsForVerify() { return pkiIdsForVerify; } public String getPkiIdsForSignAsString(){ StringBuilder sb = new StringBuilder(); if (!pkiIdsForSign.isEmpty()) { for(String pkiId : pkiIdsForSign) { sb.append(pkiId); sb.append("\n"); } } else { return "Not Found"; } return sb.subSequence(0, sb.length() - 1).toString(); } public String getPkiIdsForVerifyAsString(){ StringBuilder sb = new StringBuilder(); if (!pkiIdsForVerify.isEmpty()) { for(String pkiId : pkiIdsForVerify) { sb.append(pkiId); sb.append("\n"); } } else { return "Not Found"; } return sb.subSequence(0, sb.length() - 1).toString(); } public String getForbiddenProfilePolicyRules() { return forbiddenProfilePolicyRules.toString(); } public String getExtCardResource() { return extCardResource.toString(); } private static String versionTypeToString(VersionType versionType) { if(versionType != null) { String vts = versionType.toString();
/* * THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON * TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR, * STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * * THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES * RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER * REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR * THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME. * * INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR * CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR * ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR * PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE * DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION * WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR * PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON * WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE. * * (C)Copyright INFINEON TECHNOLOGIES All rights reserved */ package com.infineon.esim.lpa.core.dtos; public class EuiccInfo { private static final String TAG = EuiccInfo.class.getName(); private String eid; private final String profileVersion; private final String svn; private final String euiccFirmwareVer; private final String globalplatformVersion; private final String sasAcreditationNumber; private final List<String> pkiIdsForSign; private final List<String> pkiIdsForVerify; private final PprIds forbiddenProfilePolicyRules; private final BerOctetString extCardResource; public EuiccInfo(EUICCInfo2 euiccInfo2) { this(null, euiccInfo2); } public EuiccInfo(String eid, EUICCInfo2 euiccInfo2) { this.eid = eid; this.profileVersion = versionTypeToString(euiccInfo2.getProfileVersion()); this.svn = versionTypeToString(euiccInfo2.getSvn()); this.euiccFirmwareVer = versionTypeToString(euiccInfo2.getEuiccFirmwareVer()); this.globalplatformVersion = versionTypeToString(euiccInfo2.getGlobalplatformVersion()); this.sasAcreditationNumber = euiccInfo2.getSasAcreditationNumber().toString(); this.pkiIdsForSign = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForSigning()); this.pkiIdsForVerify = euiccPkiIdList(euiccInfo2.getEuiccCiPKIdListForVerification()); this.forbiddenProfilePolicyRules = euiccInfo2.getForbiddenProfilePolicyRules(); this.extCardResource = euiccInfo2.getExtCardResource(); } public void setEid(String eid) { this.eid = eid; } public String getEid() { return eid; } public String getProfileVersion() { return profileVersion; } public String getSvn() { return svn; } public String getEuiccFirmwareVer() { return euiccFirmwareVer; } public String getGlobalplatformVersion() { return globalplatformVersion; } public String getSasAcreditationNumber() { return sasAcreditationNumber; } public List<String> getPkiIdsForSign() { return pkiIdsForSign; } public List<String> getPkiIdsForVerify() { return pkiIdsForVerify; } public String getPkiIdsForSignAsString(){ StringBuilder sb = new StringBuilder(); if (!pkiIdsForSign.isEmpty()) { for(String pkiId : pkiIdsForSign) { sb.append(pkiId); sb.append("\n"); } } else { return "Not Found"; } return sb.subSequence(0, sb.length() - 1).toString(); } public String getPkiIdsForVerifyAsString(){ StringBuilder sb = new StringBuilder(); if (!pkiIdsForVerify.isEmpty()) { for(String pkiId : pkiIdsForVerify) { sb.append(pkiId); sb.append("\n"); } } else { return "Not Found"; } return sb.subSequence(0, sb.length() - 1).toString(); } public String getForbiddenProfilePolicyRules() { return forbiddenProfilePolicyRules.toString(); } public String getExtCardResource() { return extCardResource.toString(); } private static String versionTypeToString(VersionType versionType) { if(versionType != null) { String vts = versionType.toString();
Log.debug(TAG, "Raw version number: \"" + vts + "\"." );
4
2023-11-06 02:41:13+00:00
16k
CxyJerry/pilipala
src/main/java/com/jerry/pilipala/domain/vod/service/impl/VodServiceImpl.java
[ { "identifier": "UserInfoBO", "path": "src/main/java/com/jerry/pilipala/application/bo/UserInfoBO.java", "snippet": "@Data\n@Accessors(chain = true)\npublic class UserInfoBO {\n private String uid;\n private String roleId;\n private List<String> permissionIdList;\n}" }, { "identifier": ...
import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Snowflake; import cn.hutool.core.util.IdUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.jerry.pilipala.application.bo.UserInfoBO; import com.jerry.pilipala.application.dto.PreUploadDTO; import com.jerry.pilipala.application.dto.VideoPostDTO; import com.jerry.pilipala.application.vo.bvod.BVodVO; import com.jerry.pilipala.application.vo.bvod.PreviewBVodVO; import com.jerry.pilipala.application.vo.user.PreviewUserVO; import com.jerry.pilipala.application.vo.vod.*; import com.jerry.pilipala.domain.common.template.MessageTrigger; import com.jerry.pilipala.domain.message.service.MessageService; import com.jerry.pilipala.domain.user.entity.mongo.Permission; import com.jerry.pilipala.domain.user.entity.mongo.User; import com.jerry.pilipala.domain.user.entity.neo4j.UserEntity; import com.jerry.pilipala.domain.user.repository.UserEntityRepository; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.Quality; import com.jerry.pilipala.domain.vod.entity.mongo.distribute.VodDistributeInfo; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionEvent; import com.jerry.pilipala.domain.vod.entity.mongo.event.VodHandleActionRecord; import com.jerry.pilipala.domain.vod.entity.mongo.statitics.VodStatistics; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.Thumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.thumbnails.VodThumbnails; import com.jerry.pilipala.domain.vod.entity.mongo.vod.BVod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.Vod; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodInfo; import com.jerry.pilipala.domain.vod.entity.mongo.vod.VodProfiles; import com.jerry.pilipala.domain.vod.entity.neo4j.VodInfoEntity; import com.jerry.pilipala.domain.vod.repository.VodInfoRepository; import com.jerry.pilipala.domain.vod.service.FileService; import com.jerry.pilipala.domain.vod.service.VodService; import com.jerry.pilipala.domain.vod.service.media.UGCSchema; import com.jerry.pilipala.domain.vod.service.media.encoder.Encoder; import com.jerry.pilipala.domain.vod.service.media.profiles.Profile; import com.jerry.pilipala.infrastructure.common.errors.BusinessException; import com.jerry.pilipala.infrastructure.common.response.StandardResponse; import com.jerry.pilipala.infrastructure.enums.ActionStatusEnum; import com.jerry.pilipala.infrastructure.enums.Qn; import com.jerry.pilipala.infrastructure.enums.VodHandleActionEnum; import com.jerry.pilipala.infrastructure.enums.VodStatusEnum; import com.jerry.pilipala.infrastructure.enums.message.TemplateNameEnum; import com.jerry.pilipala.infrastructure.enums.redis.VodCacheKeyEnum; import com.jerry.pilipala.infrastructure.enums.video.Resolution; import com.jerry.pilipala.infrastructure.utils.JsonHelper; import com.jerry.pilipala.infrastructure.utils.Page; import com.jerry.pilipala.infrastructure.utils.SecurityTool; import lombok.extern.slf4j.Slf4j; import net.bramp.ffmpeg.FFmpeg; import net.bramp.ffmpeg.FFmpegExecutor; import net.bramp.ffmpeg.FFprobe; import net.bramp.ffmpeg.builder.FFmpegBuilder; import net.bramp.ffmpeg.builder.FFmpegOutputBuilder; import net.bramp.ffmpeg.probe.FFmpegFormat; import net.bramp.ffmpeg.probe.FFmpegProbeResult; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.InputStreamResource; import org.springframework.core.task.TaskExecutor; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.IOException; import java.time.Instant; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
13,765
} /** * 预上传稿件 * * @param preUploadDTO 稿件素材信息 * @return 预上传结果 */ @Override @Transactional(rollbackFor = Exception.class, value = "multiTransactionManager") public PreUploadVO preUpload(PreUploadDTO preUploadDTO) { String bvId = preUploadDTO.getBvId(); String filename = genFilename(preUploadDTO); Long cid = snowflake.nextId(); // 触发初始化开始 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.init, cid)); BVod bVod; if (StringUtils.isNotBlank(bvId)) { Query query = new Query(Criteria.where("_id").is(bvId)); bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("bvid 不存在", StandardResponse.ERROR); } } else { bvId = "BV" + UUID.randomUUID().toString().replace("-", "").toUpperCase(); bVod = new BVod() .setBvId(bvId) .setUid((String) StpUtil.getLoginId()) .setCidList(new ArrayList<>()); } mongoTemplate.save(bVod); Vod vod = new Vod() .setCid(cid) .setBvId(bvId) .setFilename(filename) .setContainer(preUploadDTO.getContainer()) .setVideo(preUploadDTO.getVideo()) .setAudio(preUploadDTO.getAudio()) .setExtra(preUploadDTO.getExtra()); mongoTemplate.save(vod); // 触发初始化结束 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.finished, cid)); return new PreUploadVO().setBvId(bvId).setCid(cid).setFilename(filename); } /** * 投递稿件 * * @param videoPostDTO 稿件信息 */ public void post(VideoPostDTO videoPostDTO) { Query query = new Query(Criteria.where("_id").is(videoPostDTO.getBvId())); BVod bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("稿件不存在,请重新投稿", StandardResponse.ERROR); } bVod.getCidList().add(videoPostDTO.getCid()); bVod.setReady(true); mongoTemplate.save(bVod); Vod vod = mongoTemplate.findById(videoPostDTO.getCid(), Vod.class); if (Objects.isNull(vod)) { throw BusinessException.businessError("稿件不存在"); } VodInfo vodInfo = new VodInfo(); vodInfo.setBvId(videoPostDTO.getBvId()) .setCid(videoPostDTO.getCid()) .setUid((String) StpUtil.getLoginId()) .setStatus(VodStatusEnum.HANDING) .setCoverUrl(videoPostDTO.getCoverUrl()) .setTitle(videoPostDTO.getTitle()) .setGcType(videoPostDTO.getGcType()) .setPartition(videoPostDTO.getPartition()) .setSubPartition(videoPostDTO.getSubPartition()) .setLabels(videoPostDTO.getLabels()) .setDesc(videoPostDTO.getDesc()) .setDuration(vod.getContainer().getDuration()) .setMtime(System.currentTimeMillis()); mongoTemplate.save(vodInfo); VodHandleActionEvent actionEvent = new VodHandleActionEvent( VodHandleActionEnum.SUBMIT, ActionStatusEnum.finished, videoPostDTO.getCid() ); // 触发提交结束 applicationEventPublisher.publishEvent(actionEvent); // 推送站内信 User author = mongoTemplate.findById(new ObjectId(bVod.getUid()), User.class); if (Objects.isNull(author)) { log.error("消息推送失败,稿件作者信息异常."); return; } Map<String, String> variables = new HashMap<>(); variables.put("username", author.getNickname()); variables.put("title", vodInfo.getTitle()); variables.put("bvid", vodInfo.getBvId()); variables.put("cid", vodInfo.getCid().toString()); messageTrigger.triggerSystemMessage( TemplateNameEnum.POST_VOD_NOTIFY, bVod.getUid(), variables ); } /** * 规划需要转出的视频规格 * * @param cid 稿件唯一ID * @param vod 稿件素材信息 * @return 视频规格列表 * @throws JsonProcessingException 打印视频规格信息时可能产生的序列化异常 */ @Override public List<Profile> schema(Long cid, Vod vod) throws JsonProcessingException { Query query = new Query(Criteria.where("_id").is(cid));
package com.jerry.pilipala.domain.vod.service.impl; @Slf4j @Service public class VodServiceImpl implements VodService { private final FFprobe fFprobe; private final FFmpeg fFmpeg; private final MongoTemplate mongoTemplate; private final RedisTemplate<String, Object> redisTemplate; private final Snowflake snowflake = IdUtil.getSnowflake(); private final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private final ApplicationEventPublisher applicationEventPublisher; private final UGCSchema ugcSchema; private final TaskExecutor taskExecutor; private final VodInfoRepository vodInfoRepository; private final UserEntityRepository userEntityRepository; private final JsonHelper jsonHelper; private final FileService fileService; private final MessageTrigger messageTrigger; public VodServiceImpl(MongoTemplate mongoTemplate, RedisTemplate<String, Object> redisTemplate, ApplicationEventPublisher applicationEventPublisher, UGCSchema ugcSchema, @Qualifier("asyncServiceExecutor") TaskExecutor taskExecutor, VodInfoRepository vodInfoRepository, UserEntityRepository userEntityRepository, MessageService messageService, JsonHelper jsonHelper, FileService fileService, MessageTrigger messageTrigger1) { this.mongoTemplate = mongoTemplate; this.redisTemplate = redisTemplate; this.applicationEventPublisher = applicationEventPublisher; this.ugcSchema = ugcSchema; this.taskExecutor = taskExecutor; this.vodInfoRepository = vodInfoRepository; this.userEntityRepository = userEntityRepository; this.jsonHelper = jsonHelper; this.fileService = fileService; this.messageTrigger = messageTrigger1; } { try { fFprobe = new FFprobe(); fFmpeg = new FFmpeg(); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void ffprobe(String filepath) { try { FFmpegProbeResult probeResult = fFprobe.probe(filepath); FFmpegFormat format = probeResult.getFormat(); System.out.println(probeResult.getStreams()); } catch (IOException e) { throw new RuntimeException(e); } } /** * 生成全局唯一的 filename * * @param preUploadDTO 预上传稿件素材信息 * @return filename */ @Override public String genFilename(PreUploadDTO preUploadDTO) { try { String json = jsonHelper.as(preUploadDTO); String now = DATE_TIME_FORMATTER.format(LocalDateTime.now()); String md5 = SecurityTool.getMd5(json); return "f%s%s".formatted(now, md5); } catch (Exception e) { throw new BusinessException("文件名生成失败", StandardResponse.ERROR); } } /** * 预上传稿件 * * @param preUploadDTO 稿件素材信息 * @return 预上传结果 */ @Override @Transactional(rollbackFor = Exception.class, value = "multiTransactionManager") public PreUploadVO preUpload(PreUploadDTO preUploadDTO) { String bvId = preUploadDTO.getBvId(); String filename = genFilename(preUploadDTO); Long cid = snowflake.nextId(); // 触发初始化开始 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.init, cid)); BVod bVod; if (StringUtils.isNotBlank(bvId)) { Query query = new Query(Criteria.where("_id").is(bvId)); bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("bvid 不存在", StandardResponse.ERROR); } } else { bvId = "BV" + UUID.randomUUID().toString().replace("-", "").toUpperCase(); bVod = new BVod() .setBvId(bvId) .setUid((String) StpUtil.getLoginId()) .setCidList(new ArrayList<>()); } mongoTemplate.save(bVod); Vod vod = new Vod() .setCid(cid) .setBvId(bvId) .setFilename(filename) .setContainer(preUploadDTO.getContainer()) .setVideo(preUploadDTO.getVideo()) .setAudio(preUploadDTO.getAudio()) .setExtra(preUploadDTO.getExtra()); mongoTemplate.save(vod); // 触发初始化结束 applicationEventPublisher.publishEvent(new VodHandleActionEvent(VodHandleActionEnum.PRE_UPLOAD, ActionStatusEnum.finished, cid)); return new PreUploadVO().setBvId(bvId).setCid(cid).setFilename(filename); } /** * 投递稿件 * * @param videoPostDTO 稿件信息 */ public void post(VideoPostDTO videoPostDTO) { Query query = new Query(Criteria.where("_id").is(videoPostDTO.getBvId())); BVod bVod = mongoTemplate.findOne(query, BVod.class); if (Objects.isNull(bVod)) { throw new BusinessException("稿件不存在,请重新投稿", StandardResponse.ERROR); } bVod.getCidList().add(videoPostDTO.getCid()); bVod.setReady(true); mongoTemplate.save(bVod); Vod vod = mongoTemplate.findById(videoPostDTO.getCid(), Vod.class); if (Objects.isNull(vod)) { throw BusinessException.businessError("稿件不存在"); } VodInfo vodInfo = new VodInfo(); vodInfo.setBvId(videoPostDTO.getBvId()) .setCid(videoPostDTO.getCid()) .setUid((String) StpUtil.getLoginId()) .setStatus(VodStatusEnum.HANDING) .setCoverUrl(videoPostDTO.getCoverUrl()) .setTitle(videoPostDTO.getTitle()) .setGcType(videoPostDTO.getGcType()) .setPartition(videoPostDTO.getPartition()) .setSubPartition(videoPostDTO.getSubPartition()) .setLabels(videoPostDTO.getLabels()) .setDesc(videoPostDTO.getDesc()) .setDuration(vod.getContainer().getDuration()) .setMtime(System.currentTimeMillis()); mongoTemplate.save(vodInfo); VodHandleActionEvent actionEvent = new VodHandleActionEvent( VodHandleActionEnum.SUBMIT, ActionStatusEnum.finished, videoPostDTO.getCid() ); // 触发提交结束 applicationEventPublisher.publishEvent(actionEvent); // 推送站内信 User author = mongoTemplate.findById(new ObjectId(bVod.getUid()), User.class); if (Objects.isNull(author)) { log.error("消息推送失败,稿件作者信息异常."); return; } Map<String, String> variables = new HashMap<>(); variables.put("username", author.getNickname()); variables.put("title", vodInfo.getTitle()); variables.put("bvid", vodInfo.getBvId()); variables.put("cid", vodInfo.getCid().toString()); messageTrigger.triggerSystemMessage( TemplateNameEnum.POST_VOD_NOTIFY, bVod.getUid(), variables ); } /** * 规划需要转出的视频规格 * * @param cid 稿件唯一ID * @param vod 稿件素材信息 * @return 视频规格列表 * @throws JsonProcessingException 打印视频规格信息时可能产生的序列化异常 */ @Override public List<Profile> schema(Long cid, Vod vod) throws JsonProcessingException { Query query = new Query(Criteria.where("_id").is(cid));
VodProfiles vodProfiles = mongoTemplate.findOne(query, VodProfiles.class);
22
2023-11-03 10:05:02+00:00
16k
giteecode/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
12,775
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired
private StatusDao statusDao;
7
2023-11-03 02:29:57+00:00
16k
Mau38/SparePartsFTC
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/ArmMecanumDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 30;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/roadRunner/d...
import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.roadRunner.drive.DriveConstants.kV; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.roadRunner.drive.StandardTrackingWheelLocalizer; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.roadRunner.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.roadRunner.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
11,786
package org.firstinspires.ftc.teamcode; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class ArmMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);
package org.firstinspires.ftc.teamcode; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class ArmMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double LATERAL_MULTIPLIER = 1; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH);
private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL);
0
2023-11-06 21:25:54+00:00
16k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/menu/impl/UnsoldItemsMenu.java
[ { "identifier": "Main", "path": "Core/src/main/java/org/by1337/bauction/Main.java", "snippet": "public final class Main extends JavaPlugin {\n private static Message message;\n private static Plugin instance;\n private static Config cfg;\n private static FileDataBase storage;\n private Co...
import org.bukkit.entity.Player; import org.by1337.api.chat.Placeholderable; import org.by1337.api.command.Command; import org.by1337.api.command.CommandException; import org.by1337.api.command.argument.ArgumentSetList; import org.by1337.api.command.argument.ArgumentString; import org.by1337.bauction.Main; import org.by1337.bauction.action.TakeUnsoldItemProcess; import org.by1337.bauction.auc.UnsoldItem; import org.by1337.bauction.auc.User; import org.by1337.bauction.lang.Lang; import org.by1337.bauction.menu.CustomItemStack; import org.by1337.bauction.menu.Menu; import org.by1337.bauction.menu.command.DefaultMenuCommand; import org.by1337.bauction.util.CUniqueName; import org.by1337.api.util.Pair; import org.by1337.bauction.util.UniqueName; import javax.annotation.Nullable; import java.util.*;
12,918
package org.by1337.bauction.menu.impl; public class UnsoldItemsMenu extends Menu { private int currentPage = 0; private int maxPage = 0; private final List<Integer> slots; private final Command<Pair<Menu, Player>> command; private final User user; public UnsoldItemsMenu(Player player, User user) { this(player, user, null); } public UnsoldItemsMenu(Player player, User user, @Nullable Menu backMenu) { super(Main.getCfg().getMenuManger().getUnsoldItems(), player, backMenu, user); this.user = user; slots = Main.getCfg().getMenuManger().getUnsoldItemsSlots(); command = new Command<Pair<Menu, Player>>("test") .addSubCommand(new Command<Pair<Menu, Player>>("[NEXT_PAGE]") .executor(((sender, args) -> { if (currentPage < maxPage - 1) { currentPage++; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[PREVIOUS_PAGE]") .executor(((sender, args) -> { if (currentPage > 0) { currentPage--; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[UPDATE]") .executor(((sender, args) -> { unsoldItems = null; generate0(); })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[TAKE_ITEM]") .argument(new ArgumentString<>("uuid")) .argument(new ArgumentSetList<>("fast", List.of("fast"))) .executor(((sender, args) -> { boolean fast = args.getOrDefault("fast", "").equals("fast"); String uuidS = (String) args.getOrThrow("uuid"); // UUID uuid = UUID.fromString(uuidS); UniqueName uuid = new CUniqueName(uuidS); UnsoldItem unsoldItem = unsoldItems.stream().filter(i -> i.getUniqueName().equals(uuid)).findFirst().orElse(null); if (unsoldItem == null) { Main.getMessage().sendMsg(player, Lang.getMessage("item_no_longer_exists")); unsoldItems = null; generate0(); return; } new TakeUnsoldItemProcess(unsoldItem, user, this, player, fast).process(); })) ) ;
package org.by1337.bauction.menu.impl; public class UnsoldItemsMenu extends Menu { private int currentPage = 0; private int maxPage = 0; private final List<Integer> slots; private final Command<Pair<Menu, Player>> command; private final User user; public UnsoldItemsMenu(Player player, User user) { this(player, user, null); } public UnsoldItemsMenu(Player player, User user, @Nullable Menu backMenu) { super(Main.getCfg().getMenuManger().getUnsoldItems(), player, backMenu, user); this.user = user; slots = Main.getCfg().getMenuManger().getUnsoldItemsSlots(); command = new Command<Pair<Menu, Player>>("test") .addSubCommand(new Command<Pair<Menu, Player>>("[NEXT_PAGE]") .executor(((sender, args) -> { if (currentPage < maxPage - 1) { currentPage++; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[PREVIOUS_PAGE]") .executor(((sender, args) -> { if (currentPage > 0) { currentPage--; generate0(); } })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[UPDATE]") .executor(((sender, args) -> { unsoldItems = null; generate0(); })) ) .addSubCommand(new Command<Pair<Menu, Player>>("[TAKE_ITEM]") .argument(new ArgumentString<>("uuid")) .argument(new ArgumentSetList<>("fast", List.of("fast"))) .executor(((sender, args) -> { boolean fast = args.getOrDefault("fast", "").equals("fast"); String uuidS = (String) args.getOrThrow("uuid"); // UUID uuid = UUID.fromString(uuidS); UniqueName uuid = new CUniqueName(uuidS); UnsoldItem unsoldItem = unsoldItems.stream().filter(i -> i.getUniqueName().equals(uuid)).findFirst().orElse(null); if (unsoldItem == null) { Main.getMessage().sendMsg(player, Lang.getMessage("item_no_longer_exists")); unsoldItems = null; generate0(); return; } new TakeUnsoldItemProcess(unsoldItem, user, this, player, fast).process(); })) ) ;
DefaultMenuCommand.command.getSubcommands().forEach((s, c) -> command.addSubCommand(c));
7
2023-11-08 18:25:18+00:00
16k
YufiriaMazenta/CrypticLib
nms/src/main/java/crypticlib/nms/item/ItemFactory.java
[ { "identifier": "CrypticLib", "path": "common/src/main/java/crypticlib/CrypticLib.java", "snippet": "public class CrypticLib {\n\n\n private static final CommandManager commandManager;\n private static final PermissionManager permissionManager;\n private static IPlatform platform;\n private ...
import crypticlib.CrypticLib; import crypticlib.function.TernaryFunction; import crypticlib.nms.item.v1_12_R1.V1_12_R1NbtItem; import crypticlib.nms.item.v1_13_R1.V1_13_R1NbtItem; import crypticlib.nms.item.v1_13_R2.V1_13_R2NbtItem; import crypticlib.nms.item.v1_14_R1.V1_14_R1NbtItem; import crypticlib.nms.item.v1_15_R1.V1_15_R1NbtItem; import crypticlib.nms.item.v1_16_R1.V1_16_R1NbtItem; import crypticlib.nms.item.v1_16_R2.V1_16_R2NbtItem; import crypticlib.nms.item.v1_16_R3.V1_16_R3NbtItem; import crypticlib.nms.item.v1_17_R1.V1_17_R1NbtItem; import crypticlib.nms.item.v1_18_R1.V1_18_R1NbtItem; import crypticlib.nms.item.v1_18_R2.V1_18_R2NbtItem; import crypticlib.nms.item.v1_19_R1.V1_19_R1NbtItem; import crypticlib.nms.item.v1_19_R2.V1_19_R2NbtItem; import crypticlib.nms.item.v1_19_R3.V1_19_R3NbtItem; import crypticlib.nms.item.v1_20_R1.V1_20_R1NbtItem; import crypticlib.nms.item.v1_20_R2.V1_20_R2NbtItem; import crypticlib.nms.item.v1_20_R3.V1_20_R3NbtItem; import crypticlib.nms.nbt.NbtFactory; import crypticlib.nms.nbt.NbtTagCompound; import crypticlib.util.MaterialUtil; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.BiFunction; import java.util.function.Function;
12,695
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1; private static final Map<String, BiFunction<Material, NbtTagCompound, NbtItem>> nbtItemProviderMap2; private static final Map<String, TernaryFunction<Material, NbtTagCompound, Integer, NbtItem>> nbtItemProviderMap3; static { nbtItemProviderMap1 = new ConcurrentHashMap<>(); nbtItemProviderMap2 = new ConcurrentHashMap<>(); nbtItemProviderMap3 = new ConcurrentHashMap<>(); regNbtItemProvider("v1_12_R1", V1_12_R1NbtItem::new, V1_12_R1NbtItem::new, V1_12_R1NbtItem::new); regNbtItemProvider("v1_13_R1", V1_13_R1NbtItem::new, V1_13_R1NbtItem::new, V1_13_R1NbtItem::new); regNbtItemProvider("v1_13_R2", V1_13_R2NbtItem::new, V1_13_R2NbtItem::new, V1_13_R2NbtItem::new); regNbtItemProvider("v1_14_R1", V1_14_R1NbtItem::new, V1_14_R1NbtItem::new, V1_14_R1NbtItem::new);
package crypticlib.nms.item; /** * CrypticLib的物品提供工厂 */ public class ItemFactory { private static final Map<String, Function<ItemStack, NbtItem>> nbtItemProviderMap1; private static final Map<String, BiFunction<Material, NbtTagCompound, NbtItem>> nbtItemProviderMap2; private static final Map<String, TernaryFunction<Material, NbtTagCompound, Integer, NbtItem>> nbtItemProviderMap3; static { nbtItemProviderMap1 = new ConcurrentHashMap<>(); nbtItemProviderMap2 = new ConcurrentHashMap<>(); nbtItemProviderMap3 = new ConcurrentHashMap<>(); regNbtItemProvider("v1_12_R1", V1_12_R1NbtItem::new, V1_12_R1NbtItem::new, V1_12_R1NbtItem::new); regNbtItemProvider("v1_13_R1", V1_13_R1NbtItem::new, V1_13_R1NbtItem::new, V1_13_R1NbtItem::new); regNbtItemProvider("v1_13_R2", V1_13_R2NbtItem::new, V1_13_R2NbtItem::new, V1_13_R2NbtItem::new); regNbtItemProvider("v1_14_R1", V1_14_R1NbtItem::new, V1_14_R1NbtItem::new, V1_14_R1NbtItem::new);
regNbtItemProvider("v1_15_R1", V1_15_R1NbtItem::new, V1_15_R1NbtItem::new, V1_15_R1NbtItem::new);
6
2023-11-07 12:39:20+00:00
16k
ynwynw/oaSystemPublic
src/main/java/cn/gson/oasys/controller/inform/InformManageController.java
[ { "identifier": "BindingResultVOUtil", "path": "src/main/java/cn/gson/oasys/common/formValid/BindingResultVOUtil.java", "snippet": "public class BindingResultVOUtil {\n /**\n * 表单验证,返回形式ResultVO\n *\n * @param br\n * @return\n */\n public static ResultVO hasErrors(BindingResult...
import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttribute; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import cn.gson.oasys.common.formValid.BindingResultVOUtil; import cn.gson.oasys.common.formValid.MapToList; import cn.gson.oasys.common.formValid.ResultEnum; import cn.gson.oasys.common.formValid.ResultVO; import cn.gson.oasys.mappers.NoticeMapper; import cn.gson.oasys.model.dao.informdao.InformDao; import cn.gson.oasys.model.dao.informdao.InformRelationDao; import cn.gson.oasys.model.dao.system.StatusDao; import cn.gson.oasys.model.dao.system.TypeDao; import cn.gson.oasys.model.dao.user.DeptDao; import cn.gson.oasys.model.dao.user.UserDao; import cn.gson.oasys.model.entity.notice.NoticeUserRelation; import cn.gson.oasys.model.entity.notice.NoticeVO; import cn.gson.oasys.model.entity.notice.NoticesList; import cn.gson.oasys.model.entity.system.SystemMenu; import cn.gson.oasys.model.entity.system.SystemStatusList; import cn.gson.oasys.model.entity.system.SystemTypeList; import cn.gson.oasys.model.entity.user.User; import cn.gson.oasys.services.inform.InformRelationService; import cn.gson.oasys.services.inform.InformService;
12,811
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired
package cn.gson.oasys.controller.inform; @Controller @RequestMapping("/") public class InformManageController { Logger log = LoggerFactory.getLogger(getClass()); @Autowired private StatusDao statusDao; @Autowired private TypeDao typeDao; @Autowired private InformDao informDao; @Autowired private InformService informService; @Autowired
private UserDao uDao;
10
2023-11-03 02:08:22+00:00
16k
firstdarkdev/modfusioner
src/main/java/com/hypherionmc/modfusioner/task/JarFuseTask.java
[ { "identifier": "Constants", "path": "src/main/java/com/hypherionmc/modfusioner/Constants.java", "snippet": "public class Constants {\n\n public static final String TASK_GROUP = \"modfusioner\";\n public static final String TASK_NAME = \"fusejars\";\n public static final String EXTENSION_NAME =...
import com.hypherionmc.modfusioner.Constants; import com.hypherionmc.modfusioner.actions.JarMergeAction; import com.hypherionmc.modfusioner.plugin.FusionerExtension; import com.hypherionmc.modfusioner.plugin.ModFusionerPlugin; import com.hypherionmc.modfusioner.utils.FileChecks; import com.hypherionmc.modfusioner.utils.FileTools; import org.apache.commons.io.FileUtils; import org.gradle.api.Project; import org.gradle.api.internal.file.copy.CopyAction; import org.gradle.api.tasks.WorkResults; import org.gradle.jvm.tasks.Jar; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.modFusionerExtension; import static com.hypherionmc.modfusioner.plugin.ModFusionerPlugin.rootProject;
14,332
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis(); ModFusionerPlugin.logger.lifecycle("Start Fusing Jars"); // Get settings from extension FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration(); FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration(); FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration(); List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations(); // Try to resolve the projects specific in the extension config Project forgeProject = null; Project fabricProject = null; Project quiltProject = null; Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>(); List<Boolean> validation = new ArrayList<>(); if (forgeConfiguration != null) { try { forgeProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(forgeConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (fabricConfiguration != null) { try { fabricProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(fabricConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (quiltConfiguration != null) { try { quiltProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(quiltConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (customConfigurations != null) { for (FusionerExtension.CustomConfiguration customSettings : customConfigurations) { try { customProjects.put(rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equals(customSettings.getProjectName())).findFirst().get(), customSettings); validation.add(true); } catch (NoSuchElementException ignored) { } } } // Check that at least 2 projects are defined if (validation.size() < 2) { if (validation.size() == 1) ModFusionerPlugin.logger.error("Only one project was found. Skipping fusejars task."); if (validation.size() == 0) ModFusionerPlugin.logger.error("No projects were found. Skipping fusejars task."); return; } validation.clear(); // Try to automatically determine the input jar from the projects File forgeJar = null; File fabricJar = null; File quiltJar = null; Map<FusionerExtension.CustomConfiguration, File> customJars = new HashMap<>(); if (forgeProject != null && forgeConfiguration != null) { forgeJar = getInputFile(forgeConfiguration.getInputFile(), forgeConfiguration.getInputTaskName(), forgeProject); } if (fabricProject != null && fabricConfiguration != null) { fabricJar = getInputFile(fabricConfiguration.getInputFile(), fabricConfiguration.getInputTaskName(), fabricProject); } if (quiltProject != null && quiltConfiguration != null) { quiltJar = getInputFile(quiltConfiguration.getInputFile(), quiltConfiguration.getInputTaskName(), quiltProject); } for (Map.Entry<Project, FusionerExtension.CustomConfiguration> entry : customProjects.entrySet()) { File f = getInputFile(entry.getValue().getInputFile(), entry.getValue().getInputTaskName(), entry.getKey()); if (f != null) customJars.put(entry.getValue(), f); } // Set up the final output jar if (mergedJar.exists()) FileUtils.forceDelete(mergedJar); if (!mergedJar.getParentFile().exists()) mergedJar.getParentFile().mkdirs(); // Set up the jar merge action
/* * This file is part of ModFusioner, licensed under the GNU Lesser General Public License v2.1. * * This project is based on, and contains code from https://github.com/PacifistMC/Forgix, licensed under the same license. * See their license here: https://github.com/PacifistMC/Forgix/blob/main/LICENSE * * Copyright HypherionSA and Contributors * Forgix Code Copyright by their contributors and Ran-Mewo */ package com.hypherionmc.modfusioner.task; /** * @author HypherionSA * The main task of the plugin */ public class JarFuseTask extends Jar { // Fixed values private final File mergedJar; private static final AtomicBoolean hasRun = new AtomicBoolean(false); public JarFuseTask() { // Set task default values from extension getArchiveBaseName().set(modFusionerExtension.getMergedJarName()); getArchiveVersion().set(modFusionerExtension.getJarVersion()); getDestinationDirectory().set(getProject().file(modFusionerExtension.getOutputDirectory())); // We don't allow custom input files, when the user defines their own task getInputs().files(); // Only allow the task to run once per cycle getOutputs().upToDateWhen(spec -> hasRun.get()); // Set output file mergedJar = new File(getDestinationDirectory().get().getAsFile(), getArchiveFileName().get()); getOutputs().file(mergedJar); } /** * Main task logic * @throws IOException - Thrown when an IO error occurs */ void fuseJars() throws IOException { long time = System.currentTimeMillis(); ModFusionerPlugin.logger.lifecycle("Start Fusing Jars"); // Get settings from extension FusionerExtension.ForgeConfiguration forgeConfiguration = modFusionerExtension.getForgeConfiguration(); FusionerExtension.FabricConfiguration fabricConfiguration = modFusionerExtension.getFabricConfiguration(); FusionerExtension.QuiltConfiguration quiltConfiguration = modFusionerExtension.getQuiltConfiguration(); List<FusionerExtension.CustomConfiguration> customConfigurations = modFusionerExtension.getCustomConfigurations(); // Try to resolve the projects specific in the extension config Project forgeProject = null; Project fabricProject = null; Project quiltProject = null; Map<Project, FusionerExtension.CustomConfiguration> customProjects = new HashMap<>(); List<Boolean> validation = new ArrayList<>(); if (forgeConfiguration != null) { try { forgeProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(forgeConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (fabricConfiguration != null) { try { fabricProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(fabricConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (quiltConfiguration != null) { try { quiltProject = rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equalsIgnoreCase(quiltConfiguration.getProjectName())).findFirst().get(); validation.add(true); } catch (NoSuchElementException ignored) { } } if (customConfigurations != null) { for (FusionerExtension.CustomConfiguration customSettings : customConfigurations) { try { customProjects.put(rootProject.getAllprojects().stream().filter(p -> !p.getName().equals(rootProject.getName())).filter(p -> p.getName().equals(customSettings.getProjectName())).findFirst().get(), customSettings); validation.add(true); } catch (NoSuchElementException ignored) { } } } // Check that at least 2 projects are defined if (validation.size() < 2) { if (validation.size() == 1) ModFusionerPlugin.logger.error("Only one project was found. Skipping fusejars task."); if (validation.size() == 0) ModFusionerPlugin.logger.error("No projects were found. Skipping fusejars task."); return; } validation.clear(); // Try to automatically determine the input jar from the projects File forgeJar = null; File fabricJar = null; File quiltJar = null; Map<FusionerExtension.CustomConfiguration, File> customJars = new HashMap<>(); if (forgeProject != null && forgeConfiguration != null) { forgeJar = getInputFile(forgeConfiguration.getInputFile(), forgeConfiguration.getInputTaskName(), forgeProject); } if (fabricProject != null && fabricConfiguration != null) { fabricJar = getInputFile(fabricConfiguration.getInputFile(), fabricConfiguration.getInputTaskName(), fabricProject); } if (quiltProject != null && quiltConfiguration != null) { quiltJar = getInputFile(quiltConfiguration.getInputFile(), quiltConfiguration.getInputTaskName(), quiltProject); } for (Map.Entry<Project, FusionerExtension.CustomConfiguration> entry : customProjects.entrySet()) { File f = getInputFile(entry.getValue().getInputFile(), entry.getValue().getInputTaskName(), entry.getKey()); if (f != null) customJars.put(entry.getValue(), f); } // Set up the final output jar if (mergedJar.exists()) FileUtils.forceDelete(mergedJar); if (!mergedJar.getParentFile().exists()) mergedJar.getParentFile().mkdirs(); // Set up the jar merge action
JarMergeAction mergeAction = JarMergeAction.of(
1
2023-11-03 23:19:08+00:00
16k
FTC-ORBIT/14872-2024-CenterStage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleMecanumDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<SequenceSegment> se...
import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.drive.MecanumDrive; import com.acmerobotics.roadrunner.followers.HolonomicPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MecanumVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV;
10,876
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) {
package org.firstinspires.ftc.teamcode.drive; /* * Simple mecanum drive hardware implementation for REV hardware. */ @Config public class SampleMecanumDrive extends MecanumDrive { public static PIDCoefficients TRANSLATIONAL_PID = new PIDCoefficients(7, 0, 2); public static PIDCoefficients HEADING_PID = new PIDCoefficients(5, 0, 1); public static double LATERAL_MULTIPLIER = 1.7; public static double VX_WEIGHT = 1; public static double VY_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint ACCEL_CONSTRAINT = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private IMU imu; private VoltageSensor batteryVoltageSensor; private List<Integer> lastEncPositions = new ArrayList<>(); private List<Integer> lastEncVels = new ArrayList<>(); public SampleMecanumDrive(HardwareMap hardwareMap) {
super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER);
14
2023-11-03 13:32:48+00:00
16k
beminder/BeautyMinder
java/src/test/java/app/beautyminder/controller/elasticsearch/DataViewApiControllerTest.java
[ { "identifier": "TokenProvider", "path": "java/src/main/java/app/beautyminder/config/jwt/TokenProvider.java", "snippet": "@Slf4j\n@RequiredArgsConstructor\n@Service\npublic class TokenProvider {\n\n private final JwtProperties jwtProperties;\n private final UserRepository userRepository;\n\n pu...
import app.beautyminder.config.jwt.TokenProvider; import app.beautyminder.domain.User; import app.beautyminder.dto.CosmeticMetricData; import app.beautyminder.dto.user.AddUserRequest; import app.beautyminder.service.auth.UserService; import app.beautyminder.service.cosmetic.CosmeticRankService; import app.beautyminder.service.cosmetic.CosmeticSearchService; import app.beautyminder.service.cosmetic.ReviewSearchService; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.time.Duration; import java.util.List; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
11,729
package app.beautyminder.controller.elasticsearch; @Slf4j @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ActiveProfiles({"awsBasic", "test"}) public class DataViewApiControllerTest { private static final Duration ACCESS_TOKEN_DURATION = Duration.ofMinutes(3); private static final String TEST_ADMIN_EMAIL = "dataviewadmin@test.com"; private static final String TEST_ADMIN_PASSWORD = "test"; @Autowired protected MockMvc mockMvc; @MockBean private ReviewSearchService reviewSearchService; @MockBean private CosmeticRankService cosmeticRankService; @MockBean private CosmeticSearchService cosmeticSearchService; @Autowired private WebApplicationContext context; @Autowired private UserService userService; @Autowired private TokenProvider tokenProvider; private String accessToken; private String userId; @BeforeEach public void mockMvcSetUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @BeforeAll public void initialize() { AddUserRequest addUserRequest = new AddUserRequest(); addUserRequest.setEmail(TEST_ADMIN_EMAIL); addUserRequest.setPassword(TEST_ADMIN_PASSWORD); User user = userService.saveAdmin(addUserRequest); userId = user.getId(); accessToken = tokenProvider.generateToken(user, ACCESS_TOKEN_DURATION); } @Test public void testGet_ReviewAnalyze() throws Exception { String expectedString = "Hello"; when(reviewSearchService.analyzeText(anyString())).thenReturn(expectedString); mockMvc.perform(get("/data-view/review/analyze?text=" + expectedString) .header("Authorization", "Bearer " + accessToken)) .andExpect(status().isOk()); } @Test public void testGet_CosmeticData() throws Exception { String expectedString = "Cosmetic"; when(cosmeticSearchService.viewCosmeticsData()).thenReturn(expectedString); mockMvc.perform(get("/data-view/cosmetics") .header("Authorization", "Bearer " + accessToken)) .andExpect(status().isOk()); } @Test public void testGet_CosmeticMetricData() throws Exception { String expectedString = "CosmeticMetric"; when(cosmeticSearchService.viewCosmeticMetricsData()).thenReturn(expectedString); mockMvc.perform(get("/data-view/cosmetic-metrics") .header("Authorization", "Bearer " + accessToken)) .andExpect(status().isOk()); } @Test public void testGet_CosmeticCounts() throws Exception {
package app.beautyminder.controller.elasticsearch; @Slf4j @SpringBootTest @AutoConfigureMockMvc @TestMethodOrder(MethodOrderer.OrderAnnotation.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ActiveProfiles({"awsBasic", "test"}) public class DataViewApiControllerTest { private static final Duration ACCESS_TOKEN_DURATION = Duration.ofMinutes(3); private static final String TEST_ADMIN_EMAIL = "dataviewadmin@test.com"; private static final String TEST_ADMIN_PASSWORD = "test"; @Autowired protected MockMvc mockMvc; @MockBean private ReviewSearchService reviewSearchService; @MockBean private CosmeticRankService cosmeticRankService; @MockBean private CosmeticSearchService cosmeticSearchService; @Autowired private WebApplicationContext context; @Autowired private UserService userService; @Autowired private TokenProvider tokenProvider; private String accessToken; private String userId; @BeforeEach public void mockMvcSetUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(context).apply(springSecurity()).build(); } @BeforeAll public void initialize() { AddUserRequest addUserRequest = new AddUserRequest(); addUserRequest.setEmail(TEST_ADMIN_EMAIL); addUserRequest.setPassword(TEST_ADMIN_PASSWORD); User user = userService.saveAdmin(addUserRequest); userId = user.getId(); accessToken = tokenProvider.generateToken(user, ACCESS_TOKEN_DURATION); } @Test public void testGet_ReviewAnalyze() throws Exception { String expectedString = "Hello"; when(reviewSearchService.analyzeText(anyString())).thenReturn(expectedString); mockMvc.perform(get("/data-view/review/analyze?text=" + expectedString) .header("Authorization", "Bearer " + accessToken)) .andExpect(status().isOk()); } @Test public void testGet_CosmeticData() throws Exception { String expectedString = "Cosmetic"; when(cosmeticSearchService.viewCosmeticsData()).thenReturn(expectedString); mockMvc.perform(get("/data-view/cosmetics") .header("Authorization", "Bearer " + accessToken)) .andExpect(status().isOk()); } @Test public void testGet_CosmeticMetricData() throws Exception { String expectedString = "CosmeticMetric"; when(cosmeticSearchService.viewCosmeticMetricsData()).thenReturn(expectedString); mockMvc.perform(get("/data-view/cosmetic-metrics") .header("Authorization", "Bearer " + accessToken)) .andExpect(status().isOk()); } @Test public void testGet_CosmeticCounts() throws Exception {
var metrics = List.of(new CosmeticMetricData(), new CosmeticMetricData());
2
2023-11-01 12:37:16+00:00
16k
FallenDeity/GameEngine2DJava
src/main/java/engine/components/PlayerController.java
[ { "identifier": "PillboxCollider", "path": "src/main/java/engine/physics2d/components/PillboxCollider.java", "snippet": "public class PillboxCollider extends Collider {\n\tprivate final transient CircleCollider bottomCircle = new CircleCollider();\n\tprivate final transient Box2DCollider box = new Box2D...
import engine.physics2d.components.PillboxCollider; import engine.physics2d.components.RigidBody2D; import engine.physics2d.enums.BodyType; import engine.ruby.KeyListener; import engine.ruby.Window; import engine.scenes.Scenes; import engine.util.AssetPool; import engine.util.CONSTANTS; import engine.util.Prefabs; import org.jbox2d.dynamics.contacts.Contact; import org.joml.Math; import org.joml.Vector2f; import org.joml.Vector4f; import static org.lwjgl.glfw.GLFW.*;
11,050
package engine.components; public class PlayerController extends Component { private final Vector2f terminalVelocity = new Vector2f(2.1f, 3.1f); private transient final float bigJumpBoost = 1.05f; private transient final float playerWidth = 0.25f; private transient final Vector2f acceleration = new Vector2f(); private transient final Vector2f velocity = new Vector2f(); public transient boolean travelledPipe = false; private transient boolean isDead = false; private transient int enemyJump = 0; private float walkSpeed = 1.9f; private float jumpBoost = 1.0f; private float invincibleTime = 0.0f; private PlayerState previousState = null; private PlayerState playerState = PlayerState.SMALL; private transient boolean isGrounded = false; private transient float groundDebounce = 0.0f;
package engine.components; public class PlayerController extends Component { private final Vector2f terminalVelocity = new Vector2f(2.1f, 3.1f); private transient final float bigJumpBoost = 1.05f; private transient final float playerWidth = 0.25f; private transient final Vector2f acceleration = new Vector2f(); private transient final Vector2f velocity = new Vector2f(); public transient boolean travelledPipe = false; private transient boolean isDead = false; private transient int enemyJump = 0; private float walkSpeed = 1.9f; private float jumpBoost = 1.0f; private float invincibleTime = 0.0f; private PlayerState previousState = null; private PlayerState playerState = PlayerState.SMALL; private transient boolean isGrounded = false; private transient float groundDebounce = 0.0f;
private transient RigidBody2D rigidBody2D;
1
2023-11-04 13:19:21+00:00
16k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/FileServiceImpl.java
[ { "identifier": "FileAdapt", "path": "talktime-minio/src/main/java/com/qingmeng/adapt/FileAdapt.java", "snippet": "public class FileAdapt {\n\n\n /**\n * 构建 minio vo\n *\n * @param uploadUrl 上传网址\n * @param downloadUrl 下载网址\n * @return {@link MinioVO }\n * @author qingmeng\n...
import cn.hutool.core.util.RandomUtil; import cn.hutool.extra.qrcode.QrCodeUtil; import cn.hutool.extra.qrcode.QrConfig; import com.qingmeng.adapt.FileAdapt; import com.qingmeng.config.adapt.UserInfoAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.constant.SystemConstant; import com.qingmeng.dao.SysUserDao; import com.qingmeng.dto.file.MinioDTO; import com.qingmeng.dto.file.ScanQrcodeDTO; import com.qingmeng.dto.file.UploadUrlDTO; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.entity.SysUser; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.enums.system.ScanQrcodeEnum; import com.qingmeng.enums.system.UploadSceneEnum; import com.qingmeng.service.FileService; import com.qingmeng.service.MinioService; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.common.ScanQrcodeInfoVO; import com.qingmeng.vo.file.MinioVO; import com.qingmeng.vo.user.CheckFriendVO; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.io.File; import java.util.ArrayList; import java.util.Objects;
13,175
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH);
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年12月05日 21:51:00 */ @Service public class FileServiceImpl implements FileService { @Resource private MinioService minioSerivce; @Resource private UserCache userCache; @Resource private SysUserDao sysUserDao; @Resource private SysUserFriendService sysUserFriendService; @Resource private UserFriendSettingCache userFriendSettingCache; /** * 获取二维码网址 * * @param userId 用户 ID * @return {@link String } * @author qingmeng * @createTime: 2023/12/05 21:59:23 */ @Override public String getQrcodeUrl(Long userId) { QrConfig config = new QrConfig(); config.setHeight(SystemConstant.QRCODE_HEIGHT); config.setWidth(SystemConstant.QRCODE_WIDTH);
config.setImg(CommonUtils.getLogoImage());
18
2023-11-07 16:04:55+00:00
16k
BaderTim/minecraft-measurement-mod
src/main/java/io/github/mmm/measurement/device/DeviceController.java
[ { "identifier": "MMM", "path": "src/main/java/io/github/mmm/MMM.java", "snippet": "@Mod(MMM.MODID)\npublic class MMM {\n // Define mod id in a common place for everything to reference\n public static final String MODID = \"mmm\";\n // Directly reference a slf4j logger\n public static final L...
import io.github.mmm.MMM; import io.github.mmm.measurement.device.objects.imu.IMU; import io.github.mmm.measurement.device.objects.imu.IMUController; import io.github.mmm.measurement.device.objects.lidar.LiDAR; import io.github.mmm.measurement.device.objects.lidar.LiDARController; import io.github.mmm.measurement.device.scans.ImuScan; import io.github.mmm.measurement.device.scans.LidarScan; import io.github.mmm.measurement.device.scans.LidarScan2D; import io.github.mmm.modconfig.Config; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.ClientLevel; import net.minecraft.client.player.LocalPlayer; import net.minecraft.network.chat.Component; import java.awt.*; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import static io.github.mmm.MMM.DEVICE_CONTROLLER; import static io.github.mmm.MMM.MMM_ROOT_PATH; import static io.github.mmm.Utils.saveStringToFile;
12,857
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance; private LiDARController lidarController; private LiDAR lidar1; private LiDAR lidar2; private LiDAR lidar3;
package io.github.mmm.measurement.device; public class DeviceController { private Boolean currentlyMeasuring; private int saveInterval; private String savePath; private boolean tickTimeWarning = false; private int tickTimeWarningTolerance; private LiDARController lidarController; private LiDAR lidar1; private LiDAR lidar2; private LiDAR lidar3;
private IMUController imuController;
2
2023-11-06 16:56:46+00:00
16k
KilianCollins/road-runner-quickstart-master
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/SampleTankDrive.java
[ { "identifier": "MAX_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/DriveConstants.java", "snippet": "public static double MAX_ACCEL = 73.17330064499293;" }, { "identifier": "MAX_ANG_ACCEL", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/drive/Dr...
import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_ACCEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_ANG_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MAX_VEL; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.MOTOR_VELO_PID; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.RUN_USING_ENCODER; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.TRACK_WIDTH; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.encoderTicksToInches; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kA; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kStatic; import static org.firstinspires.ftc.teamcode.drive.DriveConstants.kV; import static org.openftc.apriltag.ApriltagDetectionJNI.getPoseEstimate; import com.acmerobotics.roadrunner.drive.TankDrive; import androidx.annotation.NonNull; import com.acmerobotics.dashboard.config.Config; import com.acmerobotics.roadrunner.control.PIDCoefficients; import com.acmerobotics.roadrunner.drive.DriveSignal; import com.acmerobotics.roadrunner.followers.TankPIDVAFollower; import com.acmerobotics.roadrunner.followers.TrajectoryFollower; import com.acmerobotics.roadrunner.geometry.Pose2d; import com.acmerobotics.roadrunner.trajectory.Trajectory; import com.acmerobotics.roadrunner.trajectory.TrajectoryBuilder; import com.acmerobotics.roadrunner.trajectory.constraints.AngularVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.MinVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.ProfileAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TankVelocityConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryAccelerationConstraint; import com.acmerobotics.roadrunner.trajectory.constraints.TrajectoryVelocityConstraint; import com.qualcomm.hardware.lynx.LynxModule; import com.qualcomm.hardware.rev.RevHubOrientationOnRobot; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorEx; import com.qualcomm.robotcore.hardware.HardwareMap; import com.qualcomm.robotcore.hardware.IMU; import com.qualcomm.robotcore.hardware.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequence; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceBuilder; import org.firstinspires.ftc.teamcode.trajectorysequence.TrajectorySequenceRunner; import org.firstinspires.ftc.teamcode.util.LynxModuleUtil; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
11,721
package org.firstinspires.ftc.teamcode.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH); follower = new TankPIDVAFollower(AXIAL_PID, CROSS_TRACK_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // // TODO: adjust the names of the following hardware devices to match your configuration // imu = hardwareMap.get(IMU.class, "imu"); // IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( // DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); // imu.initialize(parameters); // add/remove motors depending on your robot (e.g., 6WD) DcMotorEx leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); DcMotorEx leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); DcMotorEx rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); DcMotorEx rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); leftMotors = Arrays.asList(leftFront, leftRear); rightMotors = Arrays.asList(rightFront, rightRear); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() // TODO: if desired, use setLocalizer() to change the localization method // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>() ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, accelConstraint); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, accelConstraint, MAX_ANG_VEL, MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); }
package org.firstinspires.ftc.teamcode.drive; /* * Simple tank drive hardware implementation for REV hardware. */ @Config public class SampleTankDrive extends TankDrive { public static PIDCoefficients AXIAL_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients CROSS_TRACK_PID = new PIDCoefficients(0, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(0, 0, 0); public static double VX_WEIGHT = 1; public static double OMEGA_WEIGHT = 1; private TrajectorySequenceRunner trajectorySequenceRunner; private static final TrajectoryVelocityConstraint VEL_CONSTRAINT = getVelocityConstraint(MAX_VEL, MAX_ANG_VEL, TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH); follower = new TankPIDVAFollower(AXIAL_PID, CROSS_TRACK_PID, new Pose2d(0.5, 0.5, Math.toRadians(5.0)), 0.5); LynxModuleUtil.ensureMinimumFirmwareVersion(hardwareMap); batteryVoltageSensor = hardwareMap.voltageSensor.iterator().next(); for (LynxModule module : hardwareMap.getAll(LynxModule.class)) { module.setBulkCachingMode(LynxModule.BulkCachingMode.AUTO); } // // TODO: adjust the names of the following hardware devices to match your configuration // imu = hardwareMap.get(IMU.class, "imu"); // IMU.Parameters parameters = new IMU.Parameters(new RevHubOrientationOnRobot( // DriveConstants.LOGO_FACING_DIR, DriveConstants.USB_FACING_DIR)); // imu.initialize(parameters); // add/remove motors depending on your robot (e.g., 6WD) DcMotorEx leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); DcMotorEx leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); DcMotorEx rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); DcMotorEx rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); leftMotors = Arrays.asList(leftFront, leftRear); rightMotors = Arrays.asList(rightFront, rightRear); for (DcMotorEx motor : motors) { MotorConfigurationType motorConfigurationType = motor.getMotorType().clone(); motorConfigurationType.setAchieveableMaxRPMFraction(1.0); motor.setMotorType(motorConfigurationType); } if (RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (RUN_USING_ENCODER && MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, MOTOR_VELO_PID); } // TODO: reverse any motors using DcMotor.setDirection() // TODO: if desired, use setLocalizer() to change the localization method // for instance, setLocalizer(new ThreeTrackingWheelLocalizer(...)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>() ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, accelConstraint); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, accelConstraint); } public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) { return new TrajectorySequenceBuilder( startPose, VEL_CONSTRAINT, accelConstraint, MAX_ANG_VEL, MAX_ANG_ACCEL ); } public void turnAsync(double angle) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(getPoseEstimate()) .turn(angle) .build() ); } public void turn(double angle) { turnAsync(angle); waitForIdle(); } public void followTrajectoryAsync(Trajectory trajectory) { trajectorySequenceRunner.followTrajectorySequenceAsync( trajectorySequenceBuilder(trajectory.start()) .addTrajectory(trajectory) .build() ); } public void followTrajectory(Trajectory trajectory) { followTrajectoryAsync(trajectory); waitForIdle(); }
public void followTrajectorySequenceAsync(TrajectorySequence trajectorySequence) {
11
2023-11-04 04:11:26+00:00
16k
conductor-oss/conductor
grpc-server/src/test/java/com/netflix/conductor/grpc/server/service/WorkflowServiceImplTest.java
[ { "identifier": "SearchResult", "path": "common/src/main/java/com/netflix/conductor/common/run/SearchResult.java", "snippet": "public class SearchResult<T> {\n\n private long totalHits;\n\n private List<T> results;\n\n public SearchResult() {}\n\n public SearchResult(long totalHits, List<T> ...
import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import com.netflix.conductor.common.run.SearchResult; import com.netflix.conductor.common.run.Workflow; import com.netflix.conductor.common.run.WorkflowSummary; import com.netflix.conductor.grpc.SearchPb; import com.netflix.conductor.grpc.WorkflowServicePb; import com.netflix.conductor.proto.WorkflowPb; import com.netflix.conductor.proto.WorkflowSummaryPb; import com.netflix.conductor.service.WorkflowService; import io.grpc.stub.StreamObserver; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; import static org.mockito.MockitoAnnotations.initMocks;
11,318
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.grpc.server.service; public class WorkflowServiceImplTest { private static final String WORKFLOW_ID = "anyWorkflowId"; private static final Boolean RESUME_SUBWORKFLOW_TASKS = true; @Mock private WorkflowService workflowService; private WorkflowServiceImpl workflowServiceImpl; @Before public void init() { initMocks(this); workflowServiceImpl = new WorkflowServiceImpl(workflowService, 5000); } @SuppressWarnings("unchecked") @Test public void givenWorkflowIdWhenRetryWorkflowThenRetriedSuccessfully() { // Given WorkflowServicePb.RetryWorkflowRequest req = WorkflowServicePb.RetryWorkflowRequest.newBuilder() .setWorkflowId(WORKFLOW_ID) .setResumeSubworkflowTasks(true) .build(); // When workflowServiceImpl.retryWorkflow(req, mock(StreamObserver.class)); // Then verify(workflowService).retryWorkflow(WORKFLOW_ID, RESUME_SUBWORKFLOW_TASKS); } @Test public void searchExceptionTest() throws InterruptedException { CountDownLatch streamAlive = new CountDownLatch(1); AtomicReference<Throwable> throwable = new AtomicReference<>(); SearchPb.Request req = SearchPb.Request.newBuilder() .setStart(1) .setSize(50000) .setSort("strings") .setQuery("") .setFreeText("") .build(); StreamObserver<WorkflowServicePb.WorkflowSummarySearchResult> streamObserver = new StreamObserver<>() { @Override public void onNext(WorkflowServicePb.WorkflowSummarySearchResult value) {} @Override public void onError(Throwable t) { throwable.set(t); streamAlive.countDown(); } @Override public void onCompleted() { streamAlive.countDown(); } }; workflowServiceImpl.search(req, streamObserver); streamAlive.await(10, TimeUnit.MILLISECONDS); assertEquals( "INVALID_ARGUMENT: Cannot return more than 5000 results", throwable.get().getMessage()); } @Test public void searchV2ExceptionTest() throws InterruptedException { CountDownLatch streamAlive = new CountDownLatch(1); AtomicReference<Throwable> throwable = new AtomicReference<>(); SearchPb.Request req = SearchPb.Request.newBuilder() .setStart(1) .setSize(50000) .setSort("strings") .setQuery("") .setFreeText("") .build(); StreamObserver<WorkflowServicePb.WorkflowSearchResult> streamObserver = new StreamObserver<>() { @Override public void onNext(WorkflowServicePb.WorkflowSearchResult value) {} @Override public void onError(Throwable t) { throwable.set(t); streamAlive.countDown(); } @Override public void onCompleted() { streamAlive.countDown(); } }; workflowServiceImpl.searchV2(req, streamObserver); streamAlive.await(10, TimeUnit.MILLISECONDS); assertEquals( "INVALID_ARGUMENT: Cannot return more than 5000 results", throwable.get().getMessage()); } @Test public void searchTest() throws InterruptedException { CountDownLatch streamAlive = new CountDownLatch(1); AtomicReference<WorkflowServicePb.WorkflowSummarySearchResult> result = new AtomicReference<>(); SearchPb.Request req = SearchPb.Request.newBuilder() .setStart(1) .setSize(1) .setSort("strings") .setQuery("") .setFreeText("") .build(); StreamObserver<WorkflowServicePb.WorkflowSummarySearchResult> streamObserver = new StreamObserver<>() { @Override public void onNext(WorkflowServicePb.WorkflowSummarySearchResult value) { result.set(value); } @Override public void onError(Throwable t) { streamAlive.countDown(); } @Override public void onCompleted() { streamAlive.countDown(); } }; WorkflowSummary workflow = new WorkflowSummary();
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.netflix.conductor.grpc.server.service; public class WorkflowServiceImplTest { private static final String WORKFLOW_ID = "anyWorkflowId"; private static final Boolean RESUME_SUBWORKFLOW_TASKS = true; @Mock private WorkflowService workflowService; private WorkflowServiceImpl workflowServiceImpl; @Before public void init() { initMocks(this); workflowServiceImpl = new WorkflowServiceImpl(workflowService, 5000); } @SuppressWarnings("unchecked") @Test public void givenWorkflowIdWhenRetryWorkflowThenRetriedSuccessfully() { // Given WorkflowServicePb.RetryWorkflowRequest req = WorkflowServicePb.RetryWorkflowRequest.newBuilder() .setWorkflowId(WORKFLOW_ID) .setResumeSubworkflowTasks(true) .build(); // When workflowServiceImpl.retryWorkflow(req, mock(StreamObserver.class)); // Then verify(workflowService).retryWorkflow(WORKFLOW_ID, RESUME_SUBWORKFLOW_TASKS); } @Test public void searchExceptionTest() throws InterruptedException { CountDownLatch streamAlive = new CountDownLatch(1); AtomicReference<Throwable> throwable = new AtomicReference<>(); SearchPb.Request req = SearchPb.Request.newBuilder() .setStart(1) .setSize(50000) .setSort("strings") .setQuery("") .setFreeText("") .build(); StreamObserver<WorkflowServicePb.WorkflowSummarySearchResult> streamObserver = new StreamObserver<>() { @Override public void onNext(WorkflowServicePb.WorkflowSummarySearchResult value) {} @Override public void onError(Throwable t) { throwable.set(t); streamAlive.countDown(); } @Override public void onCompleted() { streamAlive.countDown(); } }; workflowServiceImpl.search(req, streamObserver); streamAlive.await(10, TimeUnit.MILLISECONDS); assertEquals( "INVALID_ARGUMENT: Cannot return more than 5000 results", throwable.get().getMessage()); } @Test public void searchV2ExceptionTest() throws InterruptedException { CountDownLatch streamAlive = new CountDownLatch(1); AtomicReference<Throwable> throwable = new AtomicReference<>(); SearchPb.Request req = SearchPb.Request.newBuilder() .setStart(1) .setSize(50000) .setSort("strings") .setQuery("") .setFreeText("") .build(); StreamObserver<WorkflowServicePb.WorkflowSearchResult> streamObserver = new StreamObserver<>() { @Override public void onNext(WorkflowServicePb.WorkflowSearchResult value) {} @Override public void onError(Throwable t) { throwable.set(t); streamAlive.countDown(); } @Override public void onCompleted() { streamAlive.countDown(); } }; workflowServiceImpl.searchV2(req, streamObserver); streamAlive.await(10, TimeUnit.MILLISECONDS); assertEquals( "INVALID_ARGUMENT: Cannot return more than 5000 results", throwable.get().getMessage()); } @Test public void searchTest() throws InterruptedException { CountDownLatch streamAlive = new CountDownLatch(1); AtomicReference<WorkflowServicePb.WorkflowSummarySearchResult> result = new AtomicReference<>(); SearchPb.Request req = SearchPb.Request.newBuilder() .setStart(1) .setSize(1) .setSort("strings") .setQuery("") .setFreeText("") .build(); StreamObserver<WorkflowServicePb.WorkflowSummarySearchResult> streamObserver = new StreamObserver<>() { @Override public void onNext(WorkflowServicePb.WorkflowSummarySearchResult value) { result.set(value); } @Override public void onError(Throwable t) { streamAlive.countDown(); } @Override public void onCompleted() { streamAlive.countDown(); } }; WorkflowSummary workflow = new WorkflowSummary();
SearchResult<WorkflowSummary> searchResult = new SearchResult<>();
0
2023-12-08 06:06:09+00:00
16k
kaifangqian/open-sign
src/main/java/com/resrun/controller/OpenSignController.java
[ { "identifier": "SignTypeEnum", "path": "src/main/java/com/resrun/enums/SignTypeEnum.java", "snippet": "public enum SignTypeEnum {\n\n\n POSITION(1,\"位置签署\"),\n KEYWORD(2,\"关键字签署\"),\n\n ;\n\n private String msg;\n private Integer code;\n\n\n SignTypeEnum(Integer code,String msg){\n ...
import com.resrun.enums.SignTypeEnum; import com.resrun.service.pojo.CertificateProperty; import com.resrun.service.pojo.GenerateCertificateInfo; import com.resrun.service.pojo.RealPositionProperty; import com.resrun.service.pojo.SourcePositionProperty; import com.resrun.service.cert.CertService; import com.resrun.service.image.EntSealClipService; import com.resrun.service.image.EntSealGenerateService; import com.resrun.service.pdf.CalculatePositionService; import com.resrun.service.pdf.SignService; import com.resrun.service.verify.SignVerifyService; import com.resrun.utils.Base64; import com.resrun.controller.vo.base.Result; import com.resrun.controller.vo.request.*; import com.resrun.controller.vo.response.SealResponse; import com.resrun.controller.vo.response.SignResponse; import com.resrun.controller.vo.response.VerifyResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.pdfbox.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.*; import java.io.*; import java.util.ArrayList; import java.util.List;
13,513
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST) public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){ if(request.getImage() == null || request.getImage().length() == 0){ return Result.error("图片数据为空",null); }
package com.resrun.controller; /** * @Description: OpenSignController * @Package: com.resrun.controller * @ClassName: OpenSignController * @copyright 北京资源律动科技有限公司 */ @Api(tags = "开放签-演示demo") @RestController public class OpenSignController { @Autowired private SignVerifyService signVerifyService ; @Autowired private CalculatePositionService calculatePositionService ; @Autowired private SignService signService ; @Autowired private EntSealGenerateService entSealGenerateService ; @Autowired private EntSealClipService entSealClipService ; @Autowired private CertService certService ; @ApiOperation("生成企业签章-上传生成") @RequestMapping(value = "/clip/seal",method = RequestMethod.POST) public Result<SealResponse> generateUpload(@RequestBody ClipSealRequest request){ if(request.getImage() == null || request.getImage().length() == 0){ return Result.error("图片数据为空",null); }
byte[] decode = Base64.decode(request.getImage());
11
2023-12-14 06:53:32+00:00
16k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/utils/ColorUtil.java
[ { "identifier": "MONET_SEED_COLOR", "path": "app/src/main/java/com/drdisagree/colorblendr/common/Const.java", "snippet": "public static final String MONET_SEED_COLOR = \"monetSeedColor\";" }, { "identifier": "WALLPAPER_COLOR_LIST", "path": "app/src/main/java/com/drdisagree/colorblendr/common...
import static com.drdisagree.colorblendr.common.Const.MONET_SEED_COLOR; import static com.drdisagree.colorblendr.common.Const.WALLPAPER_COLOR_LIST; import android.content.Context; import android.graphics.Color; import android.util.TypedValue; import androidx.annotation.ColorInt; import androidx.annotation.FloatRange; import androidx.core.content.ContextCompat; import androidx.core.graphics.ColorUtils; import com.drdisagree.colorblendr.ColorBlendr; import com.drdisagree.colorblendr.common.Const; import com.drdisagree.colorblendr.config.RPrefs; import com.drdisagree.colorblendr.utils.cam.Cam; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger;
12,297
}, new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary0, context.getTheme()) }, new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral0, context.getTheme()) }, new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant0, context.getTheme()) }}; } public static int calculateTextColor(@ColorInt int color) { double darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255; return darkness < 0.5 ? Color.BLACK : Color.WHITE; } /** * Convert a color appearance model representation to an ARGB color. * <p> * Note: the returned color may have a lower chroma than requested. Whether a chroma is * available depends on luminance. For example, there's no such thing as a high chroma light * red, due to the limitations of our eyes and/or physics. If the requested chroma is * unavailable, the highest possible chroma at the requested luminance is returned. * * @param hue hue, in degrees, in CAM coordinates * @param chroma chroma in CAM coordinates. * @param lstar perceptual luminance, L* in L*a*b* */ @ColorInt public static int CAMToColor(float hue, float chroma, float lstar) { return Cam.getInt(hue, chroma, lstar); } private static final double XYZ_WHITE_REFERENCE_X = 95.047; private static final double XYZ_WHITE_REFERENCE_Y = 100; private static final double XYZ_WHITE_REFERENCE_Z = 108.883; /** * Converts a color from CIE XYZ to its RGB representation. * * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE * 2° Standard Observer (1931).</p> * * @param x X component value [0...95.047) * @param y Y component value [0...100) * @param z Z component value [0...108.883) * @return int containing the RGB representation */ @ColorInt public static int XYZToColor(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x, @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y, @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z) { double r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100; double g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100; double b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100; r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r; g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g; b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b; return Color.rgb( constrain((int) Math.round(r * 255), 0, 255), constrain((int) Math.round(g * 255), 0, 255), constrain((int) Math.round(b * 255), 0, 255)); } private static float constrain(float amount, float low, float high) { return amount < low ? low : Math.min(amount, high); } @SuppressWarnings("SameParameterValue") private static int constrain(int amount, int low, int high) { return amount < low ? low : Math.min(amount, high); } public static ArrayList<Integer> getMonetAccentColors() { ArrayList<Integer> colors = new ArrayList<>();
package com.drdisagree.colorblendr.utils; public class ColorUtil { public static @ColorInt int getColorFromAttribute(Context context, int attr) { TypedValue typedValue = new TypedValue(); context.getTheme().resolveAttribute(attr, typedValue, true); return typedValue.data; } public static ArrayList<ArrayList<Integer>> generateModifiedColors( Context context, ColorSchemeUtil.MONET style, int accentSaturation, int backgroundSaturation, int backgroundLightness, boolean pitchBlackTheme, boolean accurateShades ) { return generateModifiedColors( context, style, accentSaturation, backgroundSaturation, backgroundLightness, pitchBlackTheme, accurateShades, true ); } public static ArrayList<ArrayList<Integer>> generateModifiedColors( Context context, ColorSchemeUtil.MONET style, int accentSaturation, int backgroundSaturation, int backgroundLightness, boolean pitchBlackTheme, boolean accurateShades, boolean modifyPitchBlack ) { return generateModifiedColors( context, style, accentSaturation, backgroundSaturation, backgroundLightness, pitchBlackTheme, accurateShades, modifyPitchBlack, SystemUtil.isDarkMode() ); } public static ArrayList<ArrayList<Integer>> generateModifiedColors( Context context, ColorSchemeUtil.MONET style, int accentSaturation, int backgroundSaturation, int backgroundLightness, boolean pitchBlackTheme, boolean accurateShades, boolean modifyPitchBlack, boolean isDark ) { String wallpaperColors = RPrefs.getString(WALLPAPER_COLOR_LIST, null); ArrayList<Integer> wallpaperColorList; if (wallpaperColors != null) { wallpaperColorList = Const.GSON.fromJson( wallpaperColors, new TypeToken<ArrayList<Integer>>() { }.getType() ); } else { wallpaperColorList = WallpaperUtil.getWallpaperColors(context); } return generateModifiedColors( style, RPrefs.getInt( MONET_SEED_COLOR, wallpaperColorList.get(0) ), accentSaturation, backgroundSaturation, backgroundLightness, pitchBlackTheme, accurateShades, modifyPitchBlack, isDark ); } public static ArrayList<ArrayList<Integer>> generateModifiedColors( ColorSchemeUtil.MONET style, @ColorInt int seedColor, int accentSaturation, int backgroundSaturation, int backgroundLightness, boolean pitchBlackTheme, boolean accurateShades, boolean modifyPitchBlack, boolean isDark ) { ArrayList<ArrayList<Integer>> palette = ColorSchemeUtil.generateColorPalette( style, seedColor, isDark ); // Modify colors for (int i = 0; i < palette.size(); i++) { ArrayList<Integer> modifiedShades = ColorModifiers.modifyColors( new ArrayList<>(palette.get(i).subList(1, palette.get(i).size())), new AtomicInteger(i), style, accentSaturation, backgroundSaturation, backgroundLightness, pitchBlackTheme, accurateShades, modifyPitchBlack ); for (int j = 1; j < palette.get(i).size(); j++) { palette.get(i).set(j, modifiedShades.get(j - 1)); } } return palette; } public static @ColorInt int getAccentColor(Context context) { TypedValue typedValue = new TypedValue(); context.getTheme().resolveAttribute(com.google.android.material.R.attr.colorPrimary, typedValue, true); return typedValue.data; } public static int modifySaturation(int color, int saturation) { float saturationFloat = (saturation - 100) / 100f; float[] hsl = new float[3]; ColorUtils.colorToHSL(color, hsl); if (saturationFloat > 0) { hsl[1] += ((1 - hsl[1]) * saturationFloat); } else if (saturationFloat < 0) { hsl[1] += (hsl[1] * saturationFloat); } return ColorUtils.HSLToColor(hsl); } public static int modifyLightness(int color, int lightness, int idx) { float lightnessFloat = (lightness - 100) / 1000f; float shade = getSystemTintList()[idx]; if (idx == 0 || idx == 12) { lightnessFloat = 0; } else if (idx == 1) { lightnessFloat /= 10; } else if (idx == 2) { lightnessFloat /= 2; } float[] hsl = new float[3]; ColorUtils.colorToHSL(color, hsl); hsl[2] = shade + lightnessFloat; return ColorUtils.HSLToColor(hsl); } public static float getHue(int color) { float[] hsl = new float[3]; ColorUtils.colorToHSL(color, hsl); return hsl[0]; } public static float[] getSystemTintList() { return new float[]{1.0f, 0.99f, 0.95f, 0.9f, 0.8f, 0.7f, 0.6f, 0.496f, 0.4f, 0.3f, 0.2f, 0.1f, 0.0f}; } public static String[][] getColorNames() { String[] accentTypes = {"system_accent1", "system_accent2", "system_accent3", "system_neutral1", "system_neutral2"}; String[] values = {"0", "10", "50", "100", "200", "300", "400", "500", "600", "700", "800", "900", "1000"}; String[][] colorNames = new String[accentTypes.length][values.length]; for (int i = 0; i < accentTypes.length; i++) { for (int j = 0; j < values.length; j++) { colorNames[i][j] = accentTypes[i] + "_" + values[j]; } } return colorNames; } public static String[][] getColorNamesM3(boolean isDynamic, boolean prefixG) { String prefix = "m3_ref_palette_"; String dynamic = "dynamic_"; String[] accentTypes = {"primary", "secondary", "tertiary", "neutral", "neutral_variant"}; String[] values = {"100", "99", "95", "90", "80", "70", "60", "50", "40", "30", "20", "10", "0"}; String[][] colorNames = new String[accentTypes.length][values.length]; for (int i = 0; i < accentTypes.length; i++) { for (int j = 0; j < values.length; j++) { colorNames[i][j] = (prefixG ? "g" : "") + prefix + (isDynamic ? dynamic : "") + accentTypes[i] + values[j]; } } return colorNames; } public static String intToHexColor(int colorInt) { return String.format("#%06X", (0xFFFFFF & colorInt)); } public static int[][] getSystemColors(Context context) { return new int[][]{ new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_primary0, context.getTheme()) }, new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_secondary0, context.getTheme()) }, new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_tertiary0, context.getTheme()) }, new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral0, context.getTheme()) }, new int[]{ context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant100, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant99, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant95, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant90, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant80, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant70, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant60, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant50, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant40, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant30, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant20, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant10, context.getTheme()), context.getResources().getColor(com.google.android.material.R.color.material_dynamic_neutral_variant0, context.getTheme()) }}; } public static int calculateTextColor(@ColorInt int color) { double darkness = 1 - (0.299 * Color.red(color) + 0.587 * Color.green(color) + 0.114 * Color.blue(color)) / 255; return darkness < 0.5 ? Color.BLACK : Color.WHITE; } /** * Convert a color appearance model representation to an ARGB color. * <p> * Note: the returned color may have a lower chroma than requested. Whether a chroma is * available depends on luminance. For example, there's no such thing as a high chroma light * red, due to the limitations of our eyes and/or physics. If the requested chroma is * unavailable, the highest possible chroma at the requested luminance is returned. * * @param hue hue, in degrees, in CAM coordinates * @param chroma chroma in CAM coordinates. * @param lstar perceptual luminance, L* in L*a*b* */ @ColorInt public static int CAMToColor(float hue, float chroma, float lstar) { return Cam.getInt(hue, chroma, lstar); } private static final double XYZ_WHITE_REFERENCE_X = 95.047; private static final double XYZ_WHITE_REFERENCE_Y = 100; private static final double XYZ_WHITE_REFERENCE_Z = 108.883; /** * Converts a color from CIE XYZ to its RGB representation. * * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE * 2° Standard Observer (1931).</p> * * @param x X component value [0...95.047) * @param y Y component value [0...100) * @param z Z component value [0...108.883) * @return int containing the RGB representation */ @ColorInt public static int XYZToColor(@FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_X) double x, @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Y) double y, @FloatRange(from = 0f, to = XYZ_WHITE_REFERENCE_Z) double z) { double r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100; double g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100; double b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100; r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r; g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g; b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b; return Color.rgb( constrain((int) Math.round(r * 255), 0, 255), constrain((int) Math.round(g * 255), 0, 255), constrain((int) Math.round(b * 255), 0, 255)); } private static float constrain(float amount, float low, float high) { return amount < low ? low : Math.min(amount, high); } @SuppressWarnings("SameParameterValue") private static int constrain(int amount, int low, int high) { return amount < low ? low : Math.min(amount, high); } public static ArrayList<Integer> getMonetAccentColors() { ArrayList<Integer> colors = new ArrayList<>();
colors.add(ContextCompat.getColor(ColorBlendr.getAppContext(), android.R.color.system_accent1_400));
2
2023-12-06 13:20:16+00:00
16k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/action/ClickActionTask.java
[ { "identifier": "DeluxeMenus", "path": "src/main/java/com/extendedclip/deluxemenus/DeluxeMenus.java", "snippet": "public class DeluxeMenus extends JavaPlugin {\r\n\r\n public final static Map<String, Material> MATERIALS\r\n = Arrays.stream(Material.values()).collect(Collectors.toUnmodifiableMa...
import com.extendedclip.deluxemenus.DeluxeMenus; import com.extendedclip.deluxemenus.menu.Menu; import com.extendedclip.deluxemenus.menu.MenuHolder; import com.extendedclip.deluxemenus.utils.AdventureUtils; import com.extendedclip.deluxemenus.utils.DebugLevel; import com.extendedclip.deluxemenus.utils.ExpUtils; import com.extendedclip.deluxemenus.utils.StringUtils; import com.extendedclip.deluxemenus.utils.VersionHelper; import java.util.logging.Level; import me.clip.placeholderapi.PlaceholderAPI; import net.kyori.adventure.Adventure; import net.kyori.adventure.text.minimessage.MiniMessage; import org.bukkit.Bukkit; import org.bukkit.OfflinePlayer; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.scheduler.BukkitRunnable; import org.jetbrains.annotations.NotNull;
12,888
case PLAYER_COMMAND_EVENT: Bukkit.getPluginManager().callEvent(new PlayerCommandPreprocessEvent(player, "/" + executable)); break; case PLACEHOLDER: PlaceholderAPI.setPlaceholders(player, executable); break; case CHAT: player.chat(executable); break; case CONSOLE: Bukkit.dispatchCommand(Bukkit.getConsoleSender(), executable); break; case MINI_MESSAGE: plugin.adventure().player(player).sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MINI_BROADCAST: plugin.adventure().all().sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MESSAGE: player.sendMessage(StringUtils.color(executable)); break; case BROADCAST: Bukkit.broadcastMessage(StringUtils.color(executable)); break; case CLOSE: Menu.closeMenu(player, true, true); break; case OPEN_GUI_MENU: case OPEN_MENU: final Menu menuToOpen = Menu.getMenu(executable); if (menuToOpen == null) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Could not find and open menu " + executable); break; } if (holder == null) { menuToOpen.openMenu(player); break; } menuToOpen.openMenu(player, holder.getTypedArgs(), holder.getPlaceholderPlayer()); break; case CONNECT: DeluxeMenus.getInstance().connect(player, executable); break; case JSON_MESSAGE: AdventureUtils.sendJson(player, executable); break; case JSON_BROADCAST: case BROADCAST_JSON: plugin.adventure().all().sendMessage(AdventureUtils.fromJson(executable)); break; case REFRESH: if (holder == null) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.WARNING, player.getName() + " does not have menu open! Nothing to refresh!" ); break; } holder.refreshMenu(); break; case TAKE_MONEY: if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Vault not hooked! Cannot take money!"); break; } try { DeluxeMenus.getInstance().getVault().takeMoney(player, Double.parseDouble(executable)); } catch (final NumberFormatException exception) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.WARNING, "Amount for take money action: " + executable + ", is not a valid number!" ); } break; case GIVE_MONEY: if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Vault not hooked! Cannot give money!"); break; } try { DeluxeMenus.getInstance().getVault().giveMoney(player, Double.parseDouble(executable)); } catch (final NumberFormatException exception) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.WARNING, "Amount for give money action: " + executable + ", is not a valid number!" ); } break; case TAKE_EXP: case GIVE_EXP: final String lowerCaseExecutable = executable.toLowerCase(); try { if (Integer.parseInt(lowerCaseExecutable.replaceAll("l", "")) <= 0) break; if (actionType == ActionType.TAKE_EXP) {
package com.extendedclip.deluxemenus.action; public class ClickActionTask extends BukkitRunnable { private final DeluxeMenus plugin; private final String name; private final ActionType actionType; private final String exec; public ClickActionTask( @NotNull final DeluxeMenus plugin, @NotNull final String name, @NotNull final ActionType actionType, @NotNull final String exec ) { this.plugin = plugin; this.name = name; this.actionType = actionType; this.exec = exec; } @Override public void run() { final Player player = Bukkit.getServer().getPlayerExact(name); if (player == null) { return; } final String executable = PlaceholderAPI.setPlaceholders((OfflinePlayer) player, exec); final MenuHolder holder = Menu.getMenuHolder(player); switch (actionType) { case META: if (!VersionHelper.IS_PDC_VERSION || DeluxeMenus.getInstance().getPersistentMetaHandler() == null) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Meta action not supported on this server version."); break; } try { final boolean result = DeluxeMenus.getInstance().getPersistentMetaHandler().setMeta(player, executable); if (!result) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid meta action! Make sure you have the right syntax."); break; } } catch (final NumberFormatException exception) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.INFO, "Invalid integer value for meta action!"); } break; case PLAYER: player.chat("/" + executable); break; case PLAYER_COMMAND_EVENT: Bukkit.getPluginManager().callEvent(new PlayerCommandPreprocessEvent(player, "/" + executable)); break; case PLACEHOLDER: PlaceholderAPI.setPlaceholders(player, executable); break; case CHAT: player.chat(executable); break; case CONSOLE: Bukkit.dispatchCommand(Bukkit.getConsoleSender(), executable); break; case MINI_MESSAGE: plugin.adventure().player(player).sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MINI_BROADCAST: plugin.adventure().all().sendMessage(MiniMessage.miniMessage().deserialize(executable)); break; case MESSAGE: player.sendMessage(StringUtils.color(executable)); break; case BROADCAST: Bukkit.broadcastMessage(StringUtils.color(executable)); break; case CLOSE: Menu.closeMenu(player, true, true); break; case OPEN_GUI_MENU: case OPEN_MENU: final Menu menuToOpen = Menu.getMenu(executable); if (menuToOpen == null) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Could not find and open menu " + executable); break; } if (holder == null) { menuToOpen.openMenu(player); break; } menuToOpen.openMenu(player, holder.getTypedArgs(), holder.getPlaceholderPlayer()); break; case CONNECT: DeluxeMenus.getInstance().connect(player, executable); break; case JSON_MESSAGE: AdventureUtils.sendJson(player, executable); break; case JSON_BROADCAST: case BROADCAST_JSON: plugin.adventure().all().sendMessage(AdventureUtils.fromJson(executable)); break; case REFRESH: if (holder == null) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.WARNING, player.getName() + " does not have menu open! Nothing to refresh!" ); break; } holder.refreshMenu(); break; case TAKE_MONEY: if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Vault not hooked! Cannot take money!"); break; } try { DeluxeMenus.getInstance().getVault().takeMoney(player, Double.parseDouble(executable)); } catch (final NumberFormatException exception) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.WARNING, "Amount for take money action: " + executable + ", is not a valid number!" ); } break; case GIVE_MONEY: if (DeluxeMenus.getInstance().getVault() == null || !DeluxeMenus.getInstance().getVault().hooked()) { DeluxeMenus.debug(DebugLevel.HIGHEST, Level.WARNING, "Vault not hooked! Cannot give money!"); break; } try { DeluxeMenus.getInstance().getVault().giveMoney(player, Double.parseDouble(executable)); } catch (final NumberFormatException exception) { DeluxeMenus.debug( DebugLevel.HIGHEST, Level.WARNING, "Amount for give money action: " + executable + ", is not a valid number!" ); } break; case TAKE_EXP: case GIVE_EXP: final String lowerCaseExecutable = executable.toLowerCase(); try { if (Integer.parseInt(lowerCaseExecutable.replaceAll("l", "")) <= 0) break; if (actionType == ActionType.TAKE_EXP) {
ExpUtils.setExp(player, "-" + lowerCaseExecutable);
5
2023-12-14 23:41:07+00:00
16k
lxs2601055687/contextAdminRuoYi
ruoyi-generator/src/main/java/com/ruoyi/generator/util/VelocityUtils.java
[ { "identifier": "GenConstants", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/GenConstants.java", "snippet": "public interface GenConstants {\n /**\n * 单表(增删改查)\n */\n String TPL_CRUD = \"crud\";\n\n /**\n * 树表(增删改查)\n */\n String TPL_TREE = \"tree\";\n\n /...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Dict; import cn.hutool.core.util.ObjectUtil; import com.ruoyi.common.constant.GenConstants; import com.ruoyi.common.helper.DataBaseHelper; import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.JsonUtils; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.generator.domain.GenTable; import com.ruoyi.generator.domain.GenTableColumn; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.velocity.VelocityContext; import java.util.*;
11,351
String subTableFkName = genTable.getSubTableFkName(); String subClassName = genTable.getSubTable().getClassName(); String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName); context.put("subTable", subTable); context.put("subTableName", subTableName); context.put("subTableFkName", subTableFkName); context.put("subTableFkClassName", subTableFkClassName); context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName)); context.put("subClassName", subClassName); context.put("subclassName", StringUtils.uncapitalize(subClassName)); context.put("subImportList", getImportList(genTable.getSubTable())); } /** * 获取模板信息 * * @return 模板列表 */ public static List<String> getTemplateList(String tplCategory) { List<String> templates = new ArrayList<String>(); templates.add("vm/java/domain.java.vm"); templates.add("vm/java/vo.java.vm"); templates.add("vm/java/bo.java.vm"); templates.add("vm/java/mapper.java.vm"); templates.add("vm/java/service.java.vm"); templates.add("vm/java/serviceImpl.java.vm"); templates.add("vm/java/controller.java.vm"); templates.add("vm/xml/mapper.xml.vm"); if (DataBaseHelper.isOracle()) { templates.add("vm/sql/oracle/sql.vm"); } else if (DataBaseHelper.isPostgerSql()) { templates.add("vm/sql/postgres/sql.vm"); } else if (DataBaseHelper.isSqlServer()) { templates.add("vm/sql/sqlserver/sql.vm"); } else { templates.add("vm/sql/sql.vm"); } templates.add("vm/js/api.js.vm"); if (GenConstants.TPL_CRUD.equals(tplCategory)) { templates.add("vm/vue/index.vue.vm"); } else if (GenConstants.TPL_TREE.equals(tplCategory)) { templates.add("vm/vue/index-tree.vue.vm"); } else if (GenConstants.TPL_SUB.equals(tplCategory)) { templates.add("vm/vue/index.vue.vm"); templates.add("vm/java/sub-domain.java.vm"); } return templates; } /** * 获取文件名 */ public static String getFileName(String template, GenTable genTable) { // 文件名称 String fileName = ""; // 包路径 String packageName = genTable.getPackageName(); // 模块名 String moduleName = genTable.getModuleName(); // 大写类名 String className = genTable.getClassName(); // 业务名称 String businessName = genTable.getBusinessName(); String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/"); String mybatisPath = MYBATIS_PATH + "/" + moduleName; String vuePath = "vue"; if (template.contains("domain.java.vm")) { fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); } if (template.contains("vo.java.vm")) { fileName = StringUtils.format("{}/domain/vo/{}Vo.java", javaPath, className); } if (template.contains("bo.java.vm")) { fileName = StringUtils.format("{}/domain/bo/{}Bo.java", javaPath, className); } if (template.contains("sub-domain.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName()); } else if (template.contains("mapper.java.vm")) { fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); } else if (template.contains("service.java.vm")) { fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className); } else if (template.contains("serviceImpl.java.vm")) { fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); } else if (template.contains("controller.java.vm")) { fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); } else if (template.contains("mapper.xml.vm")) { fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); } else if (template.contains("sql.vm")) { fileName = businessName + "Menu.sql"; } else if (template.contains("api.js.vm")) { fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); } else if (template.contains("index.vue.vm")) { fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } else if (template.contains("index-tree.vue.vm")) { fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } return fileName; } /** * 获取包前缀 * * @param packageName 包名称 * @return 包前缀名称 */ public static String getPackagePrefix(String packageName) { int lastIndex = packageName.lastIndexOf("."); return StringUtils.substring(packageName, 0, lastIndex); } /** * 根据列类型获取导入包 * * @param genTable 业务表对象 * @return 返回需要导入的包列表 */ public static HashSet<String> getImportList(GenTable genTable) {
package com.ruoyi.generator.util; /** * 模板处理工具类 * * @author ruoyi */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public class VelocityUtils { /** * 项目空间路径 */ private static final String PROJECT_PATH = "main/java"; /** * mybatis空间路径 */ private static final String MYBATIS_PATH = "main/resources/mapper"; /** * 默认上级菜单,系统工具 */ private static final String DEFAULT_PARENT_MENU_ID = "3"; /** * 设置模板变量信息 * * @return 模板列表 */ public static VelocityContext prepareContext(GenTable genTable) { String moduleName = genTable.getModuleName(); String businessName = genTable.getBusinessName(); String packageName = genTable.getPackageName(); String tplCategory = genTable.getTplCategory(); String functionName = genTable.getFunctionName(); VelocityContext velocityContext = new VelocityContext(); velocityContext.put("tplCategory", genTable.getTplCategory()); velocityContext.put("tableName", genTable.getTableName()); velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); velocityContext.put("ClassName", genTable.getClassName()); velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName())); velocityContext.put("moduleName", genTable.getModuleName()); velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName())); velocityContext.put("businessName", genTable.getBusinessName()); velocityContext.put("basePackage", getPackagePrefix(packageName)); velocityContext.put("packageName", packageName); velocityContext.put("author", genTable.getFunctionAuthor()); velocityContext.put("datetime", DateUtils.getDate()); velocityContext.put("pkColumn", genTable.getPkColumn()); velocityContext.put("importList", getImportList(genTable)); velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); velocityContext.put("columns", genTable.getColumns()); velocityContext.put("table", genTable); velocityContext.put("dicts", getDicts(genTable)); setMenuVelocityContext(velocityContext, genTable); if (GenConstants.TPL_TREE.equals(tplCategory)) { setTreeVelocityContext(velocityContext, genTable); } if (GenConstants.TPL_SUB.equals(tplCategory)) { setSubVelocityContext(velocityContext, genTable); } return velocityContext; } public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) { String options = genTable.getOptions(); Dict paramsObj = JsonUtils.parseMap(options); String parentMenuId = getParentMenuId(paramsObj); context.put("parentMenuId", parentMenuId); } public static void setTreeVelocityContext(VelocityContext context, GenTable genTable) { String options = genTable.getOptions(); Dict paramsObj = JsonUtils.parseMap(options); String treeCode = getTreecode(paramsObj); String treeParentCode = getTreeParentCode(paramsObj); String treeName = getTreeName(paramsObj); context.put("treeCode", treeCode); context.put("treeParentCode", treeParentCode); context.put("treeName", treeName); context.put("expandColumn", getExpandColumn(genTable)); if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { context.put("tree_parent_code", paramsObj.get(GenConstants.TREE_PARENT_CODE)); } if (paramsObj.containsKey(GenConstants.TREE_NAME)) { context.put("tree_name", paramsObj.get(GenConstants.TREE_NAME)); } } public static void setSubVelocityContext(VelocityContext context, GenTable genTable) { GenTable subTable = genTable.getSubTable(); String subTableName = genTable.getSubTableName(); String subTableFkName = genTable.getSubTableFkName(); String subClassName = genTable.getSubTable().getClassName(); String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName); context.put("subTable", subTable); context.put("subTableName", subTableName); context.put("subTableFkName", subTableFkName); context.put("subTableFkClassName", subTableFkClassName); context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName)); context.put("subClassName", subClassName); context.put("subclassName", StringUtils.uncapitalize(subClassName)); context.put("subImportList", getImportList(genTable.getSubTable())); } /** * 获取模板信息 * * @return 模板列表 */ public static List<String> getTemplateList(String tplCategory) { List<String> templates = new ArrayList<String>(); templates.add("vm/java/domain.java.vm"); templates.add("vm/java/vo.java.vm"); templates.add("vm/java/bo.java.vm"); templates.add("vm/java/mapper.java.vm"); templates.add("vm/java/service.java.vm"); templates.add("vm/java/serviceImpl.java.vm"); templates.add("vm/java/controller.java.vm"); templates.add("vm/xml/mapper.xml.vm"); if (DataBaseHelper.isOracle()) { templates.add("vm/sql/oracle/sql.vm"); } else if (DataBaseHelper.isPostgerSql()) { templates.add("vm/sql/postgres/sql.vm"); } else if (DataBaseHelper.isSqlServer()) { templates.add("vm/sql/sqlserver/sql.vm"); } else { templates.add("vm/sql/sql.vm"); } templates.add("vm/js/api.js.vm"); if (GenConstants.TPL_CRUD.equals(tplCategory)) { templates.add("vm/vue/index.vue.vm"); } else if (GenConstants.TPL_TREE.equals(tplCategory)) { templates.add("vm/vue/index-tree.vue.vm"); } else if (GenConstants.TPL_SUB.equals(tplCategory)) { templates.add("vm/vue/index.vue.vm"); templates.add("vm/java/sub-domain.java.vm"); } return templates; } /** * 获取文件名 */ public static String getFileName(String template, GenTable genTable) { // 文件名称 String fileName = ""; // 包路径 String packageName = genTable.getPackageName(); // 模块名 String moduleName = genTable.getModuleName(); // 大写类名 String className = genTable.getClassName(); // 业务名称 String businessName = genTable.getBusinessName(); String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/"); String mybatisPath = MYBATIS_PATH + "/" + moduleName; String vuePath = "vue"; if (template.contains("domain.java.vm")) { fileName = StringUtils.format("{}/domain/{}.java", javaPath, className); } if (template.contains("vo.java.vm")) { fileName = StringUtils.format("{}/domain/vo/{}Vo.java", javaPath, className); } if (template.contains("bo.java.vm")) { fileName = StringUtils.format("{}/domain/bo/{}Bo.java", javaPath, className); } if (template.contains("sub-domain.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { fileName = StringUtils.format("{}/domain/{}.java", javaPath, genTable.getSubTable().getClassName()); } else if (template.contains("mapper.java.vm")) { fileName = StringUtils.format("{}/mapper/{}Mapper.java", javaPath, className); } else if (template.contains("service.java.vm")) { fileName = StringUtils.format("{}/service/I{}Service.java", javaPath, className); } else if (template.contains("serviceImpl.java.vm")) { fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); } else if (template.contains("controller.java.vm")) { fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); } else if (template.contains("mapper.xml.vm")) { fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); } else if (template.contains("sql.vm")) { fileName = businessName + "Menu.sql"; } else if (template.contains("api.js.vm")) { fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); } else if (template.contains("index.vue.vm")) { fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } else if (template.contains("index-tree.vue.vm")) { fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } return fileName; } /** * 获取包前缀 * * @param packageName 包名称 * @return 包前缀名称 */ public static String getPackagePrefix(String packageName) { int lastIndex = packageName.lastIndexOf("."); return StringUtils.substring(packageName, 0, lastIndex); } /** * 根据列类型获取导入包 * * @param genTable 业务表对象 * @return 返回需要导入的包列表 */ public static HashSet<String> getImportList(GenTable genTable) {
List<GenTableColumn> columns = genTable.getColumns();
6
2023-12-07 12:06:21+00:00
16k
DantSu/studio
driver/src/main/java/studio/driver/fs/FsStoryTellerAsyncDriver.java
[ { "identifier": "transformUuid", "path": "core/src/main/java/studio/core/v1/writer/fs/FsStoryPackWriter.java", "snippet": "public static String transformUuid(String uuid) {\n String uuidStr = uuid.replace(\"-\", \"\");\n return uuidStr.substring(uuidStr.length()-8).toUpperCase();\n}" }, { ...
import static studio.core.v1.writer.fs.FsStoryPackWriter.transformUuid; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.usb4java.Device; import studio.core.v1.utils.AESCBCCipher; import studio.core.v1.utils.SecurityUtils; import studio.core.v1.utils.XXTEACipher; import studio.core.v1.utils.exception.StoryTellerException; import studio.core.v1.utils.stream.ThrowingConsumer; import studio.core.v1.writer.fs.FsStoryPackWriter; import studio.core.v1.writer.fs.FsStoryPackWriterV3; import studio.driver.DeviceVersion; import studio.driver.LibUsbDetectionHelper; import studio.driver.StoryTellerAsyncDriver; import studio.driver.event.DevicePluggedListener; import studio.driver.event.DeviceUnpluggedListener; import studio.driver.event.TransferProgressListener; import studio.driver.model.TransferStatus; import studio.driver.model.fs.FsDeviceInfos; import studio.driver.model.fs.FsStoryPackInfos;
12,553
throw new StoryTellerException("Pack not found"); } } catch (Exception e) { throw new StoryTellerException("Failed to read pack metadata on device partition", e); } }); } private CompletionStage<Boolean> writePackIndex(List<UUID> packUUIDs) { try { Path piFile = this.partitionMountPoint.resolve(PACK_INDEX_FILENAME); LOGGER.trace("Replacing pack index file: {}", piFile); ByteBuffer bb = ByteBuffer.allocate(16 * packUUIDs.size()); for (UUID packUUID : packUUIDs) { bb.putLong(packUUID.getMostSignificantBits()); bb.putLong(packUUID.getLeastSignificantBits()); } Files.write(piFile, bb.array()); return CompletableFuture.completedFuture(true); } catch (Exception e) { return CompletableFuture.failedFuture(new StoryTellerException("Failed to write pack index on device partition", e)); } } public CompletionStage<TransferStatus> downloadPack(String uuid, Path destPath, TransferProgressListener listener) { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } return readPackIndex() .thenCompose(packUUIDs -> CompletableFuture.supplyAsync(() -> { // Look for UUID in packs index Optional<UUID> matched = packUUIDs.stream().filter(p -> p.equals(UUID.fromString(uuid))).findFirst(); if (matched.isEmpty()) { throw new StoryTellerException("Pack not found"); } LOGGER.debug("Found pack with uuid: {}", uuid); // Generate folder name String folderName = transformUuid(uuid); Path sourceFolder = this.partitionMountPoint.resolve(CONTENT_FOLDER).resolve(folderName); LOGGER.trace("Downloading pack folder: {}", sourceFolder); if (Files.notExists(sourceFolder)) { throw new StoryTellerException("Pack folder not found"); } try { // Destination folder Path destFolder = destPath.resolve(uuid); // Copy folder with progress tracking return copyPackFolder(sourceFolder, destFolder, 2, new byte[0], listener); } catch (IOException e) { throw new StoryTellerException("Failed to copy pack from device", e); } })); } private static class FsDeviceInfosTransferStatus { private final FsDeviceInfos deviceInfos; private final TransferStatus status; public FsDeviceInfosTransferStatus(FsDeviceInfos deviceInfos, TransferStatus status) { this.deviceInfos = deviceInfos; this.status = status; } public FsDeviceInfos getDeviceInfos() { return this.deviceInfos; } public TransferStatus getStatus() { return this.status; } } public CompletionStage<TransferStatus> uploadPack(String uuid, Path inputPath, TransferProgressListener listener) { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } try { // Check free space long folderSize = FileUtils.getFolderSize(inputPath); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Pack folder size: {}", FileUtils.readableByteSize(folderSize)); } Path mdFile = this.partitionMountPoint.resolve(DEVICE_METADATA_FILENAME); long freeSpace = Files.getFileStore(mdFile).getUsableSpace(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("SD free space: {}", FileUtils.readableByteSize(freeSpace)); } if (freeSpace < folderSize) { throw new StoryTellerException("Not enough free space on the device"); } // Generate folder name String folderName = transformUuid(uuid); Path folderPath = this.partitionMountPoint.resolve(CONTENT_FOLDER).resolve(folderName); LOGGER.debug("Uploading pack to folder: {}", folderName); // Copy folder with progress tracking return getDeviceInfos().thenApplyAsync(deviceInfos -> { try { return new FsDeviceInfosTransferStatus( deviceInfos, copyPackFolder(inputPath, folderPath, deviceInfos.getFirmwareMajor(), deviceInfos.getDeviceKey(), listener) ); } catch (IOException e) { throw new StoryTellerException("Failed to copy pack from device", e); } }).thenApply(fsDeviceInfosTransferStatus -> { FsDeviceInfos deviceInfos = fsDeviceInfosTransferStatus.getDeviceInfos(); TransferStatus status = fsDeviceInfosTransferStatus.getStatus(); // When transfer is complete, generate device-specific boot file from device UUID LOGGER.debug("Generating device-specific boot file"); try { if (deviceInfos.getFirmwareMajor() == 3) { FsStoryPackWriterV3.addBootFile(folderPath, deviceInfos.getDeviceKey()); } else {
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package studio.driver.fs; public class FsStoryTellerAsyncDriver implements StoryTellerAsyncDriver<FsDeviceInfos, FsStoryPackInfos> { private static final Logger LOGGER = LogManager.getLogger(FsStoryTellerAsyncDriver.class); private static final String DEVICE_METADATA_FILENAME = ".md"; private static final String PACK_INDEX_FILENAME = ".pi"; private static final String CONTENT_FOLDER = ".content"; private static final String NODE_INDEX_FILENAME = "ni"; private static final String NIGHT_MODE_FILENAME = "nm"; private static final long FS_MOUNTPOINT_POLL_DELAY = 1000L; private static final long FS_MOUNTPOINT_RETRY = 10; private Device device = null; private Path partitionMountPoint = null; private List<DevicePluggedListener> pluggedlisteners = new ArrayList<>(); private List<DeviceUnpluggedListener> unpluggedlisteners = new ArrayList<>(); public FsStoryTellerAsyncDriver() { // Initialize libusb, handle and propagate hotplug events LOGGER.debug("Registering hotplug listener"); LibUsbDetectionHelper.initializeLibUsb(DeviceVersion.DEVICE_VERSION_2, // device2 -> { // Wait for a partition to be mounted which contains the .md file LOGGER.debug("Waiting for device partition..."); for (int i = 0; i < FS_MOUNTPOINT_RETRY && partitionMountPoint == null; i++) { try { Thread.sleep(FS_MOUNTPOINT_POLL_DELAY); DeviceUtils.listMountPoints().forEach(path -> { LOGGER.trace("Looking for .md in {}", path); if (Files.exists(path.resolve(DEVICE_METADATA_FILENAME))) { partitionMountPoint = path; LOGGER.info("FS device partition located: {}", partitionMountPoint); } }); } catch (InterruptedException e) { LOGGER.error("Failed to locate device partition", e); Thread.currentThread().interrupt(); } } if (partitionMountPoint == null) { throw new StoryTellerException("Could not locate device partition"); } // Update device reference FsStoryTellerAsyncDriver.this.device = device2; // Notify listeners FsStoryTellerAsyncDriver.this.pluggedlisteners.forEach(l -> l.onDevicePlugged(device2)); }, // device2 -> { // Update device reference FsStoryTellerAsyncDriver.this.device = null; FsStoryTellerAsyncDriver.this.partitionMountPoint = null; // Notify listeners FsStoryTellerAsyncDriver.this.unpluggedlisteners.forEach(l -> l.onDeviceUnplugged(device2)); }); } public void registerDeviceListener(DevicePluggedListener pluggedlistener, DeviceUnpluggedListener unpluggedlistener) { this.pluggedlisteners.add(pluggedlistener); this.unpluggedlisteners.add(unpluggedlistener); if (this.device != null) { pluggedlistener.onDevicePlugged(this.device); } } public CompletionStage<FsDeviceInfos> getDeviceInfos() { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } FsDeviceInfos infos = new FsDeviceInfos(); Path mdFile = this.partitionMountPoint.resolve(DEVICE_METADATA_FILENAME); LOGGER.trace("Reading device infos from file: {}", mdFile); try (DataInputStream is = new DataInputStream(new BufferedInputStream(Files.newInputStream(mdFile)))) { // SD card size and used space FileStore mdFd = Files.getFileStore(mdFile); long sdCardTotalSpace = mdFd.getTotalSpace(); long sdCardUsedSpace = mdFd.getTotalSpace() - mdFd.getUnallocatedSpace(); double percent = Math.round(100d * 100d * sdCardUsedSpace / sdCardTotalSpace) / 100d; infos.setSdCardSizeInBytes(sdCardTotalSpace); infos.setUsedSpaceInBytes(sdCardUsedSpace); if (LOGGER.isDebugEnabled()) { LOGGER.debug("SD card used : {}% ({} / {})", percent, FileUtils.readableByteSize(sdCardUsedSpace), FileUtils.readableByteSize(sdCardTotalSpace)); } // MD file format version short mdVersion = DeviceUtils.readLittleEndianShort(is); LOGGER.trace("Device metadata format version: {}", mdVersion); if (mdVersion >= 1 && mdVersion <= 4) { return this.getDeviceInfosMeta1to4(infos, is); } else if (mdVersion == 6) { return this.getDeviceInfosMeta6(infos, is); } else { return CompletableFuture.failedFuture(new StoryTellerException("Unsupported device metadata format version: " + mdVersion)); } } catch (IOException e) { return CompletableFuture.failedFuture(new StoryTellerException("Failed to read device metadata on partition", e)); } } public CompletionStage<FsDeviceInfos> getDeviceInfosMeta1to4(FsDeviceInfos infos, DataInputStream is) throws IOException { // Firmware version is.skipBytes(4); short major = DeviceUtils.readLittleEndianShort(is); short minor = DeviceUtils.readLittleEndianShort(is); infos.setFirmwareMajor(major); infos.setFirmwareMinor(minor); LOGGER.debug("Firmware version: {}.{}", major, minor); // Serial number String serialNumber = null; long sn = DeviceUtils.readBigEndianLong(is); if (sn != 0L && sn != -1L && sn != -4294967296L) { serialNumber = String.format("%014d", sn); LOGGER.debug("Serial Number: {}", serialNumber); } else { LOGGER.warn("No serial number in SPI"); } infos.setSerialNumber(serialNumber); // UUID is.skipBytes(238); byte[] deviceId = is.readNBytes(256); infos.setDeviceKey(deviceId); if (LOGGER.isDebugEnabled()) { LOGGER.debug("UUID: {}", SecurityUtils.encodeHex(deviceId)); } return CompletableFuture.completedFuture(infos); } public CompletionStage<FsDeviceInfos> getDeviceInfosMeta6(FsDeviceInfos infos, DataInputStream is) throws IOException { short major = DeviceUtils.readAsciiToShort(is, 1); is.skipBytes(1); short minor = DeviceUtils.readAsciiToShort(is, 1); infos.setFirmwareMajor(major); infos.setFirmwareMinor(minor); LOGGER.debug("Firmware version: " + major + "." + minor); // Serial number is.skipBytes(21); long sn = DeviceUtils.readAsciiToLong(is, 14); String serialNumber = String.format("%014d", sn); LOGGER.debug("Serial Number: " + serialNumber); infos.setSerialNumber(serialNumber); // UUID byte[] snb = String.valueOf(sn).getBytes(StandardCharsets.UTF_8); is.skipBytes(24); byte[] key = is.readNBytes(32); byte[] deviceKey = new byte[64]; System.arraycopy(snb, 0, deviceKey, 0 , 14); System.arraycopy(snb, 0, deviceKey, 24 , 8); System.arraycopy(key, 0, deviceKey, 32 , 32); infos.setDeviceKey(deviceKey); is.close(); return CompletableFuture.completedFuture(infos); } public CompletionStage<List<FsStoryPackInfos>> getPacksList() { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } return readPackIndex() .thenApply(packUUIDs -> { try { LOGGER.debug("Number of packs in index: {}", packUUIDs.size()); List<FsStoryPackInfos> packs = new ArrayList<>(); for (UUID packUUID : packUUIDs) { FsStoryPackInfos packInfos = new FsStoryPackInfos(); packInfos.setUuid(packUUID); LOGGER.debug("Pack UUID: {}", packUUID); // Compute .content folder (last 4 bytes of UUID) String folderName = transformUuid(packUUID.toString()); Path packPath = this.partitionMountPoint.resolve(CONTENT_FOLDER).resolve(folderName); packInfos.setFolderName(folderName); // Open 'ni' file Path niPath = packPath.resolve(NODE_INDEX_FILENAME); try (InputStream niDis = new BufferedInputStream(Files.newInputStream(niPath))) { ByteBuffer bb = ByteBuffer.wrap(niDis.readNBytes(512)).order(ByteOrder.LITTLE_ENDIAN); short version = bb.getShort(2); packInfos.setVersion(version); LOGGER.debug("Pack version: {}", version); } // Night mode is available if file 'nm' exists packInfos.setNightModeAvailable(Files.exists(packPath.resolve(NIGHT_MODE_FILENAME))); // Compute folder size packInfos.setSizeInBytes(FileUtils.getFolderSize(packPath)); packs.add(packInfos); } return packs; } catch (IOException e) { throw new StoryTellerException("Failed to read pack metadata on device partition", e); } }); } private CompletionStage<List<UUID>> readPackIndex() { return CompletableFuture.supplyAsync(() -> { List<UUID> packUUIDs = new ArrayList<>(); Path piFile = this.partitionMountPoint.resolve(PACK_INDEX_FILENAME); LOGGER.trace("Reading packs index from file: {}", piFile); try { ByteBuffer bb = ByteBuffer.wrap(Files.readAllBytes(piFile)); while (bb.hasRemaining()) { long high = bb.getLong(); long low = bb.getLong(); packUUIDs.add(new UUID(high, low)); } return packUUIDs; } catch (IOException e) { throw new StoryTellerException("Failed to read pack index on device partition", e); } }); } public CompletionStage<Boolean> reorderPacks(List<String> uuids) { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } return readPackIndex() .thenCompose(packUUIDs -> { try { boolean allUUIDsAreOnDevice = uuids.stream() .allMatch(uuid -> packUUIDs.stream().anyMatch(p -> p.equals(UUID.fromString(uuid)))); if (allUUIDsAreOnDevice) { // Reorder list according to uuids list packUUIDs.sort(Comparator.comparingInt(p -> uuids.indexOf(p.toString()))); // Write pack index return writePackIndex(packUUIDs); } else { throw new StoryTellerException("Packs on device do not match UUIDs"); } } catch (Exception e) { throw new StoryTellerException("Failed to read pack metadata on device partition", e); } }); } public CompletionStage<Boolean> deletePack(String uuid) { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } return readPackIndex() .thenCompose(packUUIDs -> { try { // Look for UUID in packs index Optional<UUID> matched = packUUIDs.stream().filter(p -> p.equals(UUID.fromString(uuid))).findFirst(); if (matched.isPresent()) { LOGGER.debug("Found pack with uuid: {}", uuid); // Remove from index packUUIDs.remove(matched.get()); // Write pack index return writePackIndex(packUUIDs) .thenCompose(ok -> { // Generate folder name String folderName = transformUuid(uuid); Path folderPath = this.partitionMountPoint.resolve(CONTENT_FOLDER).resolve(folderName); LOGGER.debug("Removing pack folder: {}", folderPath); try { FileUtils.deleteDirectory(folderPath); return CompletableFuture.completedFuture(ok); } catch (IOException e) { return CompletableFuture.failedFuture(new StoryTellerException("Failed to delete pack folder on device partition", e)); } }); } else { throw new StoryTellerException("Pack not found"); } } catch (Exception e) { throw new StoryTellerException("Failed to read pack metadata on device partition", e); } }); } private CompletionStage<Boolean> writePackIndex(List<UUID> packUUIDs) { try { Path piFile = this.partitionMountPoint.resolve(PACK_INDEX_FILENAME); LOGGER.trace("Replacing pack index file: {}", piFile); ByteBuffer bb = ByteBuffer.allocate(16 * packUUIDs.size()); for (UUID packUUID : packUUIDs) { bb.putLong(packUUID.getMostSignificantBits()); bb.putLong(packUUID.getLeastSignificantBits()); } Files.write(piFile, bb.array()); return CompletableFuture.completedFuture(true); } catch (Exception e) { return CompletableFuture.failedFuture(new StoryTellerException("Failed to write pack index on device partition", e)); } } public CompletionStage<TransferStatus> downloadPack(String uuid, Path destPath, TransferProgressListener listener) { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } return readPackIndex() .thenCompose(packUUIDs -> CompletableFuture.supplyAsync(() -> { // Look for UUID in packs index Optional<UUID> matched = packUUIDs.stream().filter(p -> p.equals(UUID.fromString(uuid))).findFirst(); if (matched.isEmpty()) { throw new StoryTellerException("Pack not found"); } LOGGER.debug("Found pack with uuid: {}", uuid); // Generate folder name String folderName = transformUuid(uuid); Path sourceFolder = this.partitionMountPoint.resolve(CONTENT_FOLDER).resolve(folderName); LOGGER.trace("Downloading pack folder: {}", sourceFolder); if (Files.notExists(sourceFolder)) { throw new StoryTellerException("Pack folder not found"); } try { // Destination folder Path destFolder = destPath.resolve(uuid); // Copy folder with progress tracking return copyPackFolder(sourceFolder, destFolder, 2, new byte[0], listener); } catch (IOException e) { throw new StoryTellerException("Failed to copy pack from device", e); } })); } private static class FsDeviceInfosTransferStatus { private final FsDeviceInfos deviceInfos; private final TransferStatus status; public FsDeviceInfosTransferStatus(FsDeviceInfos deviceInfos, TransferStatus status) { this.deviceInfos = deviceInfos; this.status = status; } public FsDeviceInfos getDeviceInfos() { return this.deviceInfos; } public TransferStatus getStatus() { return this.status; } } public CompletionStage<TransferStatus> uploadPack(String uuid, Path inputPath, TransferProgressListener listener) { if (this.device == null || this.partitionMountPoint == null) { return CompletableFuture.failedFuture(noDevicePluggedException()); } try { // Check free space long folderSize = FileUtils.getFolderSize(inputPath); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Pack folder size: {}", FileUtils.readableByteSize(folderSize)); } Path mdFile = this.partitionMountPoint.resolve(DEVICE_METADATA_FILENAME); long freeSpace = Files.getFileStore(mdFile).getUsableSpace(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("SD free space: {}", FileUtils.readableByteSize(freeSpace)); } if (freeSpace < folderSize) { throw new StoryTellerException("Not enough free space on the device"); } // Generate folder name String folderName = transformUuid(uuid); Path folderPath = this.partitionMountPoint.resolve(CONTENT_FOLDER).resolve(folderName); LOGGER.debug("Uploading pack to folder: {}", folderName); // Copy folder with progress tracking return getDeviceInfos().thenApplyAsync(deviceInfos -> { try { return new FsDeviceInfosTransferStatus( deviceInfos, copyPackFolder(inputPath, folderPath, deviceInfos.getFirmwareMajor(), deviceInfos.getDeviceKey(), listener) ); } catch (IOException e) { throw new StoryTellerException("Failed to copy pack from device", e); } }).thenApply(fsDeviceInfosTransferStatus -> { FsDeviceInfos deviceInfos = fsDeviceInfosTransferStatus.getDeviceInfos(); TransferStatus status = fsDeviceInfosTransferStatus.getStatus(); // When transfer is complete, generate device-specific boot file from device UUID LOGGER.debug("Generating device-specific boot file"); try { if (deviceInfos.getFirmwareMajor() == 3) { FsStoryPackWriterV3.addBootFile(folderPath, deviceInfos.getDeviceKey()); } else {
FsStoryPackWriter.addBootFile(folderPath, deviceInfos.getDeviceKey());
6
2023-12-14 15:08:35+00:00
16k
Patbox/PolyDecorations
src/main/java/eu/pb4/polydecorations/block/DecorationsBlocks.java
[ { "identifier": "ModInit", "path": "src/main/java/eu/pb4/polydecorations/ModInit.java", "snippet": "public class ModInit implements ModInitializer {\n\tpublic static final String ID = \"polydecorations\";\n\tpublic static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMet...
import eu.pb4.polydecorations.ModInit; import eu.pb4.polydecorations.block.furniture.BenchBlock; import eu.pb4.polydecorations.block.furniture.LargeFlowerPotBlock; import eu.pb4.polydecorations.block.item.DisplayCaseBlock; import eu.pb4.polydecorations.block.item.ShelfBlock; import eu.pb4.polydecorations.block.furniture.BrazierBlock; import eu.pb4.polydecorations.block.item.GlobeBlock; import eu.pb4.polydecorations.block.extension.SignPostBlock; import eu.pb4.polydecorations.block.extension.WallAttachedLanternBlock; import eu.pb4.polydecorations.util.WoodUtil; import eu.pb4.polymer.core.api.block.PolymerBlock; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.registry.RegistryEntryAddedCallback; import net.minecraft.block.*; import net.minecraft.block.enums.Instrument; import net.minecraft.loot.LootTable; import net.minecraft.registry.Registries; import net.minecraft.registry.Registry; import net.minecraft.server.MinecraftServer; import net.minecraft.util.DyeColor; import net.minecraft.util.Identifier; import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import static eu.pb4.polydecorations.ModInit.id;
12,029
package eu.pb4.polydecorations.block; public class DecorationsBlocks { private static final List<Block> BLOCKS = new ArrayList<>(); public static final WallAttachedLanternBlock WALL_LANTERN = register("wall_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.LANTERN)); public static final WallAttachedLanternBlock WALL_SOUL_LANTERN = register("wall_soul_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.SOUL_LANTERN)); public static final BrazierBlock BRAZIER = register("brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final BrazierBlock SOUL_BRAZIER = register("soul_brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.SOUL_LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.SOUL_CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final GlobeBlock GLOBE = register("globe", new GlobeBlock(AbstractBlock.Settings.copy(Blocks.OAK_PLANKS).nonOpaque())); public static final DisplayCaseBlock DISPLAY_CASE = register("display_case", new DisplayCaseBlock(AbstractBlock.Settings.copy(Blocks.GLASS).nonOpaque())); public static final LargeFlowerPotBlock LARGE_FLOWER_POT = register("large_flower_pot", new LargeFlowerPotBlock( AbstractBlock.Settings.create().mapColor(MapColor.ORANGE).instrument(Instrument.BASEDRUM).strength(1.25F).nonOpaque()));
package eu.pb4.polydecorations.block; public class DecorationsBlocks { private static final List<Block> BLOCKS = new ArrayList<>(); public static final WallAttachedLanternBlock WALL_LANTERN = register("wall_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.LANTERN)); public static final WallAttachedLanternBlock WALL_SOUL_LANTERN = register("wall_soul_lantern", new WallAttachedLanternBlock((LanternBlock) Blocks.SOUL_LANTERN)); public static final BrazierBlock BRAZIER = register("brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final BrazierBlock SOUL_BRAZIER = register("soul_brazier", new BrazierBlock(AbstractBlock.Settings.copy(Blocks.SOUL_LANTERN).nonOpaque().luminance(x -> { return x.get(BrazierBlock.LIT) ? Blocks.SOUL_CAMPFIRE.getDefaultState().getLuminance() : 0; })) ); public static final GlobeBlock GLOBE = register("globe", new GlobeBlock(AbstractBlock.Settings.copy(Blocks.OAK_PLANKS).nonOpaque())); public static final DisplayCaseBlock DISPLAY_CASE = register("display_case", new DisplayCaseBlock(AbstractBlock.Settings.copy(Blocks.GLASS).nonOpaque())); public static final LargeFlowerPotBlock LARGE_FLOWER_POT = register("large_flower_pot", new LargeFlowerPotBlock( AbstractBlock.Settings.create().mapColor(MapColor.ORANGE).instrument(Instrument.BASEDRUM).strength(1.25F).nonOpaque()));
public static final Map<WoodType, ShelfBlock> SHELF = registerWood("shelf", (x) -> {
4
2023-12-10 16:20:36+00:00
16k
i-moonlight/Suricate
src/main/java/com/michelin/suricate/services/js/scheduler/JsExecutionScheduler.java
[ { "identifier": "JsExecutionDto", "path": "src/main/java/com/michelin/suricate/model/dto/js/JsExecutionDto.java", "snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = false)\n@ToString\npublic class JsExecutionDto extends AbstractDto {\n private String properties;\n pri...
import com.michelin.suricate.model.dto.js.JsExecutionDto; import com.michelin.suricate.model.dto.js.JsResultDto; import com.michelin.suricate.model.dto.js.WidgetVariableResponseDto; import com.michelin.suricate.model.entities.Project; import com.michelin.suricate.model.entities.ProjectGrid; import com.michelin.suricate.model.entities.ProjectWidget; import com.michelin.suricate.model.enums.WidgetStateEnum; import com.michelin.suricate.services.api.ProjectWidgetService; import com.michelin.suricate.services.api.WidgetService; import com.michelin.suricate.services.js.services.DashboardScheduleService; import com.michelin.suricate.services.js.services.JsExecutionService; import com.michelin.suricate.services.js.tasks.JsExecutionAsyncTask; import com.michelin.suricate.services.js.tasks.JsResultAsyncTask; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.jasypt.encryption.StringEncryptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional;
13,662
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.michelin.suricate.services.js.scheduler; /** * Class used to schedule the Js executions. */ @Slf4j @Service public class JsExecutionScheduler { private static final int EXECUTOR_POOL_SIZE = 60; private static final long JS_IMMEDIATE_EXECUTION_DELAY = 1L; private final Map<Long, Pair<WeakReference<ScheduledFuture<JsResultDto>>, WeakReference<ScheduledFuture<Void>>>> jsTasksByProjectWidgetId = new ConcurrentHashMap<>(); private ScheduledThreadPoolExecutor jsExecutionExecutor; private ScheduledThreadPoolExecutor jsResultExecutor; @Autowired private ApplicationContext applicationContext; @Lazy @Autowired private ProjectWidgetService projectWidgetService; @Autowired private WidgetService widgetService; @Autowired private JsExecutionService jsExecutionService; @Lazy @Autowired private DashboardScheduleService dashboardScheduleService; @Autowired @Qualifier("jasyptStringEncryptor") private StringEncryptor stringEncryptor; /** * Init the Js executors. */ @Transactional public void init() { log.debug("Initializing the JavaScript executors"); if (jsExecutionExecutor != null) { jsExecutionExecutor.shutdownNow(); } jsExecutionExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(EXECUTOR_POOL_SIZE); jsExecutionExecutor.setRemoveOnCancelPolicy(true); if (jsResultExecutor != null) { jsResultExecutor.shutdownNow(); } jsResultExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(EXECUTOR_POOL_SIZE); jsResultExecutor.setRemoveOnCancelPolicy(true); jsTasksByProjectWidgetId.clear(); projectWidgetService.resetProjectWidgetsState(); } /** * Schedule a list of Js executions. * * @param jsExecutionDtos The list of Js execution to schedule * @param startJsRequestNow Should the Js execution starts now or from the widget configured delay */ public void scheduleJsRequests(final List<JsExecutionDto> jsExecutionDtos, boolean startJsRequestNow) { try { jsExecutionDtos.forEach(jsExecRequest -> schedule(jsExecRequest, startJsRequestNow)); } catch (Exception e) { log.error("An error has occurred when scheduling a JavaScript request for a new project subscription", e); } } /** * Method used to schedule the Js execution updating the associated widget. * Checks if the given Js execution can be executed and set the widget in a pause state * if it cannot be. * If the widget was in a pause state from a previous execution, then set the widget in a running * state before executing the request. * Create an asynchronous task which will execute the Js execution and execute the widget. Schedule * this task according to the computed delay. * Create another asynchronous task which will wait for the result of the first task * (the result of the widget execution). * It waits during the whole duration set in the widget description as timeout. * * @param jsExecutionDto The Js execution * @param startJsRequestNow Should the Js execution starts now or from the widget configured delay */ public void schedule(final JsExecutionDto jsExecutionDto, final boolean startJsRequestNow) { if (jsExecutionDto == null || jsExecutionExecutor == null || jsResultExecutor == null) { return; } log.debug("Scheduling the JavaScript execution of the widget instance {}", jsExecutionDto.getProjectWidgetId()); if (!jsExecutionService.isJsExecutable(jsExecutionDto)) { projectWidgetService.updateState(WidgetStateEnum.STOPPED, jsExecutionDto.getProjectWidgetId(), new Date()); return; } if (WidgetStateEnum.STOPPED == jsExecutionDto.getWidgetState()) { log.debug( "The widget instance {} of the JavaScript execution was stopped. " + "Setting the widget instance to running", jsExecutionDto.getProjectWidgetId()); projectWidgetService.updateState(WidgetStateEnum.RUNNING, jsExecutionDto.getProjectWidgetId(), new Date()); }
/* * Copyright 2012-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.michelin.suricate.services.js.scheduler; /** * Class used to schedule the Js executions. */ @Slf4j @Service public class JsExecutionScheduler { private static final int EXECUTOR_POOL_SIZE = 60; private static final long JS_IMMEDIATE_EXECUTION_DELAY = 1L; private final Map<Long, Pair<WeakReference<ScheduledFuture<JsResultDto>>, WeakReference<ScheduledFuture<Void>>>> jsTasksByProjectWidgetId = new ConcurrentHashMap<>(); private ScheduledThreadPoolExecutor jsExecutionExecutor; private ScheduledThreadPoolExecutor jsResultExecutor; @Autowired private ApplicationContext applicationContext; @Lazy @Autowired private ProjectWidgetService projectWidgetService; @Autowired private WidgetService widgetService; @Autowired private JsExecutionService jsExecutionService; @Lazy @Autowired private DashboardScheduleService dashboardScheduleService; @Autowired @Qualifier("jasyptStringEncryptor") private StringEncryptor stringEncryptor; /** * Init the Js executors. */ @Transactional public void init() { log.debug("Initializing the JavaScript executors"); if (jsExecutionExecutor != null) { jsExecutionExecutor.shutdownNow(); } jsExecutionExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(EXECUTOR_POOL_SIZE); jsExecutionExecutor.setRemoveOnCancelPolicy(true); if (jsResultExecutor != null) { jsResultExecutor.shutdownNow(); } jsResultExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(EXECUTOR_POOL_SIZE); jsResultExecutor.setRemoveOnCancelPolicy(true); jsTasksByProjectWidgetId.clear(); projectWidgetService.resetProjectWidgetsState(); } /** * Schedule a list of Js executions. * * @param jsExecutionDtos The list of Js execution to schedule * @param startJsRequestNow Should the Js execution starts now or from the widget configured delay */ public void scheduleJsRequests(final List<JsExecutionDto> jsExecutionDtos, boolean startJsRequestNow) { try { jsExecutionDtos.forEach(jsExecRequest -> schedule(jsExecRequest, startJsRequestNow)); } catch (Exception e) { log.error("An error has occurred when scheduling a JavaScript request for a new project subscription", e); } } /** * Method used to schedule the Js execution updating the associated widget. * Checks if the given Js execution can be executed and set the widget in a pause state * if it cannot be. * If the widget was in a pause state from a previous execution, then set the widget in a running * state before executing the request. * Create an asynchronous task which will execute the Js execution and execute the widget. Schedule * this task according to the computed delay. * Create another asynchronous task which will wait for the result of the first task * (the result of the widget execution). * It waits during the whole duration set in the widget description as timeout. * * @param jsExecutionDto The Js execution * @param startJsRequestNow Should the Js execution starts now or from the widget configured delay */ public void schedule(final JsExecutionDto jsExecutionDto, final boolean startJsRequestNow) { if (jsExecutionDto == null || jsExecutionExecutor == null || jsResultExecutor == null) { return; } log.debug("Scheduling the JavaScript execution of the widget instance {}", jsExecutionDto.getProjectWidgetId()); if (!jsExecutionService.isJsExecutable(jsExecutionDto)) { projectWidgetService.updateState(WidgetStateEnum.STOPPED, jsExecutionDto.getProjectWidgetId(), new Date()); return; } if (WidgetStateEnum.STOPPED == jsExecutionDto.getWidgetState()) { log.debug( "The widget instance {} of the JavaScript execution was stopped. " + "Setting the widget instance to running", jsExecutionDto.getProjectWidgetId()); projectWidgetService.updateState(WidgetStateEnum.RUNNING, jsExecutionDto.getProjectWidgetId(), new Date()); }
ProjectWidget projectWidget = projectWidgetService
5
2023-12-11 11:28:37+00:00
16k
i-moonlight/Beluga
server/src/main/java/com/amnesica/belugaproject/services/aircraft/AircraftService.java
[ { "identifier": "Configuration", "path": "server/src/main/java/com/amnesica/belugaproject/config/Configuration.java", "snippet": "@Data\n@Slf4j\n@Validated\n@ConstructorBinding\n@org.springframework.context.annotation.Configuration\npublic class Configuration {\n\n @Autowired\n private Environment...
import com.amnesica.belugaproject.config.Configuration; import com.amnesica.belugaproject.config.Feeder; import com.amnesica.belugaproject.entities.aircraft.Aircraft; import com.amnesica.belugaproject.entities.aircraft.AircraftSuperclass; import com.amnesica.belugaproject.entities.aircraft.OpenskyAircraft; import com.amnesica.belugaproject.services.data.FlightrouteDataService; import com.amnesica.belugaproject.services.data.OperatorDataService; import com.amnesica.belugaproject.services.data.RegcodeDataService; import com.amnesica.belugaproject.services.helper.HelperService; import com.amnesica.belugaproject.services.helper.NetworkHandlerService; import com.amnesica.belugaproject.services.trails.AircraftTrailService; import lombok.extern.slf4j.Slf4j; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Calendar;
10,834
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class AircraftService { @Autowired private RegcodeDataService regcodeDataService; @Autowired
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class AircraftService { @Autowired private RegcodeDataService regcodeDataService; @Autowired
private OperatorDataService operatorDataService;
6
2023-12-11 11:37:46+00:00
16k
netty/netty-incubator-codec-ohttp
codec-ohttp/src/test/java/io/netty/incubator/codec/ohttp/OHttpCodecsTest.java
[ { "identifier": "BinaryHttpRequest", "path": "codec-bhttp/src/main/java/io/netty/incubator/codec/bhttp/BinaryHttpRequest.java", "snippet": "public interface BinaryHttpRequest extends HttpRequest {\n\n /**\n * Returns the scheme used.\n *\n * @return scheme.\n */\n String scheme();\...
import io.netty.incubator.codec.bhttp.BinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultBinaryHttpResponse; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpRequest; import io.netty.incubator.codec.bhttp.DefaultFullBinaryHttpResponse; import io.netty.incubator.codec.bhttp.FullBinaryHttpRequest; import io.netty.incubator.codec.hpke.AEAD; import io.netty.incubator.codec.hpke.AsymmetricCipherKeyPair; import io.netty.incubator.codec.hpke.AsymmetricKeyParameter; import io.netty.incubator.codec.hpke.KDF; import io.netty.incubator.codec.hpke.KEM; import io.netty.incubator.codec.hpke.OHttpCryptoProvider; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.socket.ChannelInputShutdownEvent; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultHttpResponse; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpUtil; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.logging.LoggingHandler; import io.netty.incubator.codec.hpke.boringssl.BoringSSLHPKE; import io.netty.incubator.codec.hpke.boringssl.BoringSSLOHttpCryptoProvider; import io.netty.incubator.codec.hpke.bouncycastle.BouncyCastleOHttpCryptoProvider; import io.netty.util.ReferenceCountUtil; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; import java.nio.charset.StandardCharsets; import java.security.Security; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue;
14,383
void testContent(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Collections.singletonList(new DefaultFullBinaryHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "https", "foo.bar", "/test", strToBuf("THIS IS MY BODY"))), Arrays.asList(new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "/test"), new DefaultHttpContent(strToBuf("THIS IS MY BODY")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("RESPONSE"))), Arrays.asList(new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("RESPONSE")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testContentChunked(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { assumeTrue(version != OHttpVersionDraft.INSTANCE); ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))), Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))) ); testTransferFlow(client, server, false, Collections.singletonList(new DefaultHttpContent(strToBuf("222"))), Collections.singletonList(new DefaultHttpContent(strToBuf("222"))) ); testTransferFlow(client, server, true, Collections.singletonList(new DefaultHttpContent(strToBuf("333"))), Collections.singletonList(new DefaultHttpContent(strToBuf("333"))) ); testTransferFlow(server, client, false, Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultHttpContent(strToBuf("555"))), Collections.singletonList(new DefaultHttpContent(strToBuf("555"))) ); testTransferFlow(server, client, true, Collections.singletonList(new DefaultHttpContent(strToBuf("666"))), Collections.singletonList(new DefaultHttpContent(strToBuf("666"))) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testCodec(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Collections.singletonList(newFullRequestWithHeaders("/test", strToBuf("request body"))), Arrays.asList(newRequestWithHeaders("/test", false), new DefaultHttpContent(strToBuf("request body")), new DefaultLastHttpContent())); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("response body"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("response body")), new DefaultLastHttpContent()) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); }
/* * Copyright 2023 The Netty Project * * The Netty Project 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: * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package io.netty.incubator.codec.ohttp; public class OHttpCodecsTest { private static final class OHttpVersionArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { List<Arguments> arguments = new ArrayList<>(); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); if (BoringSSLHPKE.isAvailable()) { arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); arguments.add(Arguments.of(OHttpVersionChunkDraft.INSTANCE, BouncyCastleOHttpCryptoProvider.INSTANCE, BoringSSLOHttpCryptoProvider.INSTANCE)); } return arguments.stream(); } } @BeforeAll public static void setupAll() { System.setProperty("io.netty.leakDetection.level", "paranoid"); Security.addProvider(new BouncyCastleProvider()); } private static void transfer(EmbeddedChannel writer, EmbeddedChannel reader) { for (;;) { ByteBuf buffer = writer.readOutbound(); if (buffer == null) { break; } reader.writeInbound(buffer); } } public interface ChannelPair { EmbeddedChannel client(); EmbeddedChannel server(); } public static ChannelPair createChannelPair(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { AsymmetricCipherKeyPair kpR = OHttpCryptoTest.createX25519KeyPair(serverProvider, "3c168975674b2fa8e465970b79c8dcf09f1c741626480bd4c6162fc5b6a98e1a"); byte keyId = 0x66; OHttpServerKeys serverKeys = new OHttpServerKeys( OHttpKey.newPrivateKey( keyId, KEM.X25519_SHA256, Arrays.asList( OHttpKey.newCipher(KDF.HKDF_SHA256, AEAD.AES_GCM128), OHttpKey.newCipher(KDF.HKDF_SHA256, AEAD.CHACHA20_POLY1305)), kpR)); OHttpCiphersuite ciphersuite = new OHttpCiphersuite(keyId, KEM.X25519_SHA256, KDF.HKDF_SHA256, AEAD.AES_GCM128); AsymmetricKeyParameter publicKey = clientProvider.deserializePublicKey( KEM.X25519_SHA256, kpR.publicParameters().encoded()); return new ChannelPair() { @Override public EmbeddedChannel client() { return createClientChannel(version, clientProvider, ciphersuite, publicKey); } @Override public EmbeddedChannel server() { return createServerChannel(serverProvider, serverKeys); } }; } private static EmbeddedChannel createClientChannel(OHttpVersion version, OHttpCryptoProvider cryptoProvider, OHttpCiphersuite ciphersuite, AsymmetricKeyParameter publicKey) { return new EmbeddedChannel( new LoggingHandler("CLIENT-RAW"), new HttpClientCodec(), new LoggingHandler("CLIENT-OUTER"), new OHttpClientCodec(cryptoProvider, __ -> OHttpClientCodec.EncapsulationParameters.newInstance(version, ciphersuite, publicKey, "/ohttp", "autority")), new LoggingHandler("CLIENT-INNER")); } private static EmbeddedChannel createServerChannel(OHttpCryptoProvider cryptoProvider, OHttpServerKeys keys) { return new EmbeddedChannel( new LoggingHandler("SERVER-RAW"), new HttpServerCodec(), new LoggingHandler("SERVER-OUTER"), new OHttpServerCodec(cryptoProvider, keys), new LoggingHandler("SERVER-INNER")); } public static void testTransferFlow(EmbeddedChannel sender, EmbeddedChannel receiver, boolean shutdownReceiverInput, List<HttpObject> sentPieces, List<HttpObject> expectedReceivedPieces) { for (HttpObject obj : sentPieces) { sender.writeOutbound(obj); } transfer(sender, receiver); if (shutdownReceiverInput) { receiver.pipeline().fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE); } for (HttpObject expected : expectedReceivedPieces) { HttpObject received = receiver.readInbound(); assertNotNull(received); assertEquals(expected, received); if (expected instanceof HttpContent) { assertEquals(((HttpContent) expected).content(), ((HttpContent) received).content()); } ReferenceCountUtil.release(expected); ReferenceCountUtil.release(received); } assertTrue(receiver.inboundMessages().isEmpty()); assertTrue(receiver.outboundMessages().isEmpty()); } public static ByteBuf strToBuf(String str) { return Unpooled.directBuffer().writeBytes(str.getBytes(StandardCharsets.US_ASCII)); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testContent(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Collections.singletonList(new DefaultFullBinaryHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "https", "foo.bar", "/test", strToBuf("THIS IS MY BODY"))), Arrays.asList(new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "/test"), new DefaultHttpContent(strToBuf("THIS IS MY BODY")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("RESPONSE"))), Arrays.asList(new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("RESPONSE")), new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER)) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testContentChunked(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { assumeTrue(version != OHttpVersionDraft.INSTANCE); ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))), Arrays.asList(newRequestWithHeaders("test", true), new DefaultHttpContent(strToBuf("111"))) ); testTransferFlow(client, server, false, Collections.singletonList(new DefaultHttpContent(strToBuf("222"))), Collections.singletonList(new DefaultHttpContent(strToBuf("222"))) ); testTransferFlow(client, server, true, Collections.singletonList(new DefaultHttpContent(strToBuf("333"))), Collections.singletonList(new DefaultHttpContent(strToBuf("333"))) ); testTransferFlow(server, client, false, Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("444"))) ); testTransferFlow(server, client, false, Collections.singletonList(new DefaultHttpContent(strToBuf("555"))), Collections.singletonList(new DefaultHttpContent(strToBuf("555"))) ); testTransferFlow(server, client, true, Collections.singletonList(new DefaultHttpContent(strToBuf("666"))), Collections.singletonList(new DefaultHttpContent(strToBuf("666"))) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); } @ParameterizedTest @ArgumentsSource(value = OHttpVersionArgumentsProvider.class) void testCodec(OHttpVersion version, OHttpCryptoProvider clientProvider, OHttpCryptoProvider serverProvider) throws Exception { ChannelPair channels = createChannelPair(version, clientProvider, serverProvider); EmbeddedChannel client = channels.client(); EmbeddedChannel server = channels.server(); testTransferFlow(client, server, false, Collections.singletonList(newFullRequestWithHeaders("/test", strToBuf("request body"))), Arrays.asList(newRequestWithHeaders("/test", false), new DefaultHttpContent(strToBuf("request body")), new DefaultLastHttpContent())); testTransferFlow(server, client, false, Collections.singletonList(new DefaultFullBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, strToBuf("response body"))), Arrays.asList(new DefaultBinaryHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK), new DefaultHttpContent(strToBuf("response body")), new DefaultLastHttpContent()) ); client.finishAndReleaseAll(); server.finishAndReleaseAll(); }
public static BinaryHttpRequest newRequestWithHeaders(String path, boolean chunked) {
0
2023-12-06 09:14:09+00:00
16k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/tag/id3/AbstractID3v2Frame.java
[ { "identifier": "MP3File", "path": "android/src/main/java/org/jaudiotagger/audio/mp3/MP3File.java", "snippet": "public class MP3File extends AudioFile\n{\n private static final int MINIMUM_FILESIZE = 150;\n\n protected static AbstractTagDisplayFormatter tagFormatter;\n\n /**\n * the ID3v2 t...
import org.jaudiotagger.audio.mp3.MP3File; import org.jaudiotagger.tag.*; import org.jaudiotagger.tag.id3.framebody.AbstractID3v2FrameBody; import org.jaudiotagger.tag.id3.framebody.FrameBodyEncrypted; import org.jaudiotagger.tag.id3.framebody.FrameBodyUnsupported; import org.jaudiotagger.tag.id3.valuepair.TextEncoding; import org.jaudiotagger.utils.EqualsUtil; import java.io.ByteArrayOutputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.logging.Level;
14,325
/* * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.tag.id3; /** * This abstract class is each frame header inside a ID3v2 tag. * * @author : Paul Taylor * @author : Eric Farng * @version $Id$ */ public abstract class AbstractID3v2Frame extends AbstractTagFrame implements TagTextField { protected static final String TYPE_FRAME = "frame"; protected static final String TYPE_FRAME_SIZE = "frameSize"; protected static final String UNSUPPORTED_ID = "Unsupported"; //Frame identifier protected String identifier = ""; //Frame Size protected int frameSize; //The purpose of this is to provide the filename that should be used when writing debug messages //when problems occur reading or writing to file, otherwise it is difficult to track down the error //when processing many files private String loggingFilename = ""; /** * * @return size in bytes of the frameid field */ protected abstract int getFrameIdSize(); /** * * @return the size in bytes of the frame size field */ protected abstract int getFrameSizeSize(); /** * * @return the size in bytes of the frame header */ protected abstract int getFrameHeaderSize(); /** * Create an empty frame */ protected AbstractID3v2Frame() { } /** * This holds the Status flags (not supported in v2.20 */ StatusFlags statusFlags = null; /** * This holds the Encoding flags (not supported in v2.20) */ EncodingFlags encodingFlags = null; /** * Create a frame based on another frame * @param frame */ public AbstractID3v2Frame(AbstractID3v2Frame frame) { super(frame); } /** * Create a frame based on a body * @param body */ public AbstractID3v2Frame(AbstractID3v2FrameBody body) { this.frameBody = body; this.frameBody.setHeader(this); } /** * Create a new frame with empty body based on identifier * @param identifier */ //TODO the identifier checks should be done in the relevent subclasses public AbstractID3v2Frame(String identifier) { logger.config("Creating empty frame of type" + identifier); this.identifier = identifier; // Use reflection to map id to frame body, which makes things much easier // to keep things up to date. try { Class<AbstractID3v2FrameBody> c = (Class<AbstractID3v2FrameBody>) Class.forName("org.jaudiotagger.tag.id3.framebody.FrameBody" + identifier); frameBody = c.newInstance(); } catch (ClassNotFoundException cnfe) { logger.severe(cnfe.getMessage()); frameBody = new FrameBodyUnsupported(identifier); } //Instantiate Interface/Abstract should not happen catch (InstantiationException ie) { logger.log(Level.SEVERE, "InstantiationException:" + identifier, ie); throw new RuntimeException(ie); } //Private Constructor shouild not happen catch (IllegalAccessException iae) { logger.log(Level.SEVERE, "IllegalAccessException:" + identifier, iae); throw new RuntimeException(iae); } frameBody.setHeader(this); if (this instanceof ID3v24Frame) { frameBody.setTextEncoding(TagOptionSingleton.getInstance().getId3v24DefaultTextEncoding()); } else if (this instanceof ID3v23Frame) { frameBody.setTextEncoding(TagOptionSingleton.getInstance().getId3v23DefaultTextEncoding()); } logger.config("Created empty frame of type" + identifier); } /** * Retrieve the logging filename to be used in debugging * * @return logging filename to be used in debugging */ protected String getLoggingFilename() { return loggingFilename; } /** * Set logging filename when construct tag for read from file * * @param loggingFilename */ protected void setLoggingFilename(String loggingFilename) { this.loggingFilename = loggingFilename; } /** * Return the frame identifier, this only identifies the frame it does not provide a unique * key, when using frames such as TXXX which are used by many fields * * * @return the frame identifier (Tag Field Interface) */ //TODO, this is confusing only returns the frameId, which does not neccessarily uniquely //identify the frame public String getId() { return getIdentifier(); } /** * Return the frame identifier * * @return the frame identifier */ public String getIdentifier() { return identifier; } //TODO:needs implementing but not sure if this method is required at all public void copyContent(TagField field) { } /** * Read the frameBody when frame marked as encrypted * * @param identifier * @param byteBuffer * @param frameSize * @return * @throws InvalidFrameException * @throws InvalidDataTypeException * @throws InvalidTagException */ protected AbstractID3v2FrameBody readEncryptedBody(String identifier, ByteBuffer byteBuffer, int frameSize) throws InvalidFrameException, InvalidDataTypeException { try {
/* * MusicTag Copyright (C)2003,2004 * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser * General Public License as published by the Free Software Foundation; either version 2.1 of the License, * or (at your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jaudiotagger.tag.id3; /** * This abstract class is each frame header inside a ID3v2 tag. * * @author : Paul Taylor * @author : Eric Farng * @version $Id$ */ public abstract class AbstractID3v2Frame extends AbstractTagFrame implements TagTextField { protected static final String TYPE_FRAME = "frame"; protected static final String TYPE_FRAME_SIZE = "frameSize"; protected static final String UNSUPPORTED_ID = "Unsupported"; //Frame identifier protected String identifier = ""; //Frame Size protected int frameSize; //The purpose of this is to provide the filename that should be used when writing debug messages //when problems occur reading or writing to file, otherwise it is difficult to track down the error //when processing many files private String loggingFilename = ""; /** * * @return size in bytes of the frameid field */ protected abstract int getFrameIdSize(); /** * * @return the size in bytes of the frame size field */ protected abstract int getFrameSizeSize(); /** * * @return the size in bytes of the frame header */ protected abstract int getFrameHeaderSize(); /** * Create an empty frame */ protected AbstractID3v2Frame() { } /** * This holds the Status flags (not supported in v2.20 */ StatusFlags statusFlags = null; /** * This holds the Encoding flags (not supported in v2.20) */ EncodingFlags encodingFlags = null; /** * Create a frame based on another frame * @param frame */ public AbstractID3v2Frame(AbstractID3v2Frame frame) { super(frame); } /** * Create a frame based on a body * @param body */ public AbstractID3v2Frame(AbstractID3v2FrameBody body) { this.frameBody = body; this.frameBody.setHeader(this); } /** * Create a new frame with empty body based on identifier * @param identifier */ //TODO the identifier checks should be done in the relevent subclasses public AbstractID3v2Frame(String identifier) { logger.config("Creating empty frame of type" + identifier); this.identifier = identifier; // Use reflection to map id to frame body, which makes things much easier // to keep things up to date. try { Class<AbstractID3v2FrameBody> c = (Class<AbstractID3v2FrameBody>) Class.forName("org.jaudiotagger.tag.id3.framebody.FrameBody" + identifier); frameBody = c.newInstance(); } catch (ClassNotFoundException cnfe) { logger.severe(cnfe.getMessage()); frameBody = new FrameBodyUnsupported(identifier); } //Instantiate Interface/Abstract should not happen catch (InstantiationException ie) { logger.log(Level.SEVERE, "InstantiationException:" + identifier, ie); throw new RuntimeException(ie); } //Private Constructor shouild not happen catch (IllegalAccessException iae) { logger.log(Level.SEVERE, "IllegalAccessException:" + identifier, iae); throw new RuntimeException(iae); } frameBody.setHeader(this); if (this instanceof ID3v24Frame) { frameBody.setTextEncoding(TagOptionSingleton.getInstance().getId3v24DefaultTextEncoding()); } else if (this instanceof ID3v23Frame) { frameBody.setTextEncoding(TagOptionSingleton.getInstance().getId3v23DefaultTextEncoding()); } logger.config("Created empty frame of type" + identifier); } /** * Retrieve the logging filename to be used in debugging * * @return logging filename to be used in debugging */ protected String getLoggingFilename() { return loggingFilename; } /** * Set logging filename when construct tag for read from file * * @param loggingFilename */ protected void setLoggingFilename(String loggingFilename) { this.loggingFilename = loggingFilename; } /** * Return the frame identifier, this only identifies the frame it does not provide a unique * key, when using frames such as TXXX which are used by many fields * * * @return the frame identifier (Tag Field Interface) */ //TODO, this is confusing only returns the frameId, which does not neccessarily uniquely //identify the frame public String getId() { return getIdentifier(); } /** * Return the frame identifier * * @return the frame identifier */ public String getIdentifier() { return identifier; } //TODO:needs implementing but not sure if this method is required at all public void copyContent(TagField field) { } /** * Read the frameBody when frame marked as encrypted * * @param identifier * @param byteBuffer * @param frameSize * @return * @throws InvalidFrameException * @throws InvalidDataTypeException * @throws InvalidTagException */ protected AbstractID3v2FrameBody readEncryptedBody(String identifier, ByteBuffer byteBuffer, int frameSize) throws InvalidFrameException, InvalidDataTypeException { try {
AbstractID3v2FrameBody frameBody = new FrameBodyEncrypted(identifier,byteBuffer, frameSize);
2
2023-12-11 05:58:19+00:00
16k
xhtcode/xht-cloud-parent
xht-cloud-system/xht-cloud-system-service/src/main/java/com/xht/cloud/system/module/permissions/service/impl/SysRoleServiceImpl.java
[ { "identifier": "PageResponse", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/api/response/PageResponse.java", "snippet": "@Data\n@Schema(description = \"分页信息响应实体\")\npublic class PageResponse<T> extends Response {\n\n /**\n * 当前页\n */\n @...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.xht.cloud.framework.core.api.response.PageResponse; import com.xht.cloud.framework.exception.Assert; import com.xht.cloud.framework.exception.business.BizException; import com.xht.cloud.framework.mybatis.core.enums.DeptUserDataScopeEnum; import com.xht.cloud.framework.mybatis.tool.PageTool; import com.xht.cloud.framework.security.support.SecurityContextUtil; import com.xht.cloud.system.exceptions.PermissionException; import com.xht.cloud.system.manager.PermissionsManager; import com.xht.cloud.system.module.dept.convert.SysDeptConvert; import com.xht.cloud.system.module.dept.dao.dataobject.SysDeptDO; import com.xht.cloud.system.module.dept.dao.dataobject.SysRoleDeptDO; import com.xht.cloud.system.module.dept.dao.mapper.SysDeptMapper; import com.xht.cloud.system.module.dept.dao.mapper.SysRoleDeptMapper; import com.xht.cloud.system.module.dept.dao.wrapper.SysRoleDeptWrapper; import com.xht.cloud.system.module.permissions.controller.request.SysRoleAddRequest; import com.xht.cloud.system.module.permissions.controller.request.SysRoleQueryRequest; import com.xht.cloud.system.module.permissions.controller.request.SysRoleUpdateRequest; import com.xht.cloud.system.module.permissions.controller.response.SysRoleResponse; import com.xht.cloud.system.module.permissions.convert.SysRoleConvert; import com.xht.cloud.system.module.permissions.dao.dataobject.SysRoleDO; import com.xht.cloud.system.module.permissions.dao.dataobject.SysUserRoleDO; import com.xht.cloud.system.module.permissions.dao.mapper.SysRoleMapper; import com.xht.cloud.system.module.permissions.dao.mapper.SysUserRoleMapper; import com.xht.cloud.system.module.permissions.dao.wrapper.SysRoleWrapper; import com.xht.cloud.system.module.permissions.service.ISysRoleService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.CollectionUtils; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
11,151
package com.xht.cloud.system.module.permissions.service.impl; /** * 描述 :系统角色表 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysRoleServiceImpl implements ISysRoleService { private final SysRoleMapper sysRoleMapper; private final SysRoleConvert sysRoleConvert; private final SysDeptMapper sysDeptMapper; private final SysDeptConvert sysDeptConvert; private final SysRoleDeptMapper sysRoleDeptMapper; private final SysUserRoleMapper sysUserRoleMapper; private final PermissionsManager permissionsManager; /** * 创建 * * @param addRequest {@link SysRoleAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysRoleAddRequest addRequest) { SysRoleDO entity = sysRoleConvert.toDO(addRequest); sysRoleMapper.insert(entity); permissionsManager.saveRoleDept(entity.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, addRequest.getDeptIds()); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysRoleUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysRoleUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } SysRoleDO entity = sysRoleConvert.toDO(updateRequest); sysRoleDeptMapper.delete(SysRoleDeptWrapper.getInstance().lambdaQuery().eq(SysRoleDeptDO::getRoleId, entity.getId())); permissionsManager.saveRoleDept(updateRequest.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, updateRequest.getDeptIds()); sysRoleMapper.updateById(entity); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { long l = sysUserRoleMapper.selectCount(new LambdaQueryWrapper<SysUserRoleDO>().in(SysUserRoleDO::getRoleId, ids)); if (l > 0) { throw new PermissionException("该角色已绑定用户,请勿操作!"); } List<SysRoleDO> sysRoleDOS = sysRoleMapper.selectBatchIds(ids); if (CollectionUtils.isEmpty(ids) || sysRoleDOS.size() != ids.size()) { Assert.fail("业务异常删除失败!"); } SecurityContextUtil.isAdminRole(sysRoleDOS.stream().map(SysRoleDO::getRoleCode).collect(Collectors.toList())).orElseThrow(() -> new PermissionException("该角色是管理员角色,禁止删除!")); sysRoleMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysRoleResponse} */ @Override public SysRoleResponse findById(String id) { SysRoleResponse response = sysRoleConvert.toResponse(sysRoleMapper.findById(id).orElse(null)); if (Objects.nonNull(response)) { List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectDeptByRoleId(id); response.setDepts(sysDeptConvert.toResponse(sysDeptDOS)); } return response; } /** * 分页查询 * * @param queryRequest {@link SysRoleQueryRequest} * @return {@link PageResponse<SysRoleResponse>} 分页详情 */ @Override
package com.xht.cloud.system.module.permissions.service.impl; /** * 描述 :系统角色表 * * @author : xht **/ @Slf4j @Service @RequiredArgsConstructor public class SysRoleServiceImpl implements ISysRoleService { private final SysRoleMapper sysRoleMapper; private final SysRoleConvert sysRoleConvert; private final SysDeptMapper sysDeptMapper; private final SysDeptConvert sysDeptConvert; private final SysRoleDeptMapper sysRoleDeptMapper; private final SysUserRoleMapper sysUserRoleMapper; private final PermissionsManager permissionsManager; /** * 创建 * * @param addRequest {@link SysRoleAddRequest} * @return {@link String} 主键 */ @Override @Transactional(rollbackFor = Exception.class) public String create(SysRoleAddRequest addRequest) { SysRoleDO entity = sysRoleConvert.toDO(addRequest); sysRoleMapper.insert(entity); permissionsManager.saveRoleDept(entity.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, addRequest.getDeptIds()); return entity.getId(); } /** * 根据id修改 * * @param updateRequest SysRoleUpdateRequest */ @Override @Transactional(rollbackFor = Exception.class) public void update(SysRoleUpdateRequest updateRequest) { if (Objects.isNull(findById(updateRequest.getId()))) { throw new BizException("修改的对象不存在!"); } SysRoleDO entity = sysRoleConvert.toDO(updateRequest); sysRoleDeptMapper.delete(SysRoleDeptWrapper.getInstance().lambdaQuery().eq(SysRoleDeptDO::getRoleId, entity.getId())); permissionsManager.saveRoleDept(updateRequest.getId(), DeptUserDataScopeEnum.DATA_SCOPE_CUSTOM, updateRequest.getDeptIds()); sysRoleMapper.updateById(entity); } /** * 删除 * * @param ids {@link List<String>} id集合 */ @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> ids) { long l = sysUserRoleMapper.selectCount(new LambdaQueryWrapper<SysUserRoleDO>().in(SysUserRoleDO::getRoleId, ids)); if (l > 0) { throw new PermissionException("该角色已绑定用户,请勿操作!"); } List<SysRoleDO> sysRoleDOS = sysRoleMapper.selectBatchIds(ids); if (CollectionUtils.isEmpty(ids) || sysRoleDOS.size() != ids.size()) { Assert.fail("业务异常删除失败!"); } SecurityContextUtil.isAdminRole(sysRoleDOS.stream().map(SysRoleDO::getRoleCode).collect(Collectors.toList())).orElseThrow(() -> new PermissionException("该角色是管理员角色,禁止删除!")); sysRoleMapper.deleteBatchIds(ids); } /** * 根据id查询详细 * * @param id {@link String} 数据库主键 * @return {@link SysRoleResponse} */ @Override public SysRoleResponse findById(String id) { SysRoleResponse response = sysRoleConvert.toResponse(sysRoleMapper.findById(id).orElse(null)); if (Objects.nonNull(response)) { List<SysDeptDO> sysDeptDOS = sysDeptMapper.selectDeptByRoleId(id); response.setDepts(sysDeptConvert.toResponse(sysDeptDOS)); } return response; } /** * 分页查询 * * @param queryRequest {@link SysRoleQueryRequest} * @return {@link PageResponse<SysRoleResponse>} 分页详情 */ @Override
public PageResponse<SysRoleResponse> findPage(SysRoleQueryRequest queryRequest) {
15
2023-12-12 08:16:30+00:00
16k
serendipitk/LunarCore
src/main/java/emu/lunarcore/game/player/PlayerUnlockData.java
[ { "identifier": "GameConstants", "path": "src/main/java/emu/lunarcore/GameConstants.java", "snippet": "public class GameConstants {\n public static String VERSION = \"1.6.0\";\n \n public static final ZoneOffset CURRENT_ZONEOFFSET = ZoneOffset.systemDefault().getRules().getOffset(Instant.now())...
import dev.morphia.annotations.Entity; import dev.morphia.annotations.Id; import emu.lunarcore.GameConstants; import emu.lunarcore.LunarCore; import emu.lunarcore.data.GameData; import emu.lunarcore.game.avatar.GameAvatar; import emu.lunarcore.game.enums.PersonalizeShowType; import emu.lunarcore.server.packet.BasePacket; import emu.lunarcore.server.packet.send.PacketPlayerSyncScNotify; import emu.lunarcore.server.packet.send.PacketUnlockChatBubbleScNotify; import emu.lunarcore.server.packet.send.PacketUnlockPhoneThemeScNotify; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.ints.IntSet; import lombok.Getter;
11,840
package emu.lunarcore.game.player; @Getter @Entity(value = "unlocks", useDiscriminator = false) public class PlayerUnlockData { private transient Player owner; @Id private int ownerUid; private IntSet headIcons; private IntSet chatBubbles; private IntSet phoneThemes; @Deprecated // Morphia only public PlayerUnlockData() {} public PlayerUnlockData(Player player) { this.owner = player; this.ownerUid = player.getUid(); // Add default head icons for (int iconId : GameConstants.DEFAULT_HEAD_ICONS) { this.addHeadIcon(iconId); } // Add head icons from avatars we already have for (GameAvatar avatar : owner.getAvatars()) { this.addHeadIcon(avatar.getHeadIconId()); } // Add default chat bubble(s) for (var excel : GameData.getChatBubbleExcelMap().values()) { if (excel.getShowType() == PersonalizeShowType.Always) { this.addChatBubble(excel.getId()); } } // Add default phone theme(s) for (var excel : GameData.getPhoneThemeExcelMap().values()) { if (excel.getShowType() == PersonalizeShowType.Always) { this.addPhoneTheme(excel.getId()); } } this.save(); } protected void setOwner(Player player) { this.owner = player; } public IntSet getHeadIcons() { if (this.headIcons == null) { this.headIcons = new IntOpenHashSet(); } return this.headIcons; } public IntSet getChatBubbles() { if (this.chatBubbles == null) { this.chatBubbles = new IntOpenHashSet(); } return this.chatBubbles; } public IntSet getPhoneThemes() { if (this.phoneThemes == null) { this.phoneThemes = new IntOpenHashSet(); } return this.phoneThemes; } public void addHeadIcon(int headIconId) { boolean success = this.getHeadIcons().add(headIconId); if (success && this.getOwner().isLoggedIn()) { this.sendPacket(new PacketPlayerSyncScNotify(getOwner().toBoardData())); this.save(); } } public void addChatBubble(int chatBubbleId) { boolean success = this.getChatBubbles().add(chatBubbleId); if (success && this.getOwner().isLoggedIn()) { this.sendPacket(new PacketUnlockChatBubbleScNotify(chatBubbleId)); this.save(); } } public void addPhoneTheme(int phoneThemeId) { boolean success = this.getPhoneThemes().add(phoneThemeId); if (success && this.getOwner().isLoggedIn()) { this.sendPacket(new PacketUnlockPhoneThemeScNotify(phoneThemeId)); this.save(); } } private void sendPacket(BasePacket packet) { this.getOwner().sendPacket(packet); } public void save() {
package emu.lunarcore.game.player; @Getter @Entity(value = "unlocks", useDiscriminator = false) public class PlayerUnlockData { private transient Player owner; @Id private int ownerUid; private IntSet headIcons; private IntSet chatBubbles; private IntSet phoneThemes; @Deprecated // Morphia only public PlayerUnlockData() {} public PlayerUnlockData(Player player) { this.owner = player; this.ownerUid = player.getUid(); // Add default head icons for (int iconId : GameConstants.DEFAULT_HEAD_ICONS) { this.addHeadIcon(iconId); } // Add head icons from avatars we already have for (GameAvatar avatar : owner.getAvatars()) { this.addHeadIcon(avatar.getHeadIconId()); } // Add default chat bubble(s) for (var excel : GameData.getChatBubbleExcelMap().values()) { if (excel.getShowType() == PersonalizeShowType.Always) { this.addChatBubble(excel.getId()); } } // Add default phone theme(s) for (var excel : GameData.getPhoneThemeExcelMap().values()) { if (excel.getShowType() == PersonalizeShowType.Always) { this.addPhoneTheme(excel.getId()); } } this.save(); } protected void setOwner(Player player) { this.owner = player; } public IntSet getHeadIcons() { if (this.headIcons == null) { this.headIcons = new IntOpenHashSet(); } return this.headIcons; } public IntSet getChatBubbles() { if (this.chatBubbles == null) { this.chatBubbles = new IntOpenHashSet(); } return this.chatBubbles; } public IntSet getPhoneThemes() { if (this.phoneThemes == null) { this.phoneThemes = new IntOpenHashSet(); } return this.phoneThemes; } public void addHeadIcon(int headIconId) { boolean success = this.getHeadIcons().add(headIconId); if (success && this.getOwner().isLoggedIn()) { this.sendPacket(new PacketPlayerSyncScNotify(getOwner().toBoardData())); this.save(); } } public void addChatBubble(int chatBubbleId) { boolean success = this.getChatBubbles().add(chatBubbleId); if (success && this.getOwner().isLoggedIn()) { this.sendPacket(new PacketUnlockChatBubbleScNotify(chatBubbleId)); this.save(); } } public void addPhoneTheme(int phoneThemeId) { boolean success = this.getPhoneThemes().add(phoneThemeId); if (success && this.getOwner().isLoggedIn()) { this.sendPacket(new PacketUnlockPhoneThemeScNotify(phoneThemeId)); this.save(); } } private void sendPacket(BasePacket packet) { this.getOwner().sendPacket(packet); } public void save() {
LunarCore.getGameDatabase().save(this);
1
2023-12-08 14:13:04+00:00
16k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardentrees/integration/GardenCoreIntegration.java
[ { "identifier": "GardenCoreAPI", "path": "src/main/java/com/jaquadro/minecraft/gardencore/api/GardenCoreAPI.java", "snippet": "public final class GardenCoreAPI {\n\n private UniqueMetaSet smallFlameHostBlocks = new UniqueMetaSet();\n private List bonemealHandlers = new ArrayList();\n private st...
import com.jaquadro.minecraft.gardencore.api.GardenCoreAPI; import com.jaquadro.minecraft.gardencore.api.IBonemealHandler; import com.jaquadro.minecraft.gardencore.api.SaplingRegistry; import com.jaquadro.minecraft.gardencore.api.WoodRegistry; import com.jaquadro.minecraft.gardencore.block.BlockGarden; import com.jaquadro.minecraft.gardentrees.core.ModBlocks; import com.jaquadro.minecraft.gardentrees.world.gen.WorldGenStandardOrnTree; import cpw.mods.fml.common.Loader; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import net.minecraft.world.gen.feature.WorldGenerator; import net.minecraftforge.oredict.OreDictionary; import java.util.Iterator; import java.util.List;
10,823
package com.jaquadro.minecraft.gardentrees.integration; public class GardenCoreIntegration { public static final String MOD_ID = "GardenCore"; public static void init() { if (Loader.isModLoaded("GardenCore")) { SaplingRegistry saplingReg = SaplingRegistry.instance(); Item sapling = Item.getItemFromBlock(Blocks.sapling); saplingReg.putExtendedData(sapling, 0, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 0, Blocks.leaves, 0)); saplingReg.putExtendedData(sapling, 1, "sm_generator", WorldGenStandardOrnTree.SmallSpruceTree.FACTORY.create(Blocks.log, 1, Blocks.leaves, 1)); saplingReg.putExtendedData(sapling, 2, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 2, Blocks.leaves, 2)); saplingReg.putExtendedData(sapling, 3, "sm_generator", WorldGenStandardOrnTree.SmallJungleTree.FACTORY.create(Blocks.log, 3, Blocks.leaves, 3)); saplingReg.putExtendedData(sapling, 4, "sm_generator", WorldGenStandardOrnTree.SmallAcaciaTree.FACTORY.create(Blocks.log2, 0, Blocks.leaves2, 0)); saplingReg.putExtendedData(sapling, 5, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log2, 1, Blocks.leaves2, 1)); Item extSapling = Item.getItemFromBlock(ModBlocks.sapling); saplingReg.registerSapling(extSapling, 0, Blocks.log, 1, Blocks.leaves, 1); saplingReg.registerSapling(extSapling, 1, Blocks.log, 0, Blocks.leaves, 0); saplingReg.registerSapling(extSapling, 2, Blocks.log, 2, Blocks.leaves, 2); saplingReg.putExtendedData(extSapling, 0, "sm_generator", WorldGenStandardOrnTree.SmallSpruceTree.FACTORY.create(Blocks.log, 1, Blocks.leaves, 1)); saplingReg.putExtendedData(extSapling, 1, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 0, Blocks.leaves, 0)); saplingReg.putExtendedData(extSapling, 2, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 2, Blocks.leaves, 2)); GardenCoreAPI.instance().registerBonemealHandler(new GardenCoreIntegration.GardenBonemealHandler()); WoodRegistry woodRegistry = WoodRegistry.instance(); List woodList = OreDictionary.getOres("treeWood"); Iterator var5 = woodList.iterator(); while(var5.hasNext()) { ItemStack item = (ItemStack)var5.next(); if (item != null) { Block block = Block.getBlockFromItem(item.getItem()); woodRegistry.registerWoodType(block, item.getItemDamage()); } } } } private static class GardenBonemealHandler implements IBonemealHandler { private GardenBonemealHandler() { }
package com.jaquadro.minecraft.gardentrees.integration; public class GardenCoreIntegration { public static final String MOD_ID = "GardenCore"; public static void init() { if (Loader.isModLoaded("GardenCore")) { SaplingRegistry saplingReg = SaplingRegistry.instance(); Item sapling = Item.getItemFromBlock(Blocks.sapling); saplingReg.putExtendedData(sapling, 0, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 0, Blocks.leaves, 0)); saplingReg.putExtendedData(sapling, 1, "sm_generator", WorldGenStandardOrnTree.SmallSpruceTree.FACTORY.create(Blocks.log, 1, Blocks.leaves, 1)); saplingReg.putExtendedData(sapling, 2, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 2, Blocks.leaves, 2)); saplingReg.putExtendedData(sapling, 3, "sm_generator", WorldGenStandardOrnTree.SmallJungleTree.FACTORY.create(Blocks.log, 3, Blocks.leaves, 3)); saplingReg.putExtendedData(sapling, 4, "sm_generator", WorldGenStandardOrnTree.SmallAcaciaTree.FACTORY.create(Blocks.log2, 0, Blocks.leaves2, 0)); saplingReg.putExtendedData(sapling, 5, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log2, 1, Blocks.leaves2, 1)); Item extSapling = Item.getItemFromBlock(ModBlocks.sapling); saplingReg.registerSapling(extSapling, 0, Blocks.log, 1, Blocks.leaves, 1); saplingReg.registerSapling(extSapling, 1, Blocks.log, 0, Blocks.leaves, 0); saplingReg.registerSapling(extSapling, 2, Blocks.log, 2, Blocks.leaves, 2); saplingReg.putExtendedData(extSapling, 0, "sm_generator", WorldGenStandardOrnTree.SmallSpruceTree.FACTORY.create(Blocks.log, 1, Blocks.leaves, 1)); saplingReg.putExtendedData(extSapling, 1, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 0, Blocks.leaves, 0)); saplingReg.putExtendedData(extSapling, 2, "sm_generator", WorldGenStandardOrnTree.SmallOakTree.FACTORY.create(Blocks.log, 2, Blocks.leaves, 2)); GardenCoreAPI.instance().registerBonemealHandler(new GardenCoreIntegration.GardenBonemealHandler()); WoodRegistry woodRegistry = WoodRegistry.instance(); List woodList = OreDictionary.getOres("treeWood"); Iterator var5 = woodList.iterator(); while(var5.hasNext()) { ItemStack item = (ItemStack)var5.next(); if (item != null) { Block block = Block.getBlockFromItem(item.getItem()); woodRegistry.registerWoodType(block, item.getItemDamage()); } } } } private static class GardenBonemealHandler implements IBonemealHandler { private GardenBonemealHandler() { }
public boolean applyBonemeal(World world, int x, int y, int z, BlockGarden hostBlock, int slot) {
4
2023-12-12 08:13:16+00:00
16k
Zergatul/java-scripting-language
src/test/java/com/zergatul/scripting/tests/MethodOverloadsTest.java
[ { "identifier": "ScriptingLanguageCompiler", "path": "src/main/java/com/zergatul/scripting/compiler/ScriptingLanguageCompiler.java", "snippet": "public class ScriptingLanguageCompiler {\r\n\r\n private static AtomicInteger counter = new AtomicInteger(0);\r\n private static ScriptingClassLoader cla...
import com.zergatul.scripting.compiler.ScriptingLanguageCompiler; import com.zergatul.scripting.helpers.FloatStorage; import com.zergatul.scripting.helpers.StringStorage; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List;
13,645
package com.zergatul.scripting.tests; public class MethodOverloadsTest { @BeforeEach public void clean() { ApiRoot.floatStorage = new FloatStorage(); ApiRoot.stringStorage = new StringStorage(); } @Test public void simpleTest() throws Exception { String code = """ stringStorage.add(methods.toString(0)); stringStorage.add(methods.toString(0.0)); """;
package com.zergatul.scripting.tests; public class MethodOverloadsTest { @BeforeEach public void clean() { ApiRoot.floatStorage = new FloatStorage(); ApiRoot.stringStorage = new StringStorage(); } @Test public void simpleTest() throws Exception { String code = """ stringStorage.add(methods.toString(0)); stringStorage.add(methods.toString(0.0)); """;
ScriptingLanguageCompiler compiler = new ScriptingLanguageCompiler(ApiRoot.class);
0
2023-12-10 00:37:27+00:00
16k
mklemmingen/senet-boom
core/src/com/senetboom/game/frontend/special/moveBotTile.java
[ { "identifier": "SenetBoom", "path": "core/src/com/senetboom/game/SenetBoom.java", "snippet": "public class SenetBoom extends ApplicationAdapter {\n\n\t// for the stage the bot moves a piece on\n\tpublic static Group botMovingStage;\n\n\t// for the empty tile texture\n\tpublic static Texture emptyTextur...
import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.ui.Image; import com.badlogic.gdx.scenes.scene2d.ui.Stack; import com.senetboom.game.SenetBoom; import com.senetboom.game.backend.Board; import com.senetboom.game.backend.Coordinate; import com.senetboom.game.backend.Piece; import com.senetboom.game.backend.Tile; import static com.senetboom.game.SenetBoom.tileSize;
10,993
package com.senetboom.game.frontend.special; public class moveBotTile { /* * This class is used to simulate the dragging of a piece by the bot. It slowly moves an image * of the soldier along the white line */ // properties for beginning and end coordinates public int start; public int end;
package com.senetboom.game.frontend.special; public class moveBotTile { /* * This class is used to simulate the dragging of a piece by the bot. It slowly moves an image * of the soldier along the white line */ // properties for beginning and end coordinates public int start; public int end;
private Coordinate startPx;
2
2023-12-05 22:19:00+00:00
16k
sinbad-navigator/erp-crm
auth/src/main/java/com/ec/auth/web/service/SysRegisterService.java
[ { "identifier": "Constants", "path": "common/src/main/java/com/ec/common/constant/Constants.java", "snippet": "public class Constants {\n /**\n * UTF-8 字符集\n */\n public static final String UTF8 = \"UTF-8\";\n\n /**\n * GBK 字符集\n */\n public static final String GBK = \"GBK\";...
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.ec.common.constant.Constants; import com.ec.common.constant.UserConstants; import com.ec.common.core.domain.entity.SysUser; import com.ec.common.core.domain.model.RegisterBody; import com.ec.common.core.redis.RedisCache; import com.ec.common.exception.user.CaptchaException; import com.ec.common.exception.user.CaptchaExpireException; import com.ec.common.utils.MessageUtils; import com.ec.common.utils.SecurityUtils; import com.ec.common.utils.StringUtils; import com.ec.auth.manager.AsyncManager; import com.ec.auth.manager.factory.AsyncFactory; import com.ec.sys.service.ISysConfigService; import com.ec.sys.service.ISysUserService;
13,043
package com.ec.auth.web.service; /** * 注册校验方法 * * @author ec */ @Component public class SysRegisterService { @Autowired
package com.ec.auth.web.service; /** * 注册校验方法 * * @author ec */ @Component public class SysRegisterService { @Autowired
private ISysUserService userService;
13
2023-12-07 14:23:12+00:00
16k