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
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/query/Q3.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 config.CommonConfig.DB_OCEANBASE;
14,180
package benchmark.olap.query; public class Q3 extends baseQuery { private static final Logger log = Logger.getLogger(Q3.class); public double k; public double b; private final int dbType; public Q3(int dbType) throws ParseException { super(); this.filterRate = benchmark.olap.OLAPClient.filterRate[2]; //0.0480 this.dbType = dbType;
package benchmark.olap.query; public class Q3 extends baseQuery { private static final Logger log = Logger.getLogger(Q3.class); public double k; public double b; private final int dbType; public Q3(int dbType) throws ParseException { super(); this.filterRate = benchmark.olap.OLAPClient.filterRate[2]; //0.0480 this.dbType = dbType;
this.k = OLTPClient.k2;
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,127
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(
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",
9
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;
11,039
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()); output = new PrintWriter(callbacks.getStdout(), true); // create our UI SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initComponents(); // customize our UI components callbacks.customizeUiComponent(tab.panel); // add the custom tab to Burp's UI callbacks.addSuiteTab(tab.tb);
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()); output = new PrintWriter(callbacks.getStdout(), true); // create our UI SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initComponents(); // customize our UI components callbacks.customizeUiComponent(tab.panel); // add the custom tab to Burp's UI callbacks.addSuiteTab(tab.tb);
callbacks.registerContextMenuFactory(new menuItem());
1
2023-10-23 12:13:00+00:00
16k
RoessinghResearch/senseeact
SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/compat/UserV7.java
[ { "identifier": "Gender", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/Gender.java", "snippet": "public enum Gender {\n\tMALE,\n\tFEMALE,\n\tOTHER\n}" }, { "identifier": "MaritalStatus", "path": "SenSeeActClient/src/main/java/nl/rrd/senseeact/client/model/MaritalStatu...
import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import nl.rrd.utils.json.SqlDateDeserializer; import nl.rrd.utils.json.SqlDateSerializer; import nl.rrd.utils.validation.ValidateEmail; import nl.rrd.utils.validation.ValidateNotNull; import nl.rrd.utils.validation.ValidateTimeZone; import nl.rrd.senseeact.client.model.Gender; import nl.rrd.senseeact.client.model.MaritalStatus; import nl.rrd.senseeact.client.model.Role; import nl.rrd.senseeact.client.model.User; import nl.rrd.senseeact.dao.AbstractDatabaseObject; import nl.rrd.senseeact.dao.DatabaseField; import nl.rrd.senseeact.dao.DatabaseObject; import nl.rrd.senseeact.dao.DatabaseType; import java.time.LocalDate; import java.util.LinkedHashSet; import java.util.Set;
10,817
*/ public String getDepartmentCode() { return departmentCode; } /** * Sets a string code for the department. * * @param departmentCode the department code or null */ public void setDepartmentCode(String departmentCode) { this.departmentCode = departmentCode; } /** * Returns any extra information. * * @return any extra information or null */ public String getExtraInfo() { return extraInfo; } /** * Sets any extra information. * * @param extraInfo any extra information or null */ public void setExtraInfo(String extraInfo) { this.extraInfo = extraInfo; } /** * Returns the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @return the locale code or null */ public String getLocaleCode() { return localeCode; } /** * Sets the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @param localeCode the locale code or null */ public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } /** * Returns the language formality that the user prefers to be addressed * with. This can be "FORMAL", "INFORMAL" or null. * * @return the language formality or null */ public String getLanguageFormality() { return languageFormality; } /** * Sets the language formality that the user prefers to be addressed with. * This can be "FORMAL", "INFORMAL" or null. * * @param languageFormality the language formality or null */ public void setLanguageFormality(String languageFormality) { this.languageFormality = languageFormality; } /** * Returns the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @return the time zone or null */ public String getTimeZone() { return timeZone; } /** * Sets the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @param timeZone the time zone or null */ public void setTimeZone(String timeZone) { this.timeZone = timeZone; } /** * Returns the status of this user. For example this could indicate whether * a user is active or inactive. * * @return the status or null */ public String getStatus() { return status; } /** * Sets the status of this user. For example this could indicate whether a * user is active or inactive. * * @param status the status or null */ public void setStatus(String status) { this.status = status; } /** * Converts a User object to a UserV7 object. * * @param user the User object * @return the UserV7 object */
package nl.rrd.senseeact.client.model.compat; /** * Model of a user in SenSeeAct. This class is used on the client side. The * server side has an extension of this class with sensitive information about * the authentication of a user. On the server it's stored in a database. * Therefore this class is a {@link DatabaseObject DatabaseObject} and it has an * ID field, but the ID field is not used on the client side. The "userid" field * is used to identify a user. * * <p>The following fields are always defined on the client side: userid, email, * role and active. All other fields may be null.</p> * * @author Dennis Hofs (RRD) */ public class UserV7 extends AbstractDatabaseObject { @JsonIgnore private String id; @DatabaseField(value=DatabaseType.STRING, index=true) @ValidateNotNull private String userid; @DatabaseField(value=DatabaseType.STRING, index=true) @ValidateEmail @ValidateNotNull private String email; @DatabaseField(value=DatabaseType.STRING) private Role role; @DatabaseField(value=DatabaseType.BYTE) private boolean active = true; @DatabaseField(value=DatabaseType.STRING) private Gender gender; @DatabaseField(value=DatabaseType.STRING) private MaritalStatus maritalStatus; @DatabaseField(value=DatabaseType.STRING) private String title; @DatabaseField(value=DatabaseType.STRING) private String initials; @DatabaseField(value=DatabaseType.STRING) private String firstName; @DatabaseField(value=DatabaseType.STRING) private String officialFirstNames; @DatabaseField(value=DatabaseType.STRING) private String prefixes; @DatabaseField(value=DatabaseType.STRING) private String lastName; @DatabaseField(value=DatabaseType.STRING) private String officialLastNames; @DatabaseField(value=DatabaseType.STRING) private String fullName; @DatabaseField(value=DatabaseType.STRING) private String nickName; @DatabaseField(value=DatabaseType.STRING) @ValidateEmail private String altEmail; @DatabaseField(value=DatabaseType.DATE) @JsonSerialize(using=SqlDateSerializer.class) @JsonDeserialize(using=SqlDateDeserializer.class) private LocalDate birthDate; @DatabaseField(value=DatabaseType.DATE) @JsonSerialize(using=SqlDateSerializer.class) @JsonDeserialize(using=SqlDateDeserializer.class) private LocalDate deathDate; @DatabaseField(value=DatabaseType.STRING) private String idNumber; @DatabaseField(value=DatabaseType.STRING) private String landlinePhone; @DatabaseField(value=DatabaseType.STRING) private String mobilePhone; @DatabaseField(value=DatabaseType.STRING) private String street; @DatabaseField(value=DatabaseType.STRING) private String streetNumber; @DatabaseField(value=DatabaseType.STRING) private String addressExtra; @DatabaseField(value=DatabaseType.STRING) private String postalCode; @DatabaseField(value=DatabaseType.STRING) private String town; @DatabaseField(value=DatabaseType.STRING) private String departmentCode; @DatabaseField(value=DatabaseType.TEXT) private String extraInfo; @DatabaseField(value=DatabaseType.STRING) private String localeCode; @DatabaseField(value=DatabaseType.STRING) private String languageFormality; @DatabaseField(value=DatabaseType.STRING) @ValidateTimeZone private String timeZone; @DatabaseField(value=DatabaseType.STRING) private String status; /** * Returns the ID. This is not defined on the client side. Users are * identified by their email address. * * @return the ID */ @Override public String getId() { return id; } /** * Sets the ID. This is not defined on the client side. Users are * identified by their email address. * * @param id the ID */ @Override public void setId(String id) { this.id = id; } /** * Returns the user ID. This is a required field. The user ID can be a UUID * or an email address (for legacy users). This field identifies the user * throughout the database. * * @return the user ID */ public String getUserid() { return userid; } /** * Sets the user ID. This is a required field. The user ID can be a UUID or * an email address (for legacy users). This field identifies the user * throughout the database. * * @param userid the user ID */ public void setUserid(String userid) { this.userid = userid; } /** * Returns the email address. This is a required field. * * @return the email address */ public String getEmail() { return email; } /** * Sets the email address. This is a required field. * * @param email the email address */ public void setEmail(String email) { this.email = email; } /** * Returns the role. This is a required field. * * @return the role */ public Role getRole() { return role; } /** * Sets the role. This is a required field. * * @param role the role */ public void setRole(Role role) { this.role = role; } /** * Returns whether the user is active. An inactive user cannot log in and * is excluded from system services. The default is true. * * @return true if the user is active, false if the user is inactive */ public boolean isActive() { return active; } /** * Sets whether the user is active. An inactive user cannot log in and is * excluded from system services. The default is true. * * @param active true if the user is active, false if the user is inactive */ public void setActive(boolean active) { this.active = active; } /** * Returns the gender. * * @return the gender or null */ public Gender getGender() { return gender; } /** * Sets the gender. * * @param gender the gender or null */ public void setGender(Gender gender) { this.gender = gender; } /** * Returns the marital status. * * @return the marital status or null */ public MaritalStatus getMaritalStatus() { return maritalStatus; } /** * Sets the marital status. * * @param maritalStatus the marital status or null */ public void setMaritalStatus(MaritalStatus maritalStatus) { this.maritalStatus = maritalStatus; } /** * Returns the title. * * @return the title or null */ public String getTitle() { return title; } /** * Sets the title. * * @param title the title or null */ public void setTitle(String title) { this.title = title; } /** * Returns the initials of the first names formatted as A.B.C. * * @return the initials or null */ public String getInitials() { return initials; } /** * Sets the initials of the first names formatted as A.B.C. * * @param initials the initials or null */ public void setInitials(String initials) { this.initials = initials; } /** * Returns the first name. This should be the familiar first name used to * address the person in friendly language. * * @return the first name or null */ public String getFirstName() { return firstName; } /** * Sets the first name. This should be the familiar first name used to * address the person in friendly language. * * @param firstName the first name or null */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Returns the official first names. * * @return the official first names or null */ public String getOfficialFirstNames() { return officialFirstNames; } /** * Sets the official first names. * * @param officialFirstNames the official first names or null */ public void setOfficialFirstNames(String officialFirstNames) { this.officialFirstNames = officialFirstNames; } /** * Returns the prefixes for the last name. Languages such as Dutch have * prefixes for last names that should be ignored when sorting. * * @return the prefixes or null */ public String getPrefixes() { return prefixes; } /** * Sets the prefixes for the last name. Languages such as Dutch have * prefixes for last names that should be ignored when sorting. * * @param prefixes the prefixes or null */ public void setPrefixes(String prefixes) { this.prefixes = prefixes; } /** * Returns the last name. This should be the familiar last name used to * address the person in friendly language. * * @return the last name or null */ public String getLastName() { return lastName; } /** * Sets the last name. This should be the familiar last name used to * address the person in friendly language. * * @param lastName the last name or null */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Returns the official last names. * * @return the official last names or null */ public String getOfficialLastNames() { return officialLastNames; } /** * Sets the official last names. * * @param officialLastNames the official last names or null */ public void setOfficialLastNames(String officialLastNames) { this.officialLastNames = officialLastNames; } /** * Returns the full name. This field can be used for applications that do * not separate first name and last name. * * @return the full name or null */ public String getFullName() { return fullName; } /** * Sets the full name. This field can be used for applications that do not * separate first name and last name. * * @param fullName the full name or null */ public void setFullName(String fullName) { this.fullName = fullName; } /** * Returns the nickname. * * @return the nickname or null */ public String getNickName() { return nickName; } /** * Sets the nickname. * * @param nickName the nickname or null */ public void setNickName(String nickName) { this.nickName = nickName; } /** * Returns the alternative email address. * * @return the alternative email address or null */ public String getAltEmail() { return altEmail; } /** * Sets the alternative email address. * * @param altEmail the alternative email address or null */ public void setAltEmail(String altEmail) { this.altEmail = altEmail; } /** * Returns the birth date. * * @return the birth date or null */ public LocalDate getBirthDate() { return birthDate; } /** * Sets the birth date. * * @param birthDate the birth date or null */ public void setBirthDate(LocalDate birthDate) { this.birthDate = birthDate; } /** * Returns the date of death. * * @return the date of death or null */ public LocalDate getDeathDate() { return deathDate; } /** * Sets the date of death. * * @param deathDate the date of death or null */ public void setDeathDate(LocalDate deathDate) { this.deathDate = deathDate; } /** * Returns the identification number. This could be the personal * identification number for government services or in a hospital * administration system. * * @return the identification number or null */ public String getIdNumber() { return idNumber; } /** * Sets the identification number. This could be the personal * identification number for government services or in a hospital * administration system. * * @param idNumber the identification number or null */ public void setIdNumber(String idNumber) { this.idNumber = idNumber; } /** * Returns the landline phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @return the landline phone number or null */ public String getLandlinePhone() { return landlinePhone; } /** * Sets the landline phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @param landlinePhone the landline phone number or null */ public void setLandlinePhone(String landlinePhone) { this.landlinePhone = landlinePhone; } /** * Returns the mobile phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @return the mobile phone number or null */ public String getMobilePhone() { return mobilePhone; } /** * Sets the mobile phone number. It could include characters such as * hyphens, parentheses and spaces. The format is not validated. * * @param mobilePhone the mobile phone number or null */ public void setMobilePhone(String mobilePhone) { this.mobilePhone = mobilePhone; } /** * Returns the street name. * * @return the street name or null */ public String getStreet() { return street; } /** * Sets the street name. * * @param street the street name or null */ public void setStreet(String street) { this.street = street; } /** * Returns the house number in the street. * * @return the house number or null */ public String getStreetNumber() { return streetNumber; } /** * Sets the house number in the street. * * @param streetNumber the house number or null */ public void setStreetNumber(String streetNumber) { this.streetNumber = streetNumber; } /** * Returns extra address lines. * * @return extra address lines or null */ public String getAddressExtra() { return addressExtra; } /** * Sets extra address lines. * * @param addressExtra extra address lines or null */ public void setAddressExtra(String addressExtra) { this.addressExtra = addressExtra; } /** * Returns the postal code. The format is not validated. * * @return the postal code or null */ public String getPostalCode() { return postalCode; } /** * Sets the postal code. The format is not validated. * * @param postalCode the postal code or null */ public void setPostalCode(String postalCode) { this.postalCode = postalCode; } /** * Returns the town name. * * @return the town name or null */ public String getTown() { return town; } /** * Sets the town name. * * @param town the town name or null */ public void setTown(String town) { this.town = town; } /** * Returns a string code for the department. * * @return the department code or null */ public String getDepartmentCode() { return departmentCode; } /** * Sets a string code for the department. * * @param departmentCode the department code or null */ public void setDepartmentCode(String departmentCode) { this.departmentCode = departmentCode; } /** * Returns any extra information. * * @return any extra information or null */ public String getExtraInfo() { return extraInfo; } /** * Sets any extra information. * * @param extraInfo any extra information or null */ public void setExtraInfo(String extraInfo) { this.extraInfo = extraInfo; } /** * Returns the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @return the locale code or null */ public String getLocaleCode() { return localeCode; } /** * Sets the locale code. For example en_GB. It should consists of an * ISO 639-1 language code, an underscore, and an ISO 3166-1 alpha-2 country * code. * * @param localeCode the locale code or null */ public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } /** * Returns the language formality that the user prefers to be addressed * with. This can be "FORMAL", "INFORMAL" or null. * * @return the language formality or null */ public String getLanguageFormality() { return languageFormality; } /** * Sets the language formality that the user prefers to be addressed with. * This can be "FORMAL", "INFORMAL" or null. * * @param languageFormality the language formality or null */ public void setLanguageFormality(String languageFormality) { this.languageFormality = languageFormality; } /** * Returns the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @return the time zone or null */ public String getTimeZone() { return timeZone; } /** * Sets the time zone. This should be a location-based time zone ID from * the tz database. For example Europe/Amsterdam. * * @param timeZone the time zone or null */ public void setTimeZone(String timeZone) { this.timeZone = timeZone; } /** * Returns the status of this user. For example this could indicate whether * a user is active or inactive. * * @return the status or null */ public String getStatus() { return status; } /** * Sets the status of this user. For example this could indicate whether a * user is active or inactive. * * @param status the status or null */ public void setStatus(String status) { this.status = status; } /** * Converts a User object to a UserV7 object. * * @param user the User object * @return the UserV7 object */
public static UserV7 fromUser(User user) {
3
2023-10-24 09:36:50+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,586
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:
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;
2
2023-10-23 17:01:53+00:00
16k
Amir-UL-Islam/eTBManager3-Backend
src/main/java/org/msh/etbm/services/cases/casemove/CaseMoveService.java
[ { "identifier": "CommandTypes", "path": "src/main/java/org/msh/etbm/commons/commands/CommandTypes.java", "snippet": "public class CommandTypes {\n\n private CommandTypes() {\n // avoid this class being instantiated inadvertently\n }\n\n // main group commands\n public static final Str...
import org.msh.etbm.commons.commands.CommandLog; import org.msh.etbm.commons.commands.CommandTypes; import org.msh.etbm.commons.entities.EntityValidationException; import org.msh.etbm.db.entities.TbCase; import org.msh.etbm.db.entities.Tbunit; import org.msh.etbm.db.entities.Unit; import org.msh.etbm.db.entities.UserWorkspace; import org.msh.etbm.services.cases.CaseLogHandler; import org.msh.etbm.services.security.ForbiddenException; import org.msh.etbm.services.session.usersession.UserRequestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import javax.persistence.EntityNotFoundException; import javax.persistence.PersistenceContext; import java.util.UUID;
14,240
package org.msh.etbm.services.cases.casemove; /** * Created by Mauricio on 12/09/2016. */ @Service public class CaseMoveService { @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired CaseOnTreatMoveService caseOnTreatMoveService; @Autowired CaseNotOnTreatMoveService notOnTreatCaseMoveService; @CommandLog(handler = CaseLogHandler.class, type = CommandTypes.CASES_CASE_TRANSFER_OUT) public CaseMoveResponse transferOut(CaseMoveRequest req) { TbCase tbcase = entityManager.find(TbCase.class, req.getTbcaseId()); Unit unitTo = entityManager.find(Unit.class, req.getUnitToId()); if (tbcase == null) { throw new EntityNotFoundException(); } if (!(unitTo instanceof Tbunit)) { throw new EntityValidationException(unitTo, "DISCRIMINATOR", "Destiny unit must be a TbUnit", null); } if (!isWorkingUnit(tbcase)) {
package org.msh.etbm.services.cases.casemove; /** * Created by Mauricio on 12/09/2016. */ @Service public class CaseMoveService { @PersistenceContext EntityManager entityManager; @Autowired UserRequestService userRequestService; @Autowired CaseOnTreatMoveService caseOnTreatMoveService; @Autowired CaseNotOnTreatMoveService notOnTreatCaseMoveService; @CommandLog(handler = CaseLogHandler.class, type = CommandTypes.CASES_CASE_TRANSFER_OUT) public CaseMoveResponse transferOut(CaseMoveRequest req) { TbCase tbcase = entityManager.find(TbCase.class, req.getTbcaseId()); Unit unitTo = entityManager.find(Unit.class, req.getUnitToId()); if (tbcase == null) { throw new EntityNotFoundException(); } if (!(unitTo instanceof Tbunit)) { throw new EntityValidationException(unitTo, "DISCRIMINATOR", "Destiny unit must be a TbUnit", null); } if (!isWorkingUnit(tbcase)) {
throw new ForbiddenException();
7
2023-10-23 13:47:54+00:00
16k
weibocom/rill-flow
rill-flow-web/src/main/java/com/weibo/rill/flow/controller/FlowController.java
[ { "identifier": "TaskException", "path": "rill-flow-common/src/main/java/com/weibo/rill/flow/common/exception/TaskException.java", "snippet": "@ResponseStatus(HttpStatus.BAD_REQUEST)\npublic class TaskException extends RuntimeException {\n private final int errorCode;\n private final String execut...
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.weibo.rill.flow.common.exception.TaskException; import com.weibo.rill.flow.common.function.ResourceCheckConfig; import com.weibo.rill.flow.common.model.BizError; import com.weibo.rill.flow.common.model.User; import com.weibo.rill.flow.olympicene.core.model.dag.DAGStatus; import com.weibo.rill.flow.olympicene.storage.redis.api.RedisClient; import com.weibo.rill.flow.service.context.DAGContextInitializer; import com.weibo.rill.flow.service.facade.OlympiceneFacade; import com.weibo.rill.flow.service.statistic.DAGSubmitChecker; import com.weibo.rill.flow.service.statistic.ProfileRecordService; import com.weibo.rill.flow.service.util.ExecutionIdUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier;
12,412
/* * 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.controller; @RestController @Api(tags = {"工作流操作相关接口"}) @RequestMapping("/flow") public class FlowController { private static final String EXECUTION_ID = "execution_id"; private static final String TASK_NAME = "task_name"; private static final String TASK_NAMES = "task_names"; private static final String SERVICE_ID = "service_id"; private static final String TYPE = "type"; private static final String CODE = "code"; @Autowired private OlympiceneFacade olympiceneFacade; @Autowired private ProfileRecordService profileRecordService; @Autowired private DAGSubmitChecker submitChecker; @Autowired @Qualifier("descriptorRedisClient") private RedisClient redisClient; @Autowired private DAGContextInitializer dagContextInitializer; /** * 任务提交接口 * * @param flowUser 用户身份认证后的用户信息对象 * @param descriptorId DAG 图 ID * @param callback 非必须,执行完成后的回调地址 * @param resourceCheck 用于检测资源是否可用的检测规则 * @param data 图执行的 context 信息 * @return */ @ApiOperation(value = "执行工作流") @RequestMapping(value = "submit.json", method = RequestMethod.POST) public Map<String, Object> submit(User flowUser, @ApiParam(value = "工作流ID") @RequestParam(value = "descriptor_id") String descriptorId, @ApiParam(value = "执行完成后的回调地址") @RequestParam(value = "callback", required = false) String callback, @ApiParam(value = "用于检测资源是否可用的检测规则") @RequestParam(value = "resource_check", required = false) String resourceCheck, @ApiParam(value = "工作流执行的context信息") @RequestBody(required = false) JSONObject data) { Supplier<Map<String, Object>> submitActions = () -> { ResourceCheckConfig resourceCheckConfig = submitChecker.getCheckConfig(resourceCheck); Map<String, Object> context = dagContextInitializer.newSubmitContextBuilder().withData(data).withIdentity(descriptorId).build(); return olympiceneFacade.submit(flowUser, descriptorId, context, callback, resourceCheckConfig); }; return profileRecordService.runNotifyAndRecordProfile("submit.json", descriptorId, submitActions); } @ApiOperation(value = "任务完成回调") @RequestMapping(value = "finish.json", method = RequestMethod.POST) public Map<String, Object> finish(User flowUser, @ApiParam(value = "执行ID") @RequestParam(EXECUTION_ID) String executionId, @ApiParam(value = "任务名称") @RequestParam(TASK_NAME) String taskName, @ApiParam(value = "工作流执行的context信息") @RequestBody JSONObject result) { Supplier<Map<String, Object>> finishActions = () -> { Map<String, Object> context = dagContextInitializer.newCallbackContextBuilder().withData(result).withIdentity(executionId).build(); JSONObject data = new JSONObject(); data.put("response", result); data.put("result_type", result.getOrDefault("result_type", "SUCCESS")); JSONObject passThrough = new JSONObject(); passThrough.put(EXECUTION_ID, executionId); passThrough.put(TASK_NAME, taskName); data.put("passthrough", passThrough); return olympiceneFacade.finish(executionId, context, data); }; return profileRecordService.runNotifyAndRecordProfile("finish.json", executionId, finishActions); } @ApiOperation(value = "唤醒挂起任务") @RequestMapping(value = "wakeup.json", method = RequestMethod.POST) public Map<String, Object> wakeup(User flowUser, @ApiParam(value = "执行ID") @RequestParam(value = EXECUTION_ID) String executionId, @ApiParam(value = "任务名称") @RequestParam(value = TASK_NAME) String taskName, @ApiParam(value = "工作流执行的context信息") @RequestBody(required = false) JSONObject data) { Supplier<Map<String, Object>> wakeupActions = () -> { if (StringUtils.isEmpty(taskName)) {
/* * 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.controller; @RestController @Api(tags = {"工作流操作相关接口"}) @RequestMapping("/flow") public class FlowController { private static final String EXECUTION_ID = "execution_id"; private static final String TASK_NAME = "task_name"; private static final String TASK_NAMES = "task_names"; private static final String SERVICE_ID = "service_id"; private static final String TYPE = "type"; private static final String CODE = "code"; @Autowired private OlympiceneFacade olympiceneFacade; @Autowired private ProfileRecordService profileRecordService; @Autowired private DAGSubmitChecker submitChecker; @Autowired @Qualifier("descriptorRedisClient") private RedisClient redisClient; @Autowired private DAGContextInitializer dagContextInitializer; /** * 任务提交接口 * * @param flowUser 用户身份认证后的用户信息对象 * @param descriptorId DAG 图 ID * @param callback 非必须,执行完成后的回调地址 * @param resourceCheck 用于检测资源是否可用的检测规则 * @param data 图执行的 context 信息 * @return */ @ApiOperation(value = "执行工作流") @RequestMapping(value = "submit.json", method = RequestMethod.POST) public Map<String, Object> submit(User flowUser, @ApiParam(value = "工作流ID") @RequestParam(value = "descriptor_id") String descriptorId, @ApiParam(value = "执行完成后的回调地址") @RequestParam(value = "callback", required = false) String callback, @ApiParam(value = "用于检测资源是否可用的检测规则") @RequestParam(value = "resource_check", required = false) String resourceCheck, @ApiParam(value = "工作流执行的context信息") @RequestBody(required = false) JSONObject data) { Supplier<Map<String, Object>> submitActions = () -> { ResourceCheckConfig resourceCheckConfig = submitChecker.getCheckConfig(resourceCheck); Map<String, Object> context = dagContextInitializer.newSubmitContextBuilder().withData(data).withIdentity(descriptorId).build(); return olympiceneFacade.submit(flowUser, descriptorId, context, callback, resourceCheckConfig); }; return profileRecordService.runNotifyAndRecordProfile("submit.json", descriptorId, submitActions); } @ApiOperation(value = "任务完成回调") @RequestMapping(value = "finish.json", method = RequestMethod.POST) public Map<String, Object> finish(User flowUser, @ApiParam(value = "执行ID") @RequestParam(EXECUTION_ID) String executionId, @ApiParam(value = "任务名称") @RequestParam(TASK_NAME) String taskName, @ApiParam(value = "工作流执行的context信息") @RequestBody JSONObject result) { Supplier<Map<String, Object>> finishActions = () -> { Map<String, Object> context = dagContextInitializer.newCallbackContextBuilder().withData(result).withIdentity(executionId).build(); JSONObject data = new JSONObject(); data.put("response", result); data.put("result_type", result.getOrDefault("result_type", "SUCCESS")); JSONObject passThrough = new JSONObject(); passThrough.put(EXECUTION_ID, executionId); passThrough.put(TASK_NAME, taskName); data.put("passthrough", passThrough); return olympiceneFacade.finish(executionId, context, data); }; return profileRecordService.runNotifyAndRecordProfile("finish.json", executionId, finishActions); } @ApiOperation(value = "唤醒挂起任务") @RequestMapping(value = "wakeup.json", method = RequestMethod.POST) public Map<String, Object> wakeup(User flowUser, @ApiParam(value = "执行ID") @RequestParam(value = EXECUTION_ID) String executionId, @ApiParam(value = "任务名称") @RequestParam(value = TASK_NAME) String taskName, @ApiParam(value = "工作流执行的context信息") @RequestBody(required = false) JSONObject data) { Supplier<Map<String, Object>> wakeupActions = () -> { if (StringUtils.isEmpty(taskName)) {
throw new TaskException(BizError.ERROR_DATA_FORMAT, executionId, "task_name is empty");
0
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,570
/* *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
/* *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;
27
2023-11-01 08:19:34+00:00
16k
daominh-studio/quick-mem
app/src/main/java/com/daominh/quickmem/ui/activities/create/CreateSetActivity.java
[ { "identifier": "CardAdapter", "path": "app/src/main/java/com/daominh/quickmem/adapter/card/CardAdapter.java", "snippet": "public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {\n\n private final Context context;\n private final ArrayList<Card> cards;\n\n public Car...
import android.annotation.SuppressLint; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import androidx.core.content.ContextCompat; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.daominh.quickmem.R; import com.daominh.quickmem.adapter.card.CardAdapter; import com.daominh.quickmem.data.dao.CardDAO; import com.daominh.quickmem.data.dao.FlashCardDAO; import com.daominh.quickmem.data.model.Card; import com.daominh.quickmem.data.model.FlashCard; import com.daominh.quickmem.databinding.ActivityCreateSetBinding; import com.daominh.quickmem.preferen.UserSharePreferences; import com.daominh.quickmem.ui.activities.set.ViewSetActivity; import com.google.android.material.snackbar.Snackbar; import org.jetbrains.annotations.NotNull; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Date;
13,287
ItemTouchHelper.SimpleCallback callback = createItemTouchHelperCallback(); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback); itemTouchHelper.attachToRecyclerView(binding.cardsLv); } private ItemTouchHelper.SimpleCallback createItemTouchHelperCallback() { return new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { @Override public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NotNull RecyclerView.ViewHolder viewHolder, int direction) { handleOnSwiped(viewHolder); } @Override public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { handleOnChildDraw(c, viewHolder, dX); } }; } private void handleOnSwiped(RecyclerView.ViewHolder viewHolder) { int position = viewHolder.getBindingAdapterPosition(); // Backup of removed item for undo purpose Card deletedItem = cards.get(position); // Removing item from recycler view cards.remove(position); updateTotalCards(); cardAdapter.notifyItemRemoved(position); // Showing Snack bar with an Undo option Snackbar snackbar = Snackbar.make(binding.getRoot(), "Item was removed from the list.", Snackbar.LENGTH_LONG); snackbar.setAction("UNDO", view -> { // Check if the position is valid before adding the item back if (position >= 0 && position <= cards.size()) { cards.add(position, deletedItem); cardAdapter.notifyItemInserted(position); updateTotalCards(); } else { // If the position isn't valid, show a message or handle the error appropriately Toast.makeText(getApplicationContext(), "Error restoring item", Toast.LENGTH_LONG).show(); } }); snackbar.setActionTextColor(Color.YELLOW); snackbar.show(); } private void handleOnChildDraw(@NotNull Canvas c, @NotNull RecyclerView.ViewHolder viewHolder, float dX) { Drawable icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_delete); View itemView = viewHolder.itemView; assert icon != null; int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2; int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2; int iconBottom = iconTop + icon.getIntrinsicHeight(); if (dX < 0) { // Swiping to the left int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth(); int iconRight = itemView.getRight() - iconMargin; icon.setBounds(iconLeft, iconTop, iconRight, iconBottom); final ColorDrawable background = new ColorDrawable(Color.WHITE); background.setBounds(itemView.getRight() + ((int) dX), itemView.getTop(), itemView.getRight(), itemView.getBottom()); background.draw(c); } else { // No swipe icon.setBounds(0, 0, 0, 0); } icon.draw(c); } @Override public boolean onPrepareOptionsMenu(Menu menu) { return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_create_set, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.done) { saveChanges(); return true; } return super.onOptionsItemSelected(item); } private void saveChanges() { String subject = binding.subjectEt.getText().toString(); String description = binding.descriptionEt.getText().toString(); if (subject.isEmpty()) { binding.subjectTil.setError("Please enter subject"); binding.subjectEt.requestFocus(); return; } else { binding.subjectTil.setError(null); } if (!saveAllCards()) { return; } if (!saveFlashCard(subject, description)) { Toast.makeText(this, "Insert flashcard failed", Toast.LENGTH_SHORT).show(); return; }
package com.daominh.quickmem.ui.activities.create; public class CreateSetActivity extends AppCompatActivity { private CardAdapter cardAdapter; private ArrayList<Card> cards; private ActivityCreateSetBinding binding; private final String id = genUUID(); @SuppressLint("NotifyDataSetChanged") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityCreateSetBinding.inflate(getLayoutInflater()); final View view = binding.getRoot(); setContentView(view); setupToolbar(); setupSubjectEditText(); setupDescriptionTextView(); setupCardsList(); setupCardAdapter(); setupAddFab(); setupItemTouchHelper(); } private void setupToolbar() { setSupportActionBar(binding.toolbar); binding.toolbar.setNavigationOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed()); } private void setupSubjectEditText() { if (binding.subjectEt.getText().toString().isEmpty()) { binding.subjectEt.requestFocus(); } } private void setupDescriptionTextView() { binding.descriptionTv.setOnClickListener(v -> { if (binding.descriptionTil.getVisibility() == View.GONE) { binding.descriptionTil.setVisibility(View.VISIBLE); } else { binding.descriptionTil.setVisibility(View.GONE); } }); } private void setupCardsList() { //create list two set cards = new ArrayList<>(); cards.add(new Card()); cards.add(new Card()); updateTotalCards(); } private void updateTotalCards() { binding.totalCardsTv.setText(String.format("Total Cards: %s", cards.size())); } @SuppressLint("NotifyDataSetChanged") private void setupCardAdapter() { cardAdapter = new CardAdapter(this, cards); binding.cardsLv.setAdapter(cardAdapter); binding.cardsLv.setLayoutManager(new LinearLayoutManager(this)); binding.cardsLv.setHasFixedSize(true); cardAdapter.notifyDataSetChanged(); } private void setupAddFab() { binding.addFab.setOnClickListener(v -> { if (!checkTwoCardsEmpty()) { Card newCard = new Card(); cards.add(newCard); //scroll to last item binding.cardsLv.smoothScrollToPosition(cards.size() - 1); //notify adapter cardAdapter.notifyItemInserted(cards.size() - 1); updateTotalCards(); } else { Toast.makeText(this, "Please enter front and back", Toast.LENGTH_SHORT).show(); } }); } private void setupItemTouchHelper() { ItemTouchHelper.SimpleCallback callback = createItemTouchHelperCallback(); ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback); itemTouchHelper.attachToRecyclerView(binding.cardsLv); } private ItemTouchHelper.SimpleCallback createItemTouchHelperCallback() { return new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) { @Override public boolean onMove(@NonNull @NotNull RecyclerView recyclerView, @NonNull @NotNull RecyclerView.ViewHolder viewHolder, @NonNull @NotNull RecyclerView.ViewHolder target) { return false; } @Override public void onSwiped(@NotNull RecyclerView.ViewHolder viewHolder, int direction) { handleOnSwiped(viewHolder); } @Override public void onChildDraw(@NotNull Canvas c, @NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { handleOnChildDraw(c, viewHolder, dX); } }; } private void handleOnSwiped(RecyclerView.ViewHolder viewHolder) { int position = viewHolder.getBindingAdapterPosition(); // Backup of removed item for undo purpose Card deletedItem = cards.get(position); // Removing item from recycler view cards.remove(position); updateTotalCards(); cardAdapter.notifyItemRemoved(position); // Showing Snack bar with an Undo option Snackbar snackbar = Snackbar.make(binding.getRoot(), "Item was removed from the list.", Snackbar.LENGTH_LONG); snackbar.setAction("UNDO", view -> { // Check if the position is valid before adding the item back if (position >= 0 && position <= cards.size()) { cards.add(position, deletedItem); cardAdapter.notifyItemInserted(position); updateTotalCards(); } else { // If the position isn't valid, show a message or handle the error appropriately Toast.makeText(getApplicationContext(), "Error restoring item", Toast.LENGTH_LONG).show(); } }); snackbar.setActionTextColor(Color.YELLOW); snackbar.show(); } private void handleOnChildDraw(@NotNull Canvas c, @NotNull RecyclerView.ViewHolder viewHolder, float dX) { Drawable icon = ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_delete); View itemView = viewHolder.itemView; assert icon != null; int iconMargin = (itemView.getHeight() - icon.getIntrinsicHeight()) / 2; int iconTop = itemView.getTop() + (itemView.getHeight() - icon.getIntrinsicHeight()) / 2; int iconBottom = iconTop + icon.getIntrinsicHeight(); if (dX < 0) { // Swiping to the left int iconLeft = itemView.getRight() - iconMargin - icon.getIntrinsicWidth(); int iconRight = itemView.getRight() - iconMargin; icon.setBounds(iconLeft, iconTop, iconRight, iconBottom); final ColorDrawable background = new ColorDrawable(Color.WHITE); background.setBounds(itemView.getRight() + ((int) dX), itemView.getTop(), itemView.getRight(), itemView.getBottom()); background.draw(c); } else { // No swipe icon.setBounds(0, 0, 0, 0); } icon.draw(c); } @Override public boolean onPrepareOptionsMenu(Menu menu) { return super.onPrepareOptionsMenu(menu); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_create_set, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.done) { saveChanges(); return true; } return super.onOptionsItemSelected(item); } private void saveChanges() { String subject = binding.subjectEt.getText().toString(); String description = binding.descriptionEt.getText().toString(); if (subject.isEmpty()) { binding.subjectTil.setError("Please enter subject"); binding.subjectEt.requestFocus(); return; } else { binding.subjectTil.setError(null); } if (!saveAllCards()) { return; } if (!saveFlashCard(subject, description)) { Toast.makeText(this, "Insert flashcard failed", Toast.LENGTH_SHORT).show(); return; }
Intent intent = new Intent(this, ViewSetActivity.class);
6
2023-11-07 16:56:39+00:00
16k
YunaBraska/type-map
src/test/java/berlin/yuna/typemap/model/TypeMapTest.java
[ { "identifier": "TypeConversionRegister", "path": "src/main/java/berlin/yuna/typemap/config/TypeConversionRegister.java", "snippet": "public class TypeConversionRegister<S, T> {\n\n /**\n * A map where the key is the target type and the value is another map.\n * The nested map's key is the so...
import berlin.yuna.typemap.config.TypeConversionRegister; import berlin.yuna.typemap.logic.TypeConverter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.time.*; import java.util.*; import java.util.stream.Stream; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat;
14,255
final Long[] longArray2 = typeMap.getArray("myKey2", Long[]::new, Long.class); assertThat(instantList2).isNotEmpty(); assertThat(integerList2).isNotEmpty().containsExactly(1, 2, 3); assertThat(floatList2).isNotEmpty().containsExactly(1f, 2f, 3f); assertThat(doubleArray2).isNotEmpty().containsExactly(1d, 2d, 3d); assertThat(longArray2).isNotEmpty().containsExactly(1L, 2L, 3L); assertThat(typeMap.getList("myKey2", Integer.class)).isNotEmpty().containsExactly(1, 2, 3); } @ParameterizedTest @MethodSource("typeMapProvider") void mapConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<Integer, Date> input = new HashMap<>(); input.put(6, new Date(TEST_TIME)); typeMap.put("myKey", input); // TREE MAP assertThat(typeMap.getMap("myKey")).containsEntry(6, new Date(TEST_TIME)); assertThat(typeMap.getMap(Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey2")).isEmpty(); // KEY MAP assertThat(typeMap.getMap("myKey", () -> new HashMap<>(), Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey", Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey2", () -> new HashMap<>(), Long.class, Instant.class)).isEmpty(); } @ParameterizedTest @MethodSource("typeMapProvider") void jsonConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> input = new HashMap<>(); final Map<String, Object> innerMap = new HashMap<>(); innerMap.put("FF", asList("GG", 2, true)); input.put("AA", asList("BB", 1, true, null)); input.put("CC", new long[]{4L, 5L, 6L}); input.put("DD", innerMap); input.put("EE", "HH,II,\n"); typeMap.put("myKey", input); assertThat(typeMap.toJson("invalidKey")).isEqualTo("{}"); assertThat(typeMap.toJson("myKey")).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(typeMap.toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); // Encode & Decode assertThat(new TypeMap(typeMap.toJson("invalidKey")).toJson()).isEqualTo("{}"); assertThat(new ConcurrentTypeMap(typeMap.toJson("myKey")).toJson()).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(new LinkedTypeMap(typeMap.toJson()).toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); } @ParameterizedTest @MethodSource("typeMapProvider") void nestedKeysTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> innerMap = new HashMap<>(); final UnknownClass anObject = new UnknownClass(); innerMap.put("BB", asList("11", "22")); innerMap.put("CC", new Object[]{"33", "44"}); innerMap.put("DD", anObject); innerMap.put("EE", singletonList(anObject)); innerMap.put("FF", new Object[]{anObject}); typeMap.put("AA", innerMap); assertThat(typeMap.gett(Object.class)).isEmpty(); assertThat(typeMap.gett(Object.class, (Object) null)).isEmpty(); assertThat(typeMap.gett(Object.class, new Object[]{null})).isEmpty(); assertThat(typeMap.gett(Object.class, "AA")).contains(innerMap); assertThat(typeMap.gett(Object.class, "AA", "BB")).contains(asList("11", "22")); assertThat(typeMap.gett(Object.class, "AA", "CC")).contains(new Object[]{"33", "44"}); assertThat(typeMap.gett(Object.class, "AA", "BB", 0)).contains("11"); assertThat(typeMap.gett(Object.class, "AA", "BB", 1)).contains("22"); assertThat(typeMap.gett(Object.class, "AA", "CC", 0)).contains("33"); assertThat(typeMap.gett(Object.class, "AA", "CC", 1)).contains("44"); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD")).contains(anObject); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD", anObject)).isEmpty(); } @Test void testDefaultMapMethods() { final String myTime = new Date(TEST_TIME).toString(); // Broken json assertThat(new TypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new LinkedTypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new ConcurrentTypeMap("{ broken json")).containsEntry("", "{ broken json"); final TypeMap map1 = new TypeMap().putt("myKey", myTime); final LinkedTypeMap map2 = new LinkedTypeMap().putt("myKey", myTime); final ConcurrentTypeMap map3 = new ConcurrentTypeMap().putt("myKey", myTime); // Get assertThat(map1.get("myKey")).isNotNull(); assertThat(map2.get("myKey")).isNotNull(); assertThat(map3.get("myKey")).isNotNull(); } @Test void argsTest() { final String[] cliArgs = {" myCommand1 myCommand2 --help -v2=\"true\" -v=\"true\" -v=\"true\" --verbose=\"true\" -DArgs=\"true\" -param 42 54 -DArgList=\"item 1\" --DArgList=\"item 2\" -v2=\"false\" --DArgList=\"-item 3\" "}; final TypeMap map1 = new TypeMap(cliArgs); final LinkedTypeMap map2 = new LinkedTypeMap(cliArgs); final ConcurrentTypeMap map3 = new ConcurrentTypeMap(cliArgs); for (final TypeMapI<?> map : new TypeMapI<?>[]{map1, map2, map3}) { assertThat(map.get("help", Boolean.class)).isTrue(); assertThat(map.get("v", Boolean.class)).isTrue(); assertThat(map.get("v2", Boolean.class)).isTrue(); assertThat(map.get("verbose", Boolean.class)).isTrue(); assertThat(map.get("DArgs", Boolean.class)).isTrue(); assertThat(map.getList("param", Integer.class)).containsExactly(42, 54); assertThat(map.getList("v2", Boolean.class)).containsExactly(true, false); assertThat(map.getList("DArgList")).containsExactly("item 1", "item 2", "-item 3"); assertThat(map.getList("DArgList", String.class)).containsExactly("item 1", "item 2", "-item 3"); } } @Test void showCaseTest() { // Converter
package berlin.yuna.typemap.model; class TypeMapTest { public static final long TEST_TIME = 1800000000000L; @BeforeEach void setUp() { System.getProperties().setProperty("user.timezone", "UTC"); TimeZone.setDefault(null); } static Stream<Arguments> typeMapProvider() { return Stream.of( Arguments.of(TypeMap.class.getSimpleName(), new TypeMap()), Arguments.of(LinkedTypeMap.class.getSimpleName(), new LinkedTypeMap()), Arguments.of(ConcurrentTypeMap.class.getSimpleName(), new ConcurrentTypeMap()) ); } @ParameterizedTest(name = "[{index}] [{0}]") @MethodSource("typeMapProvider") void simpleConvertTest(final String mapName, final TypeMapI<?> typeMap) { final String myTime = new Date(TEST_TIME).toString(); typeMap.addd("myKey", myTime); // VALIDATIONS assertThat(typeMap.typeList()).isEmpty(); assertThat(typeMap.typeMap()).isPresent(); // TREE MAP assertThat(typeMap.gett(Instant.class, "myKey")).contains(Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.gett(LocalTime.class, "myKey")).contains(LocalDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault()).toLocalTime()); assertThat(typeMap.get(OffsetDateTime.class, "myKey")).isEqualTo(OffsetDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault())); // KEY MAP assertThat(typeMap.gett("myKey", Instant.class)).contains(Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.gett("myKey", LocalTime.class)).contains(LocalDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault()).toLocalTime()); assertThat(typeMap.get("myKey", OffsetDateTime.class)).isEqualTo(OffsetDateTime.ofInstant(Instant.ofEpochMilli(TEST_TIME), ZoneId.systemDefault())); } @ParameterizedTest @MethodSource("typeMapProvider") void enumConvertTest(final String mapName, final TypeMapI<?> typeMap) { typeMap.put("myKey", "BB"); assertThat(typeMap.gett(TestEnum.class, "myKey")).contains(TestEnum.BB); } @ParameterizedTest @MethodSource("typeMapProvider") void collectionConvertTest(final String mapName, final TypeMapI<?> typeMap) { final String myTime = new Date(TEST_TIME).toString(); typeMap.putt("myKey1", myTime); typeMap.put("myKey2", new String[]{"1", "2", "3"}); // TREE MAP final List<Instant> instantList1 = typeMap.getList(ArrayList::new, Instant.class, "myKey1"); final List<Integer> integerList1 = typeMap.getList(ArrayList::new, Integer.class, "myKey2"); final List<Float> floatList1 = typeMap.getList(ArrayList::new, Float.class, "myKey2"); final Double[] doubleArray1 = typeMap.getArray(new Double[0], Double.class, "myKey2"); final Long[] longArray1 = typeMap.getArray(Long[]::new, Long.class, "myKey2"); assertThat(instantList1).isNotEmpty(); assertThat(integerList1).isNotEmpty().containsExactly(1, 2, 3); assertThat(floatList1).isNotEmpty().containsExactly(1f, 2f, 3f); assertThat(doubleArray1).isNotEmpty().containsExactly(1d, 2d, 3d); assertThat(longArray1).isNotEmpty().containsExactly(1L, 2L, 3L); assertThat(typeMap.getList("myKey2")).isNotEmpty().containsExactly("1", "2", "3"); assertThat(typeMap.getList(Integer.class, "myKey2")).isNotEmpty().containsExactly(1, 2, 3); // KEY MAP final List<Instant> instantList2 = typeMap.getList("myKey1", ArrayList::new, Instant.class); final List<Integer> integerList2 = typeMap.getList("myKey2", ArrayList::new, Integer.class); final List<Float> floatList2 = typeMap.getList("myKey2", ArrayList::new, Float.class); final Double[] doubleArray2 = typeMap.getArray("myKey2", new Double[0], Double.class); final Long[] longArray2 = typeMap.getArray("myKey2", Long[]::new, Long.class); assertThat(instantList2).isNotEmpty(); assertThat(integerList2).isNotEmpty().containsExactly(1, 2, 3); assertThat(floatList2).isNotEmpty().containsExactly(1f, 2f, 3f); assertThat(doubleArray2).isNotEmpty().containsExactly(1d, 2d, 3d); assertThat(longArray2).isNotEmpty().containsExactly(1L, 2L, 3L); assertThat(typeMap.getList("myKey2", Integer.class)).isNotEmpty().containsExactly(1, 2, 3); } @ParameterizedTest @MethodSource("typeMapProvider") void mapConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<Integer, Date> input = new HashMap<>(); input.put(6, new Date(TEST_TIME)); typeMap.put("myKey", input); // TREE MAP assertThat(typeMap.getMap("myKey")).containsEntry(6, new Date(TEST_TIME)); assertThat(typeMap.getMap(Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey")).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap(() -> new HashMap<>(), Long.class, Instant.class, "myKey2")).isEmpty(); // KEY MAP assertThat(typeMap.getMap("myKey", () -> new HashMap<>(), Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey", Long.class, Instant.class)).containsEntry(6L, Instant.ofEpochMilli(TEST_TIME)); assertThat(typeMap.getMap("myKey2", () -> new HashMap<>(), Long.class, Instant.class)).isEmpty(); } @ParameterizedTest @MethodSource("typeMapProvider") void jsonConvertTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> input = new HashMap<>(); final Map<String, Object> innerMap = new HashMap<>(); innerMap.put("FF", asList("GG", 2, true)); input.put("AA", asList("BB", 1, true, null)); input.put("CC", new long[]{4L, 5L, 6L}); input.put("DD", innerMap); input.put("EE", "HH,II,\n"); typeMap.put("myKey", input); assertThat(typeMap.toJson("invalidKey")).isEqualTo("{}"); assertThat(typeMap.toJson("myKey")).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(typeMap.toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); // Encode & Decode assertThat(new TypeMap(typeMap.toJson("invalidKey")).toJson()).isEqualTo("{}"); assertThat(new ConcurrentTypeMap(typeMap.toJson("myKey")).toJson()).isEqualTo("{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}"); assertThat(new LinkedTypeMap(typeMap.toJson()).toJson()).isEqualTo("{\"myKey\":{\"AA\":[\"BB\",1,true,null],\"CC\":[4,5,6],\"DD\":{\"FF\":[\"GG\",2,true]},\"EE\":\"HH,II,\\n\"}}"); } @ParameterizedTest @MethodSource("typeMapProvider") void nestedKeysTest(final String mapName, final TypeMapI<?> typeMap) { final Map<String, Object> innerMap = new HashMap<>(); final UnknownClass anObject = new UnknownClass(); innerMap.put("BB", asList("11", "22")); innerMap.put("CC", new Object[]{"33", "44"}); innerMap.put("DD", anObject); innerMap.put("EE", singletonList(anObject)); innerMap.put("FF", new Object[]{anObject}); typeMap.put("AA", innerMap); assertThat(typeMap.gett(Object.class)).isEmpty(); assertThat(typeMap.gett(Object.class, (Object) null)).isEmpty(); assertThat(typeMap.gett(Object.class, new Object[]{null})).isEmpty(); assertThat(typeMap.gett(Object.class, "AA")).contains(innerMap); assertThat(typeMap.gett(Object.class, "AA", "BB")).contains(asList("11", "22")); assertThat(typeMap.gett(Object.class, "AA", "CC")).contains(new Object[]{"33", "44"}); assertThat(typeMap.gett(Object.class, "AA", "BB", 0)).contains("11"); assertThat(typeMap.gett(Object.class, "AA", "BB", 1)).contains("22"); assertThat(typeMap.gett(Object.class, "AA", "CC", 0)).contains("33"); assertThat(typeMap.gett(Object.class, "AA", "CC", 1)).contains("44"); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD")).contains(anObject); assertThat(typeMap.gett(UnknownClass.class, "AA", "DD", anObject)).isEmpty(); } @Test void testDefaultMapMethods() { final String myTime = new Date(TEST_TIME).toString(); // Broken json assertThat(new TypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new LinkedTypeMap("{ broken json")).containsEntry("", "{ broken json"); assertThat(new ConcurrentTypeMap("{ broken json")).containsEntry("", "{ broken json"); final TypeMap map1 = new TypeMap().putt("myKey", myTime); final LinkedTypeMap map2 = new LinkedTypeMap().putt("myKey", myTime); final ConcurrentTypeMap map3 = new ConcurrentTypeMap().putt("myKey", myTime); // Get assertThat(map1.get("myKey")).isNotNull(); assertThat(map2.get("myKey")).isNotNull(); assertThat(map3.get("myKey")).isNotNull(); } @Test void argsTest() { final String[] cliArgs = {" myCommand1 myCommand2 --help -v2=\"true\" -v=\"true\" -v=\"true\" --verbose=\"true\" -DArgs=\"true\" -param 42 54 -DArgList=\"item 1\" --DArgList=\"item 2\" -v2=\"false\" --DArgList=\"-item 3\" "}; final TypeMap map1 = new TypeMap(cliArgs); final LinkedTypeMap map2 = new LinkedTypeMap(cliArgs); final ConcurrentTypeMap map3 = new ConcurrentTypeMap(cliArgs); for (final TypeMapI<?> map : new TypeMapI<?>[]{map1, map2, map3}) { assertThat(map.get("help", Boolean.class)).isTrue(); assertThat(map.get("v", Boolean.class)).isTrue(); assertThat(map.get("v2", Boolean.class)).isTrue(); assertThat(map.get("verbose", Boolean.class)).isTrue(); assertThat(map.get("DArgs", Boolean.class)).isTrue(); assertThat(map.getList("param", Integer.class)).containsExactly(42, 54); assertThat(map.getList("v2", Boolean.class)).containsExactly(true, false); assertThat(map.getList("DArgList")).containsExactly("item 1", "item 2", "-item 3"); assertThat(map.getList("DArgList", String.class)).containsExactly("item 1", "item 2", "-item 3"); } } @Test void showCaseTest() { // Converter
final Date date = TypeConverter.convertObj("Sat Nov 11 16:12:29 CET 2023", Date.class);
1
2023-11-09 14:40:13+00:00
16k
estkme-group/InfiLPA
app/src/main/java/com/infineon/esim/lpa/lpa/LocalProfileAssistant.java
[ { "identifier": "LocalProfileAssistantCoreImpl", "path": "core/src/main/java/com/infineon/esim/lpa/core/LocalProfileAssistantCoreImpl.java", "snippet": "public class LocalProfileAssistantCoreImpl implements LocalProfileAssistantCore {\n private static final String TAG = LocalProfileAssistantCoreImpl....
import androidx.lifecycle.MutableLiveData; import com.infineon.esim.lpa.core.LocalProfileAssistantCoreImpl; import com.infineon.esim.lpa.core.dtos.ActivationCode; import com.infineon.esim.lpa.core.dtos.EuiccInfo; import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType; import com.infineon.esim.lpa.core.dtos.profile.ProfileList; import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata; import com.infineon.esim.lpa.core.dtos.result.remote.AuthenticateResult; import com.infineon.esim.lpa.core.dtos.result.remote.CancelSessionResult; import com.infineon.esim.lpa.core.dtos.result.remote.DownloadResult; import com.infineon.esim.lpa.data.StatusAndEventHandler; import com.infineon.esim.lpa.euicc.EuiccManager; import com.infineon.esim.lpa.euicc.base.EuiccConnection; import com.infineon.esim.lpa.euicc.base.EuiccConnectionConsumer; import com.infineon.esim.lpa.lpa.task.AuthenticateTask; import com.infineon.esim.lpa.lpa.task.CancelSessionTask; import com.infineon.esim.lpa.lpa.task.DownloadTask; import com.infineon.esim.lpa.lpa.task.GetEuiccInfoTask; import com.infineon.esim.lpa.lpa.task.GetProfileListTask; import com.infineon.esim.lpa.lpa.task.HandleAndClearAllNotificationsTask; import com.infineon.esim.lpa.lpa.task.ProfileActionTask; import com.infineon.esim.lpa.ui.generic.ActionStatus; import com.infineon.esim.lpa.ui.generic.Error; import com.infineon.esim.lpa.util.android.InternetConnectionConsumer; import com.infineon.esim.lpa.util.threading.TaskRunner; import com.infineon.esim.util.Log;
14,315
/* * 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.lpa; public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer { private static final String TAG = LocalProfileAssistant.class.getName(); private final StatusAndEventHandler statusAndEventHandler; private final MutableLiveData<ProfileList> profileList; private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver; private EuiccConnection euiccConnection;
/* * 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.lpa; public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer { private static final String TAG = LocalProfileAssistant.class.getName(); private final StatusAndEventHandler statusAndEventHandler; private final MutableLiveData<ProfileList> profileList; private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver; private EuiccConnection euiccConnection;
private EuiccInfo euiccInfo;
2
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;
12,189
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;
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;
11
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;
13,073
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; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId);
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; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){ List<User> users=uDao.findByFatherId(userId); NoticesList nl=informDao.findOne(noticeId);
List<NoticeUserRelation> nurs=new ArrayList<>();
11
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,757
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;
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);
2
2023-11-06 21:25:54+00:00
16k
By1337/BAuction
Core/src/main/java/org/by1337/bauction/db/kernel/CSellItem.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.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.by1337.api.BLib; import org.by1337.bauction.Main; import org.by1337.bauction.auc.SellItem; import org.by1337.bauction.lang.Lang; import org.by1337.bauction.serialize.SerializeUtils; import org.by1337.bauction.util.CUniqueName; import org.by1337.bauction.util.NumberUtil; import org.by1337.bauction.util.TagUtil; import org.by1337.bauction.util.UniqueName; import org.jetbrains.annotations.NotNull; import java.io.*; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*;
12,417
String sellerName = in.readUTF(); UUID sellerUuid = SerializeUtils.readUUID(in); double price = in.readDouble(); boolean saleByThePiece = in.readBoolean(); Set<String> tags = new HashSet<>(SerializeUtils.readCollectionFromStream(in)); long timeListedForSale = in.readLong(); long removalDate = in.readLong(); UniqueName uniqueName = new CUniqueName( in.readUTF() ); Material material = Material.valueOf(in.readUTF()); int amount = in.readInt(); double priceForOne = in.readDouble(); Set<String> sellFor = new HashSet<>(SerializeUtils.readCollectionFromStream(in)); String server = in.readUTF(); return new CSellItem( item, sellerName, sellerUuid, price, saleByThePiece, tags, timeListedForSale, removalDate, uniqueName, material, amount, priceForOne, sellFor, null, server ); } } public String getItem() { return item; } public String getSellerName() { return sellerName; } public UUID getSellerUuid() { return sellerUuid; } public double getPrice() { return price; } public boolean isSaleByThePiece() { return saleByThePiece; } public Set<String> getTags() { return tags; } public long getTimeListedForSale() { return timeListedForSale; } public long getRemovalDate() { return removalDate; } public UniqueName getUniqueName() { return uniqueName; } public Material getMaterial() { return material; } public int getAmount() { return amount; } public double getPriceForOne() { return priceForOne; } // public Set<String> getSellFor() { // return sellFor; // } @Override public String toString() { return "CSellItem{" + "item='" + item + '\'' + ", sellerName='" + sellerName + '\'' + ", sellerUuid=" + sellerUuid + ", price=" + price + ", saleByThePiece=" + saleByThePiece + ", tags=" + tags + ", timeListedForSale=" + timeListedForSale + ", removalDate=" + removalDate + ", uniqueName=" + uniqueName + ", material=" + material + ", amount=" + amount + ", priceForOne=" + priceForOne + ", sellFor=" + sellFor + ", server='" + server + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CSellItem sellItem)) return false; return Double.compare(getPrice(), sellItem.getPrice()) == 0 && isSaleByThePiece() == sellItem.isSaleByThePiece() && getTimeListedForSale() == sellItem.getTimeListedForSale() && getRemovalDate() == sellItem.getRemovalDate() && getAmount() == sellItem.getAmount() && Double.compare(getPriceForOne(), sellItem.getPriceForOne()) == 0 && Objects.equals(getItem(), sellItem.getItem()) && Objects.equals(getSellerName(), sellItem.getSellerName()) && Objects.equals(getSellerUuid(), sellItem.getSellerUuid()) && Objects.equals(getTags(), sellItem.getTags()) && Objects.equals(getUniqueName(), sellItem.getUniqueName()) && getMaterial() == sellItem.getMaterial() && Objects.equals(sellFor, sellItem.sellFor) && Objects.equals(getItemStack(), sellItem.getItemStack()); } @Override public int hashCode() { return Arrays.hashCode(uniqueName.getKey().toCharArray()); } @Override public String replace(String s) { StringBuilder sb = new StringBuilder(s); while (true) { if (sb.indexOf("{seller_uuid}") != -1) { sb.replace(sb.indexOf("{seller_uuid}"), sb.indexOf("{seller_uuid}") + "{seller_uuid}".length(), sellerUuid.toString()); continue; } if (sb.indexOf("{seller_name}") != -1) { sb.replace(sb.indexOf("{seller_name}"), sb.indexOf("{seller_name}") + "{seller_name}".length(), sellerName); continue; } if (sb.indexOf("{price}") != -1) {
package org.by1337.bauction.db.kernel; public class CSellItem implements SellItem { final String item; final String sellerName; final UUID sellerUuid; final double price; final boolean saleByThePiece; final Set<String> tags; final long timeListedForSale; final long removalDate; final UniqueName uniqueName; final Material material; final int amount; final double priceForOne; final Set<String> sellFor; transient ItemStack itemStack; final String server; public static CSellItemBuilder builder() { return new CSellItemBuilder(); } @Override public String toSql(String table) { return String.format( "INSERT INTO %s (uuid, seller_uuid, item, seller_name, price, sale_by_the_piece, tags, time_listed_for_sale, removal_date, material, amount, price_for_one, sell_for, server)" + "VALUES('%s', '%s', '%s', '%s', %s, %s, '%s', %s, %s, '%s', %s, %s, '%s', '%s')", table, uniqueName.getKey(), sellerUuid, item, sellerName, price, saleByThePiece, listToString(tags), timeListedForSale, removalDate, material.name(), amount, priceForOne, listToString(sellFor), server ); } public static CSellItem fromResultSet(ResultSet resultSet) throws SQLException { return CSellItem.builder() .uniqueName(new CUniqueName(resultSet.getString("uuid"))) .sellerUuid(UUID.fromString(resultSet.getString("seller_uuid"))) .item(resultSet.getString("item")) .sellerName(resultSet.getString("seller_name")) .price(resultSet.getDouble("price")) .saleByThePiece(resultSet.getBoolean("sale_by_the_piece")) .tags(new HashSet<>(Arrays.asList(resultSet.getString("tags").split(",")))) .timeListedForSale(resultSet.getLong("time_listed_for_sale")) .removalDate(resultSet.getLong("removal_date")) .material(Material.valueOf(resultSet.getString("material"))) .amount(resultSet.getInt("amount")) .priceForOne(resultSet.getDouble("price_for_one")) .sellFor(new HashSet<>(Arrays.asList(resultSet.getString("sell_for").split(",")))) .server(resultSet.getString("server")) .build(); } private static String listToString(Collection<? extends CharSequence> collection) { return String.join(",", collection); } public CSellItem(String item, String sellerName, UUID sellerUuid, double price, boolean saleByThePiece, Set<String> tags, long timeListedForSale, long removalDate, UniqueName uniqueName, Material material, int amount, double priceForOne, Set<String> sellFor, ItemStack itemStack, String server) { this.server = server; this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = tags; this.timeListedForSale = timeListedForSale; this.removalDate = removalDate; this.uniqueName = uniqueName; this.material = material; this.amount = amount; this.priceForOne = priceForOne; this.sellFor = sellFor; this.itemStack = itemStack; } public CSellItem(String item, String sellerName, UUID sellerUuid, double price, boolean saleByThePiece, Set<String> tags, long timeListedForSale, long removalDate, UniqueName uniqueName, Material material, int amount, double priceForOne, ItemStack itemStack) { this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = tags; this.timeListedForSale = timeListedForSale; this.removalDate = removalDate; this.uniqueName = uniqueName; this.material = material; this.amount = amount; this.priceForOne = priceForOne; this.itemStack = itemStack; sellFor = new HashSet<>(); server = Main.getServerId(); } public CSellItem(String item, String sellerName, UUID sellerUuid, double price, boolean saleByThePiece, Set<String> tags, long timeListedForSale, long removalDate, UniqueName uniqueName, Material material, int amount, double priceForOne) { this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = tags; this.timeListedForSale = timeListedForSale; this.removalDate = removalDate; this.uniqueName = uniqueName; this.material = material; this.amount = amount; this.priceForOne = priceForOne; sellFor = new HashSet<>(); server = Main.getServerId(); } public CSellItem(@NotNull String item, @NotNull String sellerName, @NotNull UUID sellerUuid, double price, boolean saleByThePiece, @NotNull Set<String> tags, long saleDuration, @NotNull Material material, int amount) { this.item = item; this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; this.tags = Collections.unmodifiableSet(tags); this.timeListedForSale = System.currentTimeMillis(); this.removalDate = System.currentTimeMillis() + saleDuration; this.uniqueName = Main.getUniqueNameGenerator().getNextCombination(); this.material = material; this.amount = amount; priceForOne = price / amount; sellFor = new HashSet<>(); server = Main.getServerId(); } public CSellItem(@NotNull Player seller, @NotNull ItemStack itemStack, double price, long saleDuration) { this(seller, itemStack, price, saleDuration, true); } public CSellItem(@NotNull Player seller, @NotNull ItemStack itemStack, double price, long saleDuration, boolean saleByThePiece) { item = BLib.getApi().getItemStackSerialize().serialize(itemStack); sellerName = seller.getName(); sellerUuid = seller.getUniqueId(); this.price = price; this.saleByThePiece = saleByThePiece; tags = Collections.unmodifiableSet(TagUtil.getTags(itemStack)); timeListedForSale = System.currentTimeMillis(); this.removalDate = System.currentTimeMillis() + saleDuration; this.uniqueName = Main.getUniqueNameGenerator().getNextCombination(); material = itemStack.getType(); amount = itemStack.getAmount(); priceForOne = saleByThePiece ? price / amount : price; sellFor = new HashSet<>(); server = Main.getServerId(); } public CSellItem(String sellerName, UUID sellerUuid, @NotNull ItemStack itemStack, double price, long saleDuration, boolean saleByThePiece) { item = BLib.getApi().getItemStackSerialize().serialize(itemStack); this.sellerName = sellerName; this.sellerUuid = sellerUuid; this.price = price; this.saleByThePiece = saleByThePiece; tags = Collections.unmodifiableSet(TagUtil.getTags(itemStack)); timeListedForSale = System.currentTimeMillis(); this.removalDate = System.currentTimeMillis() + saleDuration; this.uniqueName = Main.getUniqueNameGenerator().getNextCombination(); material = itemStack.getType(); amount = itemStack.getAmount(); priceForOne = saleByThePiece ? price / amount : price; sellFor = new HashSet<>(); server = Main.getServerId(); } static CSellItem parse(SellItem item) { return new CSellItem( BLib.getApi().getItemStackSerialize().serialize(item.getItemStack()), item.getSellerName(), item.getSellerUuid(), item.getPrice(), item.isSaleByThePiece(), item.getTags(), item.getTimeListedForSale(), item.getRemovalDate(), item.getUniqueName(), item.getMaterial(), item.getAmount(), item.getPriceForOne(), new HashSet<>(), item.getItemStack(), item.getServer() ); } public ItemStack getItemStack() { if (itemStack == null) { itemStack = BLib.getApi().getItemStackSerialize().deserialize(item); } return itemStack.clone(); } public boolean isValid() { return item != null && sellerName != null && sellerUuid != null && tags != null && uniqueName != null && material != null && sellFor != null && server != null; } @Override public byte[] getBytes() throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(out)) { data.writeUTF(item); data.writeUTF(sellerName); SerializeUtils.writeUUID(sellerUuid, data); data.writeDouble(price); data.writeBoolean(saleByThePiece); SerializeUtils.writeCollectionToStream(data, tags); data.writeLong(timeListedForSale); data.writeLong(removalDate); data.writeUTF(uniqueName.getKey()); data.writeUTF(material.name()); data.writeInt(amount); data.writeDouble(priceForOne); SerializeUtils.writeCollectionToStream(data, sellFor); data.writeUTF(server); data.flush(); return out.toByteArray(); } } public static CSellItem fromBytes(byte[] arr) throws IOException { try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(arr))) { String item = in.readUTF(); String sellerName = in.readUTF(); UUID sellerUuid = SerializeUtils.readUUID(in); double price = in.readDouble(); boolean saleByThePiece = in.readBoolean(); Set<String> tags = new HashSet<>(SerializeUtils.readCollectionFromStream(in)); long timeListedForSale = in.readLong(); long removalDate = in.readLong(); UniqueName uniqueName = new CUniqueName( in.readUTF() ); Material material = Material.valueOf(in.readUTF()); int amount = in.readInt(); double priceForOne = in.readDouble(); Set<String> sellFor = new HashSet<>(SerializeUtils.readCollectionFromStream(in)); String server = in.readUTF(); return new CSellItem( item, sellerName, sellerUuid, price, saleByThePiece, tags, timeListedForSale, removalDate, uniqueName, material, amount, priceForOne, sellFor, null, server ); } } public String getItem() { return item; } public String getSellerName() { return sellerName; } public UUID getSellerUuid() { return sellerUuid; } public double getPrice() { return price; } public boolean isSaleByThePiece() { return saleByThePiece; } public Set<String> getTags() { return tags; } public long getTimeListedForSale() { return timeListedForSale; } public long getRemovalDate() { return removalDate; } public UniqueName getUniqueName() { return uniqueName; } public Material getMaterial() { return material; } public int getAmount() { return amount; } public double getPriceForOne() { return priceForOne; } // public Set<String> getSellFor() { // return sellFor; // } @Override public String toString() { return "CSellItem{" + "item='" + item + '\'' + ", sellerName='" + sellerName + '\'' + ", sellerUuid=" + sellerUuid + ", price=" + price + ", saleByThePiece=" + saleByThePiece + ", tags=" + tags + ", timeListedForSale=" + timeListedForSale + ", removalDate=" + removalDate + ", uniqueName=" + uniqueName + ", material=" + material + ", amount=" + amount + ", priceForOne=" + priceForOne + ", sellFor=" + sellFor + ", server='" + server + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CSellItem sellItem)) return false; return Double.compare(getPrice(), sellItem.getPrice()) == 0 && isSaleByThePiece() == sellItem.isSaleByThePiece() && getTimeListedForSale() == sellItem.getTimeListedForSale() && getRemovalDate() == sellItem.getRemovalDate() && getAmount() == sellItem.getAmount() && Double.compare(getPriceForOne(), sellItem.getPriceForOne()) == 0 && Objects.equals(getItem(), sellItem.getItem()) && Objects.equals(getSellerName(), sellItem.getSellerName()) && Objects.equals(getSellerUuid(), sellItem.getSellerUuid()) && Objects.equals(getTags(), sellItem.getTags()) && Objects.equals(getUniqueName(), sellItem.getUniqueName()) && getMaterial() == sellItem.getMaterial() && Objects.equals(sellFor, sellItem.sellFor) && Objects.equals(getItemStack(), sellItem.getItemStack()); } @Override public int hashCode() { return Arrays.hashCode(uniqueName.getKey().toCharArray()); } @Override public String replace(String s) { StringBuilder sb = new StringBuilder(s); while (true) { if (sb.indexOf("{seller_uuid}") != -1) { sb.replace(sb.indexOf("{seller_uuid}"), sb.indexOf("{seller_uuid}") + "{seller_uuid}".length(), sellerUuid.toString()); continue; } if (sb.indexOf("{seller_name}") != -1) { sb.replace(sb.indexOf("{seller_name}"), sb.indexOf("{seller_name}") + "{seller_name}".length(), sellerName); continue; } if (sb.indexOf("{price}") != -1) {
sb.replace(sb.indexOf("{price}"), sb.indexOf("{price}") + "{price}".length(), NumberUtil.format(price));
5
2023-11-08 18:25:18+00:00
16k
YufiriaMazenta/CrypticLib
nms/src/main/java/crypticlib/nms/nbt/NbtFactory.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 com.google.gson.JsonObject; import crypticlib.CrypticLib; import crypticlib.nms.nbt.v1_12_R1.V1_12_R1NbtTagCompound; import crypticlib.nms.nbt.v1_13_R1.V1_13_R1NbtTagCompound; import crypticlib.nms.nbt.v1_13_R2.V1_13_R2NbtTagCompound; import crypticlib.nms.nbt.v1_14_R1.V1_14_R1NbtTagCompound; import crypticlib.nms.nbt.v1_15_R1.V1_15_R1NbtTagCompound; import crypticlib.nms.nbt.v1_16_R1.V1_16_R1NbtTagCompound; import crypticlib.nms.nbt.v1_16_R2.V1_16_R2NbtTagCompound; import crypticlib.nms.nbt.v1_16_R3.V1_16_R3NbtTagCompound; import crypticlib.nms.nbt.v1_17_R1.V1_17_R1NbtTagCompound; import crypticlib.nms.nbt.v1_18_R1.V1_18_R1NbtTagCompound; import crypticlib.nms.nbt.v1_18_R2.V1_18_R2NbtTagCompound; import crypticlib.nms.nbt.v1_19_R1.V1_19_R1NbtTagCompound; import crypticlib.nms.nbt.v1_19_R2.V1_19_R2NbtTagCompound; import crypticlib.nms.nbt.v1_19_R3.V1_19_R3NbtTagCompound; import crypticlib.nms.nbt.v1_20_R1.V1_20_R1NbtTagCompound; import crypticlib.nms.nbt.v1_20_R2.V1_20_R2NbtTagCompound; import crypticlib.nms.nbt.v1_20_R3.V1_20_R3NbtTagCompound; import crypticlib.util.JsonUtil; import crypticlib.util.YamlConfigUtil; import org.bukkit.configuration.ConfigurationSection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Supplier;
11,270
package crypticlib.nms.nbt; /** * CrypticLib的Nbt提供工厂 */ public class NbtFactory { private static final Map<String, Function<Map<String, Object>, NbtTagCompound>> nbtTagCompoundProviderMap; private static final Map<String, Supplier<NbtTagCompound>> emptyNbtTagCompoundProviderMap; private static final Map<String, Function<String, NbtTagCompound>> mojangsonToNbtCompoundProviderMap; static { nbtTagCompoundProviderMap = new ConcurrentHashMap<>(); emptyNbtTagCompoundProviderMap = new ConcurrentHashMap<>(); mojangsonToNbtCompoundProviderMap = new ConcurrentHashMap<>(); regNbtTagCompoundProvider("v1_12_R1", V1_12_R1NbtTagCompound::new, V1_12_R1NbtTagCompound::new, V1_12_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_13_R1", V1_13_R1NbtTagCompound::new, V1_13_R1NbtTagCompound::new, V1_13_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_13_R2", V1_13_R2NbtTagCompound::new, V1_13_R2NbtTagCompound::new, V1_13_R2NbtTagCompound::new); regNbtTagCompoundProvider("v1_14_R1", V1_14_R1NbtTagCompound::new, V1_14_R1NbtTagCompound::new, V1_14_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_15_R1", V1_15_R1NbtTagCompound::new, V1_15_R1NbtTagCompound::new, V1_15_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_16_R1", V1_16_R1NbtTagCompound::new, V1_16_R1NbtTagCompound::new, V1_16_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_16_R2", V1_16_R2NbtTagCompound::new, V1_16_R2NbtTagCompound::new, V1_16_R2NbtTagCompound::new); regNbtTagCompoundProvider("v1_16_R3", V1_16_R3NbtTagCompound::new, V1_16_R3NbtTagCompound::new, V1_16_R3NbtTagCompound::new); regNbtTagCompoundProvider("v1_17_R1", V1_17_R1NbtTagCompound::new, V1_17_R1NbtTagCompound::new, V1_17_R1NbtTagCompound::new);
package crypticlib.nms.nbt; /** * CrypticLib的Nbt提供工厂 */ public class NbtFactory { private static final Map<String, Function<Map<String, Object>, NbtTagCompound>> nbtTagCompoundProviderMap; private static final Map<String, Supplier<NbtTagCompound>> emptyNbtTagCompoundProviderMap; private static final Map<String, Function<String, NbtTagCompound>> mojangsonToNbtCompoundProviderMap; static { nbtTagCompoundProviderMap = new ConcurrentHashMap<>(); emptyNbtTagCompoundProviderMap = new ConcurrentHashMap<>(); mojangsonToNbtCompoundProviderMap = new ConcurrentHashMap<>(); regNbtTagCompoundProvider("v1_12_R1", V1_12_R1NbtTagCompound::new, V1_12_R1NbtTagCompound::new, V1_12_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_13_R1", V1_13_R1NbtTagCompound::new, V1_13_R1NbtTagCompound::new, V1_13_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_13_R2", V1_13_R2NbtTagCompound::new, V1_13_R2NbtTagCompound::new, V1_13_R2NbtTagCompound::new); regNbtTagCompoundProvider("v1_14_R1", V1_14_R1NbtTagCompound::new, V1_14_R1NbtTagCompound::new, V1_14_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_15_R1", V1_15_R1NbtTagCompound::new, V1_15_R1NbtTagCompound::new, V1_15_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_16_R1", V1_16_R1NbtTagCompound::new, V1_16_R1NbtTagCompound::new, V1_16_R1NbtTagCompound::new); regNbtTagCompoundProvider("v1_16_R2", V1_16_R2NbtTagCompound::new, V1_16_R2NbtTagCompound::new, V1_16_R2NbtTagCompound::new); regNbtTagCompoundProvider("v1_16_R3", V1_16_R3NbtTagCompound::new, V1_16_R3NbtTagCompound::new, V1_16_R3NbtTagCompound::new); regNbtTagCompoundProvider("v1_17_R1", V1_17_R1NbtTagCompound::new, V1_17_R1NbtTagCompound::new, V1_17_R1NbtTagCompound::new);
regNbtTagCompoundProvider("v1_18_R1", V1_18_R1NbtTagCompound::new, V1_18_R1NbtTagCompound::new, V1_18_R1NbtTagCompound::new);
10
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;
13,047
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; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){
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; @Autowired private DeptDao deptDao; @Autowired private InformRelationDao informrelationDao; @Autowired private InformRelationService informrelationservice; @Autowired private NoticeMapper nm; /** * 通知管理面板 * * @return */ @RequestMapping("infrommanage") public String inform(@RequestParam(value = "page", defaultValue = "0") int page,@SessionAttribute("userId") Long userId,Model model) { Page<NoticesList> page2 = informService.pageThis(page,userId); List<NoticesList> noticeList=page2.getContent(); List<Map<String, Object>> list=informService.fengZhuang(noticeList); model.addAttribute("list", list); model.addAttribute("page", page2); //设置变量,需要load的url; model.addAttribute("url", "infrommanagepaging"); return "inform/informmanage"; } @RequestMapping("forwardother") public String forwardOther(@SessionAttribute("userId")Long userId,@RequestParam(value="noticeId")Long noticeId){
List<User> users=uDao.findByFatherId(userId);
17
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;
13,525
/* * 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
/* * 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();
2
2023-11-03 23:19:08+00:00
16k
data-harness-cloud/data_harness-be
application-webadmin/src/main/java/supie/webadmin/interceptor/AuthenticationInterceptor.java
[ { "identifier": "CacheConfig", "path": "common/common-core/src/main/java/supie/common/core/cache/CacheConfig.java", "snippet": "@Configuration\n@EnableCaching\npublic class CacheConfig {\n\n private static final int DEFAULT_MAXSIZE = 10000;\n private static final int DEFAULT_TTL = 3600;\n\n /**...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.text.StrFormatter; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpResponse; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import supie.common.core.annotation.NoAuthInterface; import supie.common.core.cache.CacheConfig; import supie.common.core.constant.ApplicationConstant; import supie.common.core.constant.DataPermRuleType; import supie.common.core.constant.ErrorCodeEnum; import supie.common.core.exception.MyRuntimeException; import supie.common.core.object.ResponseResult; import supie.common.core.object.TokenData; import supie.common.core.util.ApplicationContextHolder; import supie.common.core.util.JwtUtil; import supie.common.core.util.RedisKeyUtil; import supie.webadmin.config.ApplicationConfig; import supie.webadmin.config.ThirdPartyAuthConfig; import io.jsonwebtoken.Claims; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.redisson.api.RBucket; import org.redisson.api.RSet; import org.redisson.api.RedissonClient; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.util.Assert; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors;
12,561
package supie.webadmin.interceptor; /** * 登录用户Token验证、生成和权限验证的拦截器。 * * @author rm -rf .bug * @date 2020-11-12 */ @Slf4j public class AuthenticationInterceptor implements HandlerInterceptor { private final ApplicationConfig appConfig = ApplicationContextHolder.getBean("applicationConfig"); private final ThirdPartyAuthConfig thirdPartyAuthConfig = ApplicationContextHolder.getBean("thirdPartyAuthConfig"); private final RedissonClient redissonClient = ApplicationContextHolder.getBean(RedissonClient.class); private final CacheManager cacheManager = ApplicationContextHolder.getBean("caffeineCacheManager"); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String url = request.getRequestURI(); String token = this.getTokenFromRequest(request); boolean noLoginUrl = this.isNoAuthInterface(handler); // 如果接口方法标记NoAuthInterface注解,可以直接跳过Token鉴权验证,这里主要为了测试接口方便 if (noLoginUrl && StrUtil.isBlank(token)) { return true; } String appCode = this.getAppCodeFromRequest(request); if (StrUtil.isNotBlank(appCode)) { return this.handleThirdPartyRequest(appCode, token, url, response); }
package supie.webadmin.interceptor; /** * 登录用户Token验证、生成和权限验证的拦截器。 * * @author rm -rf .bug * @date 2020-11-12 */ @Slf4j public class AuthenticationInterceptor implements HandlerInterceptor { private final ApplicationConfig appConfig = ApplicationContextHolder.getBean("applicationConfig"); private final ThirdPartyAuthConfig thirdPartyAuthConfig = ApplicationContextHolder.getBean("thirdPartyAuthConfig"); private final RedissonClient redissonClient = ApplicationContextHolder.getBean(RedissonClient.class); private final CacheManager cacheManager = ApplicationContextHolder.getBean("caffeineCacheManager"); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String url = request.getRequestURI(); String token = this.getTokenFromRequest(request); boolean noLoginUrl = this.isNoAuthInterface(handler); // 如果接口方法标记NoAuthInterface注解,可以直接跳过Token鉴权验证,这里主要为了测试接口方便 if (noLoginUrl && StrUtil.isBlank(token)) { return true; } String appCode = this.getAppCodeFromRequest(request); if (StrUtil.isNotBlank(appCode)) { return this.handleThirdPartyRequest(appCode, token, url, response); }
Claims c = JwtUtil.parseToken(token, appConfig.getTokenSigningKey());
8
2023-11-04 12:36:44+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;
11,604
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); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_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); leftFront = hardwareMap.get(DcMotorEx.class, "lf"); leftRear = hardwareMap.get(DcMotorEx.class, "lb"); rightRear = hardwareMap.get(DcMotorEx.class, "rb"); rightFront = hardwareMap.get(DcMotorEx.class, "rf"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); 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() leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method // setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); setLocalizer(new TwoWheelTrackingLocalizer(hardwareMap, this)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); }
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); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_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); leftFront = hardwareMap.get(DcMotorEx.class, "lf"); leftRear = hardwareMap.get(DcMotorEx.class, "lb"); rightRear = hardwareMap.get(DcMotorEx.class, "rb"); rightFront = hardwareMap.get(DcMotorEx.class, "rf"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); 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() leftFront.setDirection(DcMotorSimple.Direction.REVERSE); leftRear.setDirection(DcMotorSimple.Direction.REVERSE); List<Integer> lastTrackingEncPositions = new ArrayList<>(); List<Integer> lastTrackingEncVels = new ArrayList<>(); // TODO: if desired, use setLocalizer() to change the localization method // setLocalizer(new StandardTrackingWheelLocalizer(hardwareMap, lastTrackingEncPositions, lastTrackingEncVels)); setLocalizer(new TwoWheelTrackingLocalizer(hardwareMap, this)); trajectorySequenceRunner = new TrajectorySequenceRunner( follower, HEADING_PID, batteryVoltageSensor, lastEncPositions, lastEncVels, lastTrackingEncPositions, lastTrackingEncVels ); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose) { return new TrajectoryBuilder(startPose, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, boolean reversed) { return new TrajectoryBuilder(startPose, reversed, VEL_CONSTRAINT, ACCEL_CONSTRAINT); } public TrajectoryBuilder trajectoryBuilder(Pose2d startPose, double startHeading) { return new TrajectoryBuilder(startPose, startHeading, VEL_CONSTRAINT, ACCEL_CONSTRAINT); }
public TrajectorySequenceBuilder trajectorySequenceBuilder(Pose2d startPose) {
1
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,359
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
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;
0
2023-11-01 12:37:16+00:00
16k
FallenDeity/GameEngine2DJava
src/main/java/engine/components/QuestionBlock.java
[ { "identifier": "JImGui", "path": "src/main/java/engine/editor/JImGui.java", "snippet": "public class JImGui {\n\tpublic static void drawVec2Control(String name, Vector2f values) {\n\t\tdrawVec2Control(name, values, 0.0f);\n\t}\n\n\tpublic static void drawVec2Control(String name, Vector2f values, float ...
import engine.editor.JImGui; import engine.ruby.Window; import engine.util.Prefabs;
11,655
package engine.components; public class QuestionBlock extends Block { private int amount = 1; private BlockType type = BlockType.COIN; @Override public void imGui() { type = JImGui.comboEnum("Type", type); if (type == BlockType.COIN) { amount = JImGui.dragInt("Amount", amount); } } @Override void playerHit(PlayerController player) { switch (type) { case COIN -> addCoin(); case GROW -> addGrow(); case FIRE -> addFire(); case INVINCIBILITY -> addInvincibility(); } StateMachine stateMachine = getGameObject().getComponent(StateMachine.class); if (stateMachine != null) { stateMachine.trigger("setInactive"); setInactive(); } } private void addCoin() {
package engine.components; public class QuestionBlock extends Block { private int amount = 1; private BlockType type = BlockType.COIN; @Override public void imGui() { type = JImGui.comboEnum("Type", type); if (type == BlockType.COIN) { amount = JImGui.dragInt("Amount", amount); } } @Override void playerHit(PlayerController player) { switch (type) { case COIN -> addCoin(); case GROW -> addGrow(); case FIRE -> addFire(); case INVINCIBILITY -> addInvincibility(); } StateMachine stateMachine = getGameObject().getComponent(StateMachine.class); if (stateMachine != null) { stateMachine.trigger("setInactive"); setInactive(); } } private void addCoin() {
GameObject coin = Prefabs.generateCoinBlock();
2
2023-11-04 13:19:21+00:00
16k
RezaGooner/University-food-ordering
Frames/Admin/FoodManagment/OrdersManage.java
[ { "identifier": "icon", "path": "Classes/Pathes/FilesPath.java", "snippet": "public static ImageIcon icon = new ImageIcon(\"Source/icon.png\");\r" }, { "identifier": "errorSound", "path": "Classes/Theme/SoundEffect.java", "snippet": "public static void errorSound() throws IOException, Un...
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.*; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter; import static Classes.Pathes.FilesPath.icon; import static Classes.Theme.SoundEffect.errorSound; import static Frames.Order.UniversitySelfRestaurant.*;
13,216
JPanel searchPanel = new JPanel(); JTextField searchField = new JTextField(20); searchField.addActionListener(e -> { String text = searchField.getText(); if (text.length() == 0) { sorter.setRowFilter(null); } else { sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text)); } }); searchPanel.add(searchField); JButton addButton = new JButton("اضافه کردن"); addButton.addActionListener(e -> { String id = JOptionPane.showInputDialog(this, "شناسه را وارد نمایید :"); if (id != null) { String date = JOptionPane.showInputDialog(this, "تاریخ را وارد نمایید : YYYY-MM-DD"); if (date != null) { String lunch = (String) JOptionPane.showInputDialog(this, "ناهار را انتخاب کنید :", "ناهار", JOptionPane.PLAIN_MESSAGE, null, lunchOptions, lunchOptions[0]); if (lunch != null){ String dinner = (String) JOptionPane.showInputDialog(this, "شام را انتخاب کنید :", "شام", JOptionPane.PLAIN_MESSAGE, null, dinnerOptions, dinnerOptions[0]); if (dinner != null) { String[] row = { id, date, lunch, dinner }; data.add(row); tableModel.addRow(row); try { saveToFile(); } catch (Exception ex) { } } } } } }); JButton editButton = new JButton("ویرایش "); editButton.addActionListener(e -> { int selectedRow = table.getSelectedRow(); if (selectedRow != -1) { String id = JOptionPane.showInputDialog(this, "شناسه را وارد نمایید :", table.getValueAt(selectedRow, 0)); if (id != null) { String date = JOptionPane.showInputDialog(this, "تاریخ را وارد نمایید : YYYY-MM-DD\n", table.getValueAt(selectedRow, 1)); if (date != null) { String lunch = (String) JOptionPane.showInputDialog(this, "ناهار جایگزین " + table.getValueAt(selectedRow, 2) + " را انتخاب کنید : ", "ناهار", JOptionPane.PLAIN_MESSAGE, null, lunchOptions, lunchOptions[0]); if (lunch != null) { String dinner = (String) JOptionPane.showInputDialog(this, "شام جایگزین " + table.getValueAt(selectedRow, 3) + " را انتخاب کنید : ", "شام", JOptionPane.PLAIN_MESSAGE, null, dinnerOptions, dinnerOptions[0]); if (dinner != null) { String[] row = { id, date, lunch, dinner }; data.set(selectedRow, row); tableModel.setValueAt(id, selectedRow, 0); tableModel.setValueAt(date, selectedRow, 1); tableModel.setValueAt(lunch, selectedRow, 2); tableModel.setValueAt(dinner, selectedRow, 3); try { saveToFile(); } catch (Exception ex) { } } } } } } else { JOptionPane.showMessageDialog(this, "لطفا یک فیلد را انتخاب نمایید."); } }); JButton deleteButton = new JButton("حذف"); deleteButton.addActionListener(e -> { int selectedRow = table.getSelectedRow(); if (selectedRow != -1) { data.remove(selectedRow); tableModel.removeRow(selectedRow); try { saveToFile(); } catch (Exception ex) { } } else { JOptionPane.showMessageDialog(this, "لطفا یک فیلد را انتخاب نمایید."); } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(addButton); buttonPanel.add(editButton); buttonPanel.add(deleteButton); add(new JScrollPane(table)); add(searchPanel, "North"); add(buttonPanel, "South"); sorter = new TableRowSorter<>(tableModel); table.setRowSorter(sorter); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu menu = new JMenu("بیشتر"); menuBar.add(menu); JMenuItem refreshButton = new JMenuItem("تازه سازی"); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); try { new OrdersManage(); } catch (Exception ignored) { } } }); menu.add(refreshButton);
package Frames.Admin.FoodManagment; /* این کد یک پنجره مدیریت سفارشات را ایجاد می‌کند. در این پنجره، admin می‌تواند سفارشات را مشاهده، اضافه، ویرایش، و حذف کند. برای این منظور، از یک JTable برای نمایش داده‌ها استفاده شده است. همچنین، از یک DefaultTableModel برای مدیریت داده‌ها، و از یک TableRowSorter برای مرتب‌سازی و جستجو در داده‌ها استفاده شده است. در متد سازنده، ابتدا آرایه‌هایی که شامل گزینه‌ها و قیمت‌های ناهار و شام هستند، ساخته می‌شوند. سپس، داده‌های موجود در فایل سفارشات خوانده می‌شوند و به جدول اضافه می‌شوند. در ادامه، پنلی برای جستجو، و سه دکمه برای اضافه کردن، ویرایش و حذف داده‌ها به پنجره اضافه می‌شوند. سپس، جدول، پنل جستجو، و دکمه‌ها به پنجره اضافه می‌شوند. در نهایت، تنظیمات جدول و پنجره انجام می‌شود و پنجره نمایش داده می‌شود. ````````````````````````````````````````````````````` This code defines an `OrdersManage` class that extends `JFrame` and is used to create a GUI application for managing food orders. Here's a breakdown of the code: - The `OrdersManage` constructor sets up the main components of the GUI. It sets the title of the application window and creates the table, table model, and row sorter for managing the orders. - The constructor reads the orders from a file and populates the table with the data. - It creates a search panel with a text field that allows users to filter the orders based on their input. - Buttons for adding, editing, and deleting orders are created and registered with action listeners to handle button click events. - The constructor also creates a menu bar with a "Refresh" menu item that allows users to refresh the orders. - The `saveToFile` method is used to save the orders to a file. - The `CreateDinnerArray` and `CreateLunchArray` methods are used to read the dinner and lunch options from files and populate the corresponding arrays. Please note that there are some dependencies in the code, such as `Classes.Pathes.FilesPath.icon`, `Classes.Theme. SoundEffect.errorSound`, `Frames.Order.UniversitySelfRestaurant.orderFilename`, `Frames.Order.UniversitySelfRestaurant. dinnerFilePath`, and `Frames.Order.UniversitySelfRestaurant.lunchFilePath`. You need to ensure that these dependencies are properly resolved and that the necessary files exist for the code to work correctly. */ public class OrdersManage extends JFrame { private JTable table; private DefaultTableModel tableModel; private List<String[]> data; private TableRowSorter<DefaultTableModel> sorter; private static String[] lunchOptions = new String[7]; private static int[] lunchPrices = new int[7]; private static String[] dinnerOptions = new String[7]; private static int[] dinnerPrices = new int[7]; public OrdersManage() throws IOException, UnsupportedAudioFileException, LineUnavailableException { super("سفارشات"); CreateDinnerArray(); CreateLunchArray(); data = new ArrayList<>(); try (BufferedReader br = new BufferedReader(new FileReader(new File(orderFilename)))) { String line; while ((line = br.readLine()) != null) { String[] parts = line.split(","); data.add(parts); } } catch (Exception e) { errorSound(); } tableModel = new DefaultTableModel(); tableModel.addColumn("شناسه"); tableModel.addColumn("تاریخ"); tableModel.addColumn("ناهار"); tableModel.addColumn("شام"); for (String[] row : data) { tableModel.addRow(row); } table = new JTable(tableModel); JPanel searchPanel = new JPanel(); JTextField searchField = new JTextField(20); searchField.addActionListener(e -> { String text = searchField.getText(); if (text.length() == 0) { sorter.setRowFilter(null); } else { sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text)); } }); searchPanel.add(searchField); JButton addButton = new JButton("اضافه کردن"); addButton.addActionListener(e -> { String id = JOptionPane.showInputDialog(this, "شناسه را وارد نمایید :"); if (id != null) { String date = JOptionPane.showInputDialog(this, "تاریخ را وارد نمایید : YYYY-MM-DD"); if (date != null) { String lunch = (String) JOptionPane.showInputDialog(this, "ناهار را انتخاب کنید :", "ناهار", JOptionPane.PLAIN_MESSAGE, null, lunchOptions, lunchOptions[0]); if (lunch != null){ String dinner = (String) JOptionPane.showInputDialog(this, "شام را انتخاب کنید :", "شام", JOptionPane.PLAIN_MESSAGE, null, dinnerOptions, dinnerOptions[0]); if (dinner != null) { String[] row = { id, date, lunch, dinner }; data.add(row); tableModel.addRow(row); try { saveToFile(); } catch (Exception ex) { } } } } } }); JButton editButton = new JButton("ویرایش "); editButton.addActionListener(e -> { int selectedRow = table.getSelectedRow(); if (selectedRow != -1) { String id = JOptionPane.showInputDialog(this, "شناسه را وارد نمایید :", table.getValueAt(selectedRow, 0)); if (id != null) { String date = JOptionPane.showInputDialog(this, "تاریخ را وارد نمایید : YYYY-MM-DD\n", table.getValueAt(selectedRow, 1)); if (date != null) { String lunch = (String) JOptionPane.showInputDialog(this, "ناهار جایگزین " + table.getValueAt(selectedRow, 2) + " را انتخاب کنید : ", "ناهار", JOptionPane.PLAIN_MESSAGE, null, lunchOptions, lunchOptions[0]); if (lunch != null) { String dinner = (String) JOptionPane.showInputDialog(this, "شام جایگزین " + table.getValueAt(selectedRow, 3) + " را انتخاب کنید : ", "شام", JOptionPane.PLAIN_MESSAGE, null, dinnerOptions, dinnerOptions[0]); if (dinner != null) { String[] row = { id, date, lunch, dinner }; data.set(selectedRow, row); tableModel.setValueAt(id, selectedRow, 0); tableModel.setValueAt(date, selectedRow, 1); tableModel.setValueAt(lunch, selectedRow, 2); tableModel.setValueAt(dinner, selectedRow, 3); try { saveToFile(); } catch (Exception ex) { } } } } } } else { JOptionPane.showMessageDialog(this, "لطفا یک فیلد را انتخاب نمایید."); } }); JButton deleteButton = new JButton("حذف"); deleteButton.addActionListener(e -> { int selectedRow = table.getSelectedRow(); if (selectedRow != -1) { data.remove(selectedRow); tableModel.removeRow(selectedRow); try { saveToFile(); } catch (Exception ex) { } } else { JOptionPane.showMessageDialog(this, "لطفا یک فیلد را انتخاب نمایید."); } }); JPanel buttonPanel = new JPanel(); buttonPanel.add(addButton); buttonPanel.add(editButton); buttonPanel.add(deleteButton); add(new JScrollPane(table)); add(searchPanel, "North"); add(buttonPanel, "South"); sorter = new TableRowSorter<>(tableModel); table.setRowSorter(sorter); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu menu = new JMenu("بیشتر"); menuBar.add(menu); JMenuItem refreshButton = new JMenuItem("تازه سازی"); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); try { new OrdersManage(); } catch (Exception ignored) { } } }); menu.add(refreshButton);
setIconImage(icon.getImage());
0
2023-11-03 08:35:22+00:00
16k
cyljx9999/talktime-Java
talktime-framework/talktime-service/src/main/java/com/qingmeng/service/impl/SysUserFriendServiceImpl.java
[ { "identifier": "FriendAdapt", "path": "talktime-framework/talktime-service/src/main/java/com/qingmeng/config/adapt/FriendAdapt.java", "snippet": "public class FriendAdapt {\n\n /**\n * 构建保存好友信息\n *\n * @param applyFriendDTO 申请好友 dto\n * @return {@link SysUserApply }\n * @author q...
import com.qingmeng.config.adapt.FriendAdapt; import com.qingmeng.config.adapt.UserSettingAdapt; import com.qingmeng.config.cache.UserCache; import com.qingmeng.config.cache.UserFriendSettingCache; import com.qingmeng.dao.SysUserFriendDao; import com.qingmeng.dao.SysUserFriendSettingDao; import com.qingmeng.dto.login.CheckFriendDTO; import com.qingmeng.dto.login.CheckFriendListDTO; import com.qingmeng.dto.user.UserFriendSettingDTO; import com.qingmeng.entity.SysUserApply; import com.qingmeng.entity.SysUserFriend; import com.qingmeng.entity.SysUserFriendSetting; import com.qingmeng.service.SysUserFriendService; import com.qingmeng.utils.AssertUtils; import com.qingmeng.utils.CommonUtils; import com.qingmeng.vo.user.CheckFriendVO; import com.qingmeng.vo.user.FriendTypeVO; import com.qingmeng.vo.user.UserFriendSettingVO; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; import java.util.stream.Collectors;
13,332
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserFriendServiceImpl implements SysUserFriendService { @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private UserFriendSettingCache userFriendSettingCache; @Resource private SysUserFriendDao sysUserFriendDao; @Resource private UserCache userCache; /** * 通过两个 ID 获取设置 * * @param userId 用户 ID * @param friendId 好友ID * @return {@link UserFriendSettingVO } * @author qingmeng * @createTime: 2023/11/29 14:41:32 */ @Override public UserFriendSettingVO getFriendSettingByBothId(Long userId, Long friendId) { String cacheKey = CommonUtils.getFriendSettingCacheKey(userId, friendId); SysUserFriendSetting friendSetting = checkLegal(cacheKey); return UserSettingAdapt.buildUserFriendSettingVO(friendSetting); } /** * 更改设置 * * @param userId 用户 ID * @param userFriendSettingDTO 用户好友设置 DTO * @author qingmeng * @createTime: 2023/11/29 15:15:19 */ @Override @Transactional(rollbackFor = Exception.class) public void alterFriendSetting(Long userId, UserFriendSettingDTO userFriendSettingDTO) { String cacheKey = CommonUtils.getFriendSettingCacheKey(userId, userFriendSettingDTO.getFriendId()); SysUserFriendSetting friendSetting = checkLegal(cacheKey); AssertUtils.equal(friendSetting.getUserId(),userId, "非法请求"); sysUserFriendSettingDao.alterSetting(userFriendSettingDTO); userFriendSettingCache.delete(cacheKey); userCache.evictFriendList(userId); } @Override @Transactional(rollbackFor = Exception.class) public void saveFriendRecord(SysUserApply sysUserApply) { SysUserFriend saveUserFriend = FriendAdapt.buildFriendRecord(sysUserApply); SysUserFriend saveUserFriendReverse = FriendAdapt.buildFriendRecordReverse(sysUserApply); sysUserFriendDao.saveOrUpdateByCustom(saveUserFriend); sysUserFriendDao.saveOrUpdateByCustom(saveUserFriendReverse); } /** * 通过两个ID获取好友 * * @param userId 用户 ID * @param targetId 目标 ID * @return {@link SysUserFriend } * @author qingmeng * @createTime: 2023/12/01 16:52:47 */ @Override public SysUserFriend getFriendByBothId(Long userId, Long targetId) { return sysUserFriendDao.getFriendByBothId(userId, targetId); } /** * 获取好友列表 * * @param userId 用户 ID * @return {@link List }<{@link FriendTypeVO }> * @author qingmeng * @createTime: 2023/12/03 10:43:34 */ @Override public List<FriendTypeVO> getFriendList(Long userId) { return userCache.getFriendList(userId); } /** * 检查是否为好友 * * @param userId 用户 ID * @param checkFriendDTO 检查好友 DTO * @return {@link CheckFriendVO } * @author qingmeng * @createTime: 2023/12/03 13:08:56 */ @Override public CheckFriendVO checkFriend(Long userId, CheckFriendDTO checkFriendDTO) { SysUserFriend sysUserFriend = sysUserFriendDao.getFriendById(userId); return FriendAdapt.buildCheckFriend(sysUserFriend, checkFriendDTO); } /** * 批量检查是否为好友 * * @param userId 用户 ID * @param checkFriendListDTO 检查好友 DTO * @return {@link List }<{@link CheckFriendVO }> * @author qingmeng * @createTime: 2023/12/03 12:49:25 */ @Override
package com.qingmeng.service.impl; /** * @author 清梦 * @version 1.0.0 * @Description * @createTime 2023年11月10日 11:19:00 */ @Service public class SysUserFriendServiceImpl implements SysUserFriendService { @Resource private SysUserFriendSettingDao sysUserFriendSettingDao; @Resource private UserFriendSettingCache userFriendSettingCache; @Resource private SysUserFriendDao sysUserFriendDao; @Resource private UserCache userCache; /** * 通过两个 ID 获取设置 * * @param userId 用户 ID * @param friendId 好友ID * @return {@link UserFriendSettingVO } * @author qingmeng * @createTime: 2023/11/29 14:41:32 */ @Override public UserFriendSettingVO getFriendSettingByBothId(Long userId, Long friendId) { String cacheKey = CommonUtils.getFriendSettingCacheKey(userId, friendId); SysUserFriendSetting friendSetting = checkLegal(cacheKey); return UserSettingAdapt.buildUserFriendSettingVO(friendSetting); } /** * 更改设置 * * @param userId 用户 ID * @param userFriendSettingDTO 用户好友设置 DTO * @author qingmeng * @createTime: 2023/11/29 15:15:19 */ @Override @Transactional(rollbackFor = Exception.class) public void alterFriendSetting(Long userId, UserFriendSettingDTO userFriendSettingDTO) { String cacheKey = CommonUtils.getFriendSettingCacheKey(userId, userFriendSettingDTO.getFriendId()); SysUserFriendSetting friendSetting = checkLegal(cacheKey); AssertUtils.equal(friendSetting.getUserId(),userId, "非法请求"); sysUserFriendSettingDao.alterSetting(userFriendSettingDTO); userFriendSettingCache.delete(cacheKey); userCache.evictFriendList(userId); } @Override @Transactional(rollbackFor = Exception.class) public void saveFriendRecord(SysUserApply sysUserApply) { SysUserFriend saveUserFriend = FriendAdapt.buildFriendRecord(sysUserApply); SysUserFriend saveUserFriendReverse = FriendAdapt.buildFriendRecordReverse(sysUserApply); sysUserFriendDao.saveOrUpdateByCustom(saveUserFriend); sysUserFriendDao.saveOrUpdateByCustom(saveUserFriendReverse); } /** * 通过两个ID获取好友 * * @param userId 用户 ID * @param targetId 目标 ID * @return {@link SysUserFriend } * @author qingmeng * @createTime: 2023/12/01 16:52:47 */ @Override public SysUserFriend getFriendByBothId(Long userId, Long targetId) { return sysUserFriendDao.getFriendByBothId(userId, targetId); } /** * 获取好友列表 * * @param userId 用户 ID * @return {@link List }<{@link FriendTypeVO }> * @author qingmeng * @createTime: 2023/12/03 10:43:34 */ @Override public List<FriendTypeVO> getFriendList(Long userId) { return userCache.getFriendList(userId); } /** * 检查是否为好友 * * @param userId 用户 ID * @param checkFriendDTO 检查好友 DTO * @return {@link CheckFriendVO } * @author qingmeng * @createTime: 2023/12/03 13:08:56 */ @Override public CheckFriendVO checkFriend(Long userId, CheckFriendDTO checkFriendDTO) { SysUserFriend sysUserFriend = sysUserFriendDao.getFriendById(userId); return FriendAdapt.buildCheckFriend(sysUserFriend, checkFriendDTO); } /** * 批量检查是否为好友 * * @param userId 用户 ID * @param checkFriendListDTO 检查好友 DTO * @return {@link List }<{@link CheckFriendVO }> * @author qingmeng * @createTime: 2023/12/03 12:49:25 */ @Override
public List<CheckFriendVO> checkFriendList(Long userId, CheckFriendListDTO checkFriendListDTO) {
7
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;
13,339
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; private IMU imu1; public DeviceController() { System.out.println("Measure constructor"); this.currentlyMeasuring = false; } public Boolean isCurrentlyMeasuring() { return this.currentlyMeasuring; } public void startMeasure() { this.saveInterval = Config.SAVE_INTERVAL.get(); this.tickTimeWarning = Config.TICK_TIME_WARNING.get(); this.tickTimeWarningTolerance = Config.TICK_TIME_WARNING_TOLERANCE.get(); this.lidarController = new LiDARController(new LiDAR[]{lidar1, lidar2, lidar3}); this.imuController = new IMUController(imu1); String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now()); this.savePath = "device_measurements/" + startTime; try { Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath)); } catch (Exception e) { System.out.println("Error creating directory: " + e.getMessage()); } if(Config.LIDAR1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar1.csv"); if(Config.LIDAR2_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar2.csv"); if(Config.LIDAR3_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar3.csv"); if(Config.IMU1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;accX;accY;accZ,gyroX;gyroY;gyroZ\n", this.savePath, "imu1.csv"); Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.start"), false); this.currentlyMeasuring = true; } public void stopMeasure() { // save remaining scans
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; private IMU imu1; public DeviceController() { System.out.println("Measure constructor"); this.currentlyMeasuring = false; } public Boolean isCurrentlyMeasuring() { return this.currentlyMeasuring; } public void startMeasure() { this.saveInterval = Config.SAVE_INTERVAL.get(); this.tickTimeWarning = Config.TICK_TIME_WARNING.get(); this.tickTimeWarningTolerance = Config.TICK_TIME_WARNING_TOLERANCE.get(); this.lidarController = new LiDARController(new LiDAR[]{lidar1, lidar2, lidar3}); this.imuController = new IMUController(imu1); String startTime = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm-ss").format(LocalDateTime.now()); this.savePath = "device_measurements/" + startTime; try { Files.createDirectories(Paths.get(MMM_ROOT_PATH + this.savePath)); } catch (Exception e) { System.out.println("Error creating directory: " + e.getMessage()); } if(Config.LIDAR1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar1.csv"); if(Config.LIDAR2_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar2.csv"); if(Config.LIDAR3_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;data\n", this.savePath, "lidar3.csv"); if(Config.IMU1_SWITCH.get()) saveStringToFile("timestamp;posX;posY;posZ;viewX;viewY;viewZ;accX;accY;accZ,gyroX;gyroY;gyroZ\n", this.savePath, "imu1.csv"); Minecraft.getInstance().player.displayClientMessage(Component.translatable("chat." + MMM.MODID + ".measure.start"), false); this.currentlyMeasuring = true; } public void stopMeasure() { // save remaining scans
ArrayList<LidarScan>[] scans = DEVICE_CONTROLLER.getLidarController().getScans();
6
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;
10,837
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) {
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);
10
2023-11-04 04:11:26+00:00
16k
conductor-oss/conductor
java-sdk/src/main/java/com/netflix/conductor/sdk/workflow/def/WorkflowBuilder.java
[ { "identifier": "WorkflowDef", "path": "common/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowDef.java", "snippet": "@ProtoMessage\n@TaskReferenceNameUniqueConstraint\npublic class WorkflowDef extends BaseDef {\n\n @ProtoEnum\n public enum TimeoutPolicy {\n TIME_OUT_WF...
import java.util.*; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.sdk.workflow.def.tasks.*; import com.netflix.conductor.sdk.workflow.executor.WorkflowExecutor; import com.netflix.conductor.sdk.workflow.utils.InputOutputGetter; import com.netflix.conductor.sdk.workflow.utils.MapBuilder; import com.netflix.conductor.sdk.workflow.utils.ObjectMapperProvider; import com.fasterxml.jackson.databind.ObjectMapper;
10,989
/* * Copyright 2022 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.sdk.workflow.def; /** * @param <T> Input type for the workflow */ public class WorkflowBuilder<T> { private String name; private String description; private int version; private String failureWorkflow; private String ownerEmail;
/* * Copyright 2022 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.sdk.workflow.def; /** * @param <T> Input type for the workflow */ public class WorkflowBuilder<T> { private String name; private String description; private int version; private String failureWorkflow; private String ownerEmail;
private WorkflowDef.TimeoutPolicy timeoutPolicy;
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,900
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()); if(decode == null || decode.length == 0){ return Result.error("签章制作失败",null); } byte[] entSealByte = entSealClipService.clip(decode, request.getColorRange()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("生成企业签章-参数生成") @RequestMapping(value = "/generate/seal",method = RequestMethod.POST) public Result<SealResponse> seal(@RequestBody GenerateSealRequest request){ if(request == null || request.getMiddleText() == null || request.getTopText() == null){ return Result.error("参数缺失",null) ; } byte[] entSealByte = entSealGenerateService.generateEntSeal(request.getTopText(), request.getMiddleText()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("签署") @RequestMapping(value = "/sign",method = RequestMethod.POST) public Result<SignResponse> sign(@RequestBody SignRequest request){ String fileName = "开源工具版说明.pdf" ; byte[] signFileBytes = null ; byte[] entSealBytes = null ; byte[] personalBytes = null ; CertificateProperty entCert = null ; CertificateProperty personalCert = 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()); if(decode == null || decode.length == 0){ return Result.error("签章制作失败",null); } byte[] entSealByte = entSealClipService.clip(decode, request.getColorRange()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("生成企业签章-参数生成") @RequestMapping(value = "/generate/seal",method = RequestMethod.POST) public Result<SealResponse> seal(@RequestBody GenerateSealRequest request){ if(request == null || request.getMiddleText() == null || request.getTopText() == null){ return Result.error("参数缺失",null) ; } byte[] entSealByte = entSealGenerateService.generateEntSeal(request.getTopText(), request.getMiddleText()); if(entSealByte == null){ return Result.error("签章制作失败",null); } String encode = Base64.encode(entSealByte); SealResponse response = new SealResponse(); response.setEntSeal(encode); return Result.OK(response) ; } @ApiOperation("签署") @RequestMapping(value = "/sign",method = RequestMethod.POST) public Result<SignResponse> sign(@RequestBody SignRequest request){ String fileName = "开源工具版说明.pdf" ; byte[] signFileBytes = null ; byte[] entSealBytes = null ; byte[] personalBytes = null ; CertificateProperty entCert = null ; CertificateProperty personalCert = null ;
List<RealPositionProperty> entPositionList = null;
3
2023-12-14 06:53:32+00:00
16k
Mahmud0808/ColorBlendr
app/src/main/java/com/drdisagree/colorblendr/utils/FragmentUtil.java
[ { "identifier": "AboutFragment", "path": "app/src/main/java/com/drdisagree/colorblendr/ui/fragments/AboutFragment.java", "snippet": "public class AboutFragment extends Fragment {\n\n private FragmentAboutBinding binding;\n\n @Override\n public View onCreateView(@NonNull LayoutInflater inflater,...
import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.drdisagree.colorblendr.R; import com.drdisagree.colorblendr.ui.fragments.AboutFragment; import com.drdisagree.colorblendr.ui.fragments.ColorsFragment; import com.drdisagree.colorblendr.ui.fragments.PerAppThemeFragment; import com.drdisagree.colorblendr.ui.fragments.SettingsFragment; import com.drdisagree.colorblendr.ui.fragments.StylesFragment; import com.drdisagree.colorblendr.ui.fragments.ThemeFragment;
12,497
package com.drdisagree.colorblendr.utils; public class FragmentUtil { public enum TAB_SELECTION { FROM_LEFT_TO_RIGHT, FROM_RIGHT_TO_LEFT, NONE } public static TAB_SELECTION getSlidingDirection(Fragment currentFragment, Fragment newFragment) { if (currentFragment == null) { return TAB_SELECTION.NONE; } TAB_SELECTION direction; if (isInGroup1(currentFragment) && !isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup4(currentFragment) && !isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup2(currentFragment)) { if (isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup3(newFragment) || isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else { return TAB_SELECTION.NONE; } } else if (isInGroup3(currentFragment)) { if (isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup1(newFragment) || isInGroup2(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else { return TAB_SELECTION.NONE; } } else { return TAB_SELECTION.NONE; } return direction; } public static void setCustomAnimations(TAB_SELECTION direction, FragmentTransaction fragmentTransaction) { switch (direction) { case FROM_LEFT_TO_RIGHT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right ); case FROM_RIGHT_TO_LEFT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left ); case NONE -> fragmentTransaction.setCustomAnimations( R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out ); } } private static boolean isInGroup1(Fragment fragment) { return fragment instanceof ColorsFragment || fragment instanceof PerAppThemeFragment; } private static boolean isInGroup2(Fragment fragment) { return fragment instanceof ThemeFragment; } private static boolean isInGroup3(Fragment fragment) { return fragment instanceof StylesFragment; } private static boolean isInGroup4(Fragment fragment) {
package com.drdisagree.colorblendr.utils; public class FragmentUtil { public enum TAB_SELECTION { FROM_LEFT_TO_RIGHT, FROM_RIGHT_TO_LEFT, NONE } public static TAB_SELECTION getSlidingDirection(Fragment currentFragment, Fragment newFragment) { if (currentFragment == null) { return TAB_SELECTION.NONE; } TAB_SELECTION direction; if (isInGroup1(currentFragment) && !isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup4(currentFragment) && !isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup2(currentFragment)) { if (isInGroup1(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else if (isInGroup3(newFragment) || isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else { return TAB_SELECTION.NONE; } } else if (isInGroup3(currentFragment)) { if (isInGroup4(newFragment)) { direction = TAB_SELECTION.FROM_LEFT_TO_RIGHT; } else if (isInGroup1(newFragment) || isInGroup2(newFragment)) { direction = TAB_SELECTION.FROM_RIGHT_TO_LEFT; } else { return TAB_SELECTION.NONE; } } else { return TAB_SELECTION.NONE; } return direction; } public static void setCustomAnimations(TAB_SELECTION direction, FragmentTransaction fragmentTransaction) { switch (direction) { case FROM_LEFT_TO_RIGHT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right ); case FROM_RIGHT_TO_LEFT -> fragmentTransaction.setCustomAnimations( R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left ); case NONE -> fragmentTransaction.setCustomAnimations( R.anim.fade_in, R.anim.fade_out, R.anim.fade_in, R.anim.fade_out ); } } private static boolean isInGroup1(Fragment fragment) { return fragment instanceof ColorsFragment || fragment instanceof PerAppThemeFragment; } private static boolean isInGroup2(Fragment fragment) { return fragment instanceof ThemeFragment; } private static boolean isInGroup3(Fragment fragment) { return fragment instanceof StylesFragment; } private static boolean isInGroup4(Fragment fragment) {
return fragment instanceof SettingsFragment || fragment instanceof AboutFragment;
0
2023-12-06 13:20:16+00:00
16k
HelpChat/DeluxeMenus
src/main/java/com/extendedclip/deluxemenus/listener/PlayerListener.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.action.ClickHandler; import com.extendedclip.deluxemenus.menu.Menu; import com.extendedclip.deluxemenus.menu.MenuHolder; import com.extendedclip.deluxemenus.menu.MenuItem; import com.extendedclip.deluxemenus.requirement.RequirementList; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.util.Optional; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.jetbrains.annotations.NotNull;
12,112
package com.extendedclip.deluxemenus.listener; public class PlayerListener implements Listener { private final DeluxeMenus plugin; private final Cache<UUID, Long> cache = CacheBuilder.newBuilder() .expireAfterWrite(75, TimeUnit.MILLISECONDS).build(); // This is so dumb. Mojang fix your shit. private final Cache<UUID, Long> shiftCache = CacheBuilder.newBuilder() .expireAfterWrite(200, TimeUnit.MILLISECONDS).build(); public PlayerListener(DeluxeMenus plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, this.plugin); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onCommandExecute(PlayerCommandPreprocessEvent event) { String cmd = event.getMessage().substring(1);
package com.extendedclip.deluxemenus.listener; public class PlayerListener implements Listener { private final DeluxeMenus plugin; private final Cache<UUID, Long> cache = CacheBuilder.newBuilder() .expireAfterWrite(75, TimeUnit.MILLISECONDS).build(); // This is so dumb. Mojang fix your shit. private final Cache<UUID, Long> shiftCache = CacheBuilder.newBuilder() .expireAfterWrite(200, TimeUnit.MILLISECONDS).build(); public PlayerListener(DeluxeMenus plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, this.plugin); } @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onCommandExecute(PlayerCommandPreprocessEvent event) { String cmd = event.getMessage().substring(1);
Menu menu = Menu.getMenuByCommand(cmd.toLowerCase());
2
2023-12-14 23:41:07+00:00
16k
lxs2601055687/contextAdminRuoYi
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/SysDeptServiceImpl.java
[ { "identifier": "CacheNames", "path": "ruoyi-common/src/main/java/com/ruoyi/common/constant/CacheNames.java", "snippet": "public interface CacheNames {\n\n /**\n * 演示案例\n */\n String DEMO_CACHE = \"demo:cache#60s#10m#20\";\n\n /**\n * 系统配置\n */\n String SYS_CONFIG = \"sys_con...
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.ruoyi.common.constant.CacheNames; import com.ruoyi.common.constant.UserConstants; import com.ruoyi.common.core.domain.entity.SysDept; import com.ruoyi.common.core.domain.entity.SysRole; import com.ruoyi.common.core.domain.entity.SysUser; import com.ruoyi.common.core.service.DeptService; import com.ruoyi.common.exception.ServiceException; import com.ruoyi.common.helper.DataBaseHelper; import com.ruoyi.common.helper.LoginHelper; import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.TreeBuildUtils; import com.ruoyi.common.utils.redis.CacheUtils; import com.ruoyi.common.utils.spring.SpringUtils; import com.ruoyi.system.mapper.SysDeptMapper; import com.ruoyi.system.mapper.SysRoleMapper; import com.ruoyi.system.mapper.SysUserMapper; import com.ruoyi.system.service.ISysDeptService; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
11,831
package com.ruoyi.system.service.impl; /** * 部门管理 服务实现 * * @author Lion Li */ @RequiredArgsConstructor @Service public class SysDeptServiceImpl implements ISysDeptService, DeptService { private final SysDeptMapper baseMapper; private final SysRoleMapper roleMapper; private final SysUserMapper userMapper; /** * 查询部门管理数据 * * @param dept 部门信息 * @return 部门信息集合 */ @Override public List<SysDept> selectDeptList(SysDept dept) { LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>(); lqw.eq(SysDept::getDelFlag, "0") .eq(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId()) .eq(ObjectUtil.isNotNull(dept.getParentId()), SysDept::getParentId, dept.getParentId()) .like(StringUtils.isNotBlank(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName()) .eq(StringUtils.isNotBlank(dept.getStatus()), SysDept::getStatus, dept.getStatus()) .orderByAsc(SysDept::getParentId) .orderByAsc(SysDept::getOrderNum); return baseMapper.selectDeptList(lqw); } /** * 查询部门树结构信息 * * @param dept 部门信息 * @return 部门树信息集合 */ @Override public List<Tree<Long>> selectDeptTreeList(SysDept dept) { List<SysDept> depts = this.selectDeptList(dept); return buildDeptTreeSelect(depts); } /** * 构建前端所需要下拉树结构 * * @param depts 部门列表 * @return 下拉树结构列表 */ @Override public List<Tree<Long>> buildDeptTreeSelect(List<SysDept> depts) { if (CollUtil.isEmpty(depts)) { return CollUtil.newArrayList(); } return TreeBuildUtils.build(depts, (dept, tree) -> tree.setId(dept.getDeptId()) .setParentId(dept.getParentId()) .setName(dept.getDeptName()) .setWeight(dept.getOrderNum())); } /** * 根据角色ID查询部门树信息 * * @param roleId 角色ID * @return 选中部门列表 */ @Override public List<Long> selectDeptListByRoleId(Long roleId) {
package com.ruoyi.system.service.impl; /** * 部门管理 服务实现 * * @author Lion Li */ @RequiredArgsConstructor @Service public class SysDeptServiceImpl implements ISysDeptService, DeptService { private final SysDeptMapper baseMapper; private final SysRoleMapper roleMapper; private final SysUserMapper userMapper; /** * 查询部门管理数据 * * @param dept 部门信息 * @return 部门信息集合 */ @Override public List<SysDept> selectDeptList(SysDept dept) { LambdaQueryWrapper<SysDept> lqw = new LambdaQueryWrapper<>(); lqw.eq(SysDept::getDelFlag, "0") .eq(ObjectUtil.isNotNull(dept.getDeptId()), SysDept::getDeptId, dept.getDeptId()) .eq(ObjectUtil.isNotNull(dept.getParentId()), SysDept::getParentId, dept.getParentId()) .like(StringUtils.isNotBlank(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName()) .eq(StringUtils.isNotBlank(dept.getStatus()), SysDept::getStatus, dept.getStatus()) .orderByAsc(SysDept::getParentId) .orderByAsc(SysDept::getOrderNum); return baseMapper.selectDeptList(lqw); } /** * 查询部门树结构信息 * * @param dept 部门信息 * @return 部门树信息集合 */ @Override public List<Tree<Long>> selectDeptTreeList(SysDept dept) { List<SysDept> depts = this.selectDeptList(dept); return buildDeptTreeSelect(depts); } /** * 构建前端所需要下拉树结构 * * @param depts 部门列表 * @return 下拉树结构列表 */ @Override public List<Tree<Long>> buildDeptTreeSelect(List<SysDept> depts) { if (CollUtil.isEmpty(depts)) { return CollUtil.newArrayList(); } return TreeBuildUtils.build(depts, (dept, tree) -> tree.setId(dept.getDeptId()) .setParentId(dept.getParentId()) .setName(dept.getDeptName()) .setWeight(dept.getOrderNum())); } /** * 根据角色ID查询部门树信息 * * @param roleId 角色ID * @return 选中部门列表 */ @Override public List<Long> selectDeptListByRoleId(Long roleId) {
SysRole role = roleMapper.selectById(roleId);
3
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,674
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)); } }
/* * 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) {
13
2023-12-14 15:08:35+00:00
16k
Patbox/PolyDecorations
src/main/java/eu/pb4/polydecorations/ModInit.java
[ { "identifier": "BrazierBlock", "path": "src/main/java/eu/pb4/polydecorations/block/furniture/BrazierBlock.java", "snippet": "public class BrazierBlock extends Block implements FactoryBlock, BarrierBasedWaterloggable {\n public static final BooleanProperty LIT = Properties.LIT;\n\n public BrazierB...
import eu.pb4.factorytools.impl.DebugData; import eu.pb4.polydecorations.block.furniture.BrazierBlock; import eu.pb4.polydecorations.block.item.GlobeBlock; import eu.pb4.polydecorations.block.extension.WallAttachedLanternBlock; import eu.pb4.polydecorations.entity.DecorationsEntities; import eu.pb4.polydecorations.polydex.PolydexCompat; import eu.pb4.polydecorations.recipe.DecorationsRecipeSerializers; import eu.pb4.polydecorations.recipe.DecorationsRecipeTypes; import eu.pb4.polydecorations.ui.GuiTextures; import eu.pb4.polydecorations.ui.UiResourceCreator; import eu.pb4.polydecorations.util.*; import eu.pb4.polymer.resourcepack.api.PolymerResourcePackUtils; import eu.pb4.polydecorations.block.DecorationsBlockEntities; import eu.pb4.polydecorations.block.DecorationsBlocks; import eu.pb4.polydecorations.item.DecorationsItems; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.util.Identifier; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
11,798
package eu.pb4.polydecorations; public class ModInit implements ModInitializer { public static final String ID = "polydecorations"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("PolyDecorations"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of PolyDecorations!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); } DecorationsBlocks.register(); DecorationsBlockEntities.register(); DecorationsItems.register(); DecorationsEntities.register(); DecorationsRecipeTypes.register(); DecorationsRecipeSerializers.register(); DecorationsUtil.register(); DebugData.register(); initModels();
package eu.pb4.polydecorations; public class ModInit implements ModInitializer { public static final String ID = "polydecorations"; public static final String VERSION = FabricLoader.getInstance().getModContainer(ID).get().getMetadata().getVersion().getFriendlyString(); public static final Logger LOGGER = LoggerFactory.getLogger("PolyDecorations"); public static final boolean DEV_ENV = FabricLoader.getInstance().isDevelopmentEnvironment(); public static final boolean DEV_MODE = VERSION.contains("-dev.") || DEV_ENV; @SuppressWarnings("PointlessBooleanExpression") public static final boolean DYNAMIC_ASSETS = true && DEV_ENV; public static Identifier id(String path) { return new Identifier(ID, path); } @Override public void onInitialize() { if (VERSION.contains("-dev.")) { LOGGER.warn("====================================================="); LOGGER.warn("You are using development version of PolyDecorations!"); LOGGER.warn("Support is limited, as features might be unfinished!"); LOGGER.warn("You are on your own!"); LOGGER.warn("====================================================="); } DecorationsBlocks.register(); DecorationsBlockEntities.register(); DecorationsItems.register(); DecorationsEntities.register(); DecorationsRecipeTypes.register(); DecorationsRecipeSerializers.register(); DecorationsUtil.register(); DebugData.register(); initModels();
UiResourceCreator.setup();
8
2023-12-10 16:20:36+00:00
16k
i-moonlight/Suricate
src/main/java/com/michelin/suricate/services/js/services/DashboardScheduleService.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 java.util.Date; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.michelin.suricate.model.dto.js.JsExecutionDto; import com.michelin.suricate.model.dto.js.JsResultDto; import com.michelin.suricate.model.dto.websocket.UpdateEvent; import com.michelin.suricate.model.entities.ProjectWidget; import com.michelin.suricate.model.enums.JsExecutionErrorTypeEnum; import com.michelin.suricate.model.enums.UpdateType; import com.michelin.suricate.model.enums.WidgetStateEnum; import com.michelin.suricate.services.api.ProjectService; import com.michelin.suricate.services.api.ProjectWidgetService; import com.michelin.suricate.services.js.scheduler.JsExecutionScheduler; import com.michelin.suricate.services.mapper.ProjectWidgetMapper; import com.michelin.suricate.services.websocket.DashboardWebSocketService;
11,861
/* * * * 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.services; /** * Dashboard schedule service. */ @Slf4j @Service public class DashboardScheduleService { @Autowired private ApplicationContext applicationContext; @Autowired private DashboardWebSocketService dashboardWebSocketService; @Autowired private ProjectWidgetService projectWidgetService; @Autowired
/* * * * 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.services; /** * Dashboard schedule service. */ @Slf4j @Service public class DashboardScheduleService { @Autowired private ApplicationContext applicationContext; @Autowired private DashboardWebSocketService dashboardWebSocketService; @Autowired private ProjectWidgetService projectWidgetService; @Autowired
private ProjectWidgetMapper projectWidgetMapper;
10
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;
11,116
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class AircraftService { @Autowired private RegcodeDataService regcodeDataService; @Autowired private OperatorDataService operatorDataService; @Autowired private FlightrouteDataService flightrouteDataService; @Autowired private AircraftTrailService aircraftTrailService; @Autowired private Configuration configuration; // Networkhandler private static final NetworkHandlerService networkHandler = new NetworkHandlerService(); // Record mit Informationen von der Planespotters.net API record PlanespottersResponse(String thumbnailLargeUrl, String linkToWebsiteUrl, String photographer) { } /** * Erstellt ein neues Flugzeug (Aircraft) * * @param element JSONObject * @param feeder Feeder * @return Aircraft */ public Aircraft createNewAircraft(JSONObject element, Feeder feeder) { // Erstelle Flugzeug Aircraft aircraftNew = new Aircraft(element.getString("hex").toLowerCase().trim(), element.getDouble("lat"), element.getDouble("lon")); // Setze spezifische Werte der Feeder setValuesToAircraft(feeder, element, aircraftNew); return aircraftNew; } /** * Erstellt ein neues Flugzeug (OpenskyAircraft) * * @param element JSONObject * @param feeder Feeder * @return OpenskyAircraft */
package com.amnesica.belugaproject.services.aircraft; @Slf4j @Service public class AircraftService { @Autowired private RegcodeDataService regcodeDataService; @Autowired private OperatorDataService operatorDataService; @Autowired private FlightrouteDataService flightrouteDataService; @Autowired private AircraftTrailService aircraftTrailService; @Autowired private Configuration configuration; // Networkhandler private static final NetworkHandlerService networkHandler = new NetworkHandlerService(); // Record mit Informationen von der Planespotters.net API record PlanespottersResponse(String thumbnailLargeUrl, String linkToWebsiteUrl, String photographer) { } /** * Erstellt ein neues Flugzeug (Aircraft) * * @param element JSONObject * @param feeder Feeder * @return Aircraft */ public Aircraft createNewAircraft(JSONObject element, Feeder feeder) { // Erstelle Flugzeug Aircraft aircraftNew = new Aircraft(element.getString("hex").toLowerCase().trim(), element.getDouble("lat"), element.getDouble("lon")); // Setze spezifische Werte der Feeder setValuesToAircraft(feeder, element, aircraftNew); return aircraftNew; } /** * Erstellt ein neues Flugzeug (OpenskyAircraft) * * @param element JSONObject * @param feeder Feeder * @return OpenskyAircraft */
public OpenskyAircraft createNewOpenskyAircraft(JSONObject element, Feeder feeder) {
4
2023-12-11 11:37:46+00:00
16k
fiber-net-gateway/fiber-net-gateway
fiber-gateway-proxy/src/main/java/io/fiber/net/proxy/lib/ReqFunc.java
[ { "identifier": "HttpExchange", "path": "fiber-gateway-common/src/main/java/io/fiber/net/common/HttpExchange.java", "snippet": "public abstract class HttpExchange {\n /**\n * 尽量把 HttpExchange 这个类的性能优化得非常好\n *\n * @param <T>\n */\n public static final class Attr<T> {\n privat...
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.BinaryNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; import io.fiber.net.common.HttpExchange; import io.fiber.net.common.utils.ArrayUtils; import io.fiber.net.common.utils.Constant; import io.fiber.net.common.utils.JsonUtil; import io.fiber.net.common.utils.StringUtils; import io.fiber.net.http.util.MultiMap; import io.fiber.net.http.util.UrlEncoded; import io.fiber.net.script.ExecutionContext; import io.fiber.net.script.Library; import io.fiber.net.script.ScriptExecException; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufUtil; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map;
12,020
package io.fiber.net.proxy.lib; public class ReqFunc { private static final ObjectNode EMPTY = JsonUtil.createObjectNode(); private static class Ctx { private final HttpExchange exchange; private ObjectNode query; private ObjectNode headers; private Ctx(HttpExchange exchange) { this.exchange = exchange; } public ObjectNode getQuery() { if (query == null) { String queryText = exchange.getQuery();
package io.fiber.net.proxy.lib; public class ReqFunc { private static final ObjectNode EMPTY = JsonUtil.createObjectNode(); private static class Ctx { private final HttpExchange exchange; private ObjectNode query; private ObjectNode headers; private Ctx(HttpExchange exchange) { this.exchange = exchange; } public ObjectNode getQuery() { if (query == null) { String queryText = exchange.getQuery();
if (StringUtils.isNotEmpty(queryText)) {
4
2023-12-08 15:18:05+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;
13,541
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,
/* * 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(
3
2023-12-06 09:14:09+00:00
16k
lyswhut/react-native-local-media-metadata
android/src/main/java/org/jaudiotagger/audio/aiff/AiffInfoReader.java
[ { "identifier": "AudioFileIO", "path": "android/src/main/java/org/jaudiotagger/audio/AudioFileIO.java", "snippet": "public class AudioFileIO\n{\n\n //Logger\n public static Logger logger = Logger.getLogger(\"org.jaudiotagger.audio\");\n\n // !! Do not forget to also add new supported extensions...
import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.aiff.chunk.*; import org.jaudiotagger.audio.exceptions.CannotReadException; import org.jaudiotagger.audio.generic.GenericAudioHeader; import org.jaudiotagger.audio.generic.Utils; import org.jaudiotagger.audio.iff.Chunk; import org.jaudiotagger.audio.iff.ChunkHeader; import org.jaudiotagger.audio.iff.IffHeaderChunk; import org.jaudiotagger.logging.Hex; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.util.logging.Logger;
12,968
package org.jaudiotagger.audio.aiff; /** * Read Aiff chunks, except the ID3 chunk. */ public class AiffInfoReader extends AiffChunkReader { public static Logger logger = Logger.getLogger("org.jaudiotagger.audio.aiff"); protected GenericAudioHeader read(File file) throws CannotReadException, IOException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); FileChannel fc = raf.getChannel(); logger.config(file + " Reading AIFF file size:" + Hex.asDecAndHex(fc.size())); AiffAudioHeader aiffAudioHeader = new AiffAudioHeader(); final AiffFileHeader fileHeader = new AiffFileHeader(); long noOfBytes = fileHeader.readHeader(fc, aiffAudioHeader, file.toString()); while (fc.position() < fc.size()) { if (!readChunk(fc, aiffAudioHeader, file.toString())) { logger.severe(file + " UnableToReadProcessChunk"); break; } } calculateBitRate(aiffAudioHeader); return aiffAudioHeader; } finally { AudioFileIO.closeQuietly(raf); } } /** * Calculate bitrate, done it here because requires data from multiple chunks * * @param info * @throws CannotReadException */ private void calculateBitRate(GenericAudioHeader info) throws CannotReadException { if (info.getAudioDataLength() != null) { info.setBitRate((int) (Math.round(info.getAudioDataLength() * Utils.BITS_IN_BYTE_MULTIPLIER / (info.getPreciseTrackLength() * Utils.KILOBYTE_MULTIPLIER)))); } } /** * Reads an AIFF Chunk. * * @return {@code false}, if we were not able to read a valid chunk id */ private boolean readChunk(FileChannel fc, AiffAudioHeader aiffAudioHeader, String fileName) throws IOException, CannotReadException { logger.config(fileName + " Reading Info Chunk"); final Chunk chunk;
package org.jaudiotagger.audio.aiff; /** * Read Aiff chunks, except the ID3 chunk. */ public class AiffInfoReader extends AiffChunkReader { public static Logger logger = Logger.getLogger("org.jaudiotagger.audio.aiff"); protected GenericAudioHeader read(File file) throws CannotReadException, IOException { RandomAccessFile raf = null; try { raf = new RandomAccessFile(file, "r"); FileChannel fc = raf.getChannel(); logger.config(file + " Reading AIFF file size:" + Hex.asDecAndHex(fc.size())); AiffAudioHeader aiffAudioHeader = new AiffAudioHeader(); final AiffFileHeader fileHeader = new AiffFileHeader(); long noOfBytes = fileHeader.readHeader(fc, aiffAudioHeader, file.toString()); while (fc.position() < fc.size()) { if (!readChunk(fc, aiffAudioHeader, file.toString())) { logger.severe(file + " UnableToReadProcessChunk"); break; } } calculateBitRate(aiffAudioHeader); return aiffAudioHeader; } finally { AudioFileIO.closeQuietly(raf); } } /** * Calculate bitrate, done it here because requires data from multiple chunks * * @param info * @throws CannotReadException */ private void calculateBitRate(GenericAudioHeader info) throws CannotReadException { if (info.getAudioDataLength() != null) { info.setBitRate((int) (Math.round(info.getAudioDataLength() * Utils.BITS_IN_BYTE_MULTIPLIER / (info.getPreciseTrackLength() * Utils.KILOBYTE_MULTIPLIER)))); } } /** * Reads an AIFF Chunk. * * @return {@code false}, if we were not able to read a valid chunk id */ private boolean readChunk(FileChannel fc, AiffAudioHeader aiffAudioHeader, String fileName) throws IOException, CannotReadException { logger.config(fileName + " Reading Info Chunk"); final Chunk chunk;
final ChunkHeader chunkHeader = new ChunkHeader(ByteOrder.BIG_ENDIAN);
5
2023-12-11 05:58:19+00:00
16k
xhtcode/xht-cloud-parent
xht-cloud-generate-service/src/main/java/com/xht/cloud/generate/core/service/impl/GenerateCoreServiceImpl.java
[ { "identifier": "StringUtils", "path": "xht-cloud-framework/xht-cloud-framework-core/src/main/java/com/xht/cloud/framework/core/support/StringUtils.java", "snippet": "public final class StringUtils extends org.springframework.util.StringUtils {\n\n /**\n * 当字符串空的时候,返回默认值,不为空返回当前值\n */\n pu...
import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.StrUtil; import com.xht.cloud.framework.core.support.StringUtils; import com.xht.cloud.framework.core.treenode.INode; import com.xht.cloud.framework.core.treenode.TreeNode; import com.xht.cloud.framework.core.treenode.TreeUtils; import com.xht.cloud.generate.constant.dto.ConfigTreeDTO; import com.xht.cloud.generate.core.controller.request.GenCodeRequest; import com.xht.cloud.generate.core.service.IGenerateCoreService; import com.xht.cloud.generate.module.column.dao.dataobject.GenTableColumnDO; import com.xht.cloud.generate.module.column.dao.mapper.GenTableColumnMapper; import com.xht.cloud.generate.module.config.dao.dataobject.GenCodeConfigDO; import com.xht.cloud.generate.module.config.dao.mapper.GenCodeConfigMapper; import com.xht.cloud.generate.module.database.dao.dataobject.GenDatabaseDO; import com.xht.cloud.generate.module.database.dao.mapper.GenDatabaseMapper; import com.xht.cloud.generate.module.table.dao.dataobject.GenTableDO; import com.xht.cloud.generate.module.table.dao.mapper.GenTableMapper; import com.xht.cloud.generate.module.template.dao.dataobject.GenCodeTemplateDO; import com.xht.cloud.generate.module.template.dao.mapper.GenCodeTemplateMapper; import com.xht.cloud.generate.utils.GenerateTool; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.velocity.VelocityContext; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
11,590
package com.xht.cloud.generate.core.service.impl; /** * 描述 :代码生成器核心任务 * * @author : 小糊涂 **/ @Slf4j @Service @RequiredArgsConstructor public class GenerateCoreServiceImpl implements IGenerateCoreService { private final GenTableMapper genTableMapper; private final GenCodeConfigMapper genCodeConfigMapper; private final GenDatabaseMapper genDatabaseMapper; private final GenTableColumnMapper genTableColumnMapper; private final GenCodeTemplateMapper genCodeTemplateMapper; /** * 查看代码 * * @param genCodeRequest {@link GenCodeRequest} * @param tableId 表id * @return 代码文件树的格式 */ @Override public List<INode<String>> viewCode(GenCodeRequest genCodeRequest, String tableId) { GenTableDO genTableDO = genTableMapper.findById(tableId).orElse(null); List<Map<String, String>> codeMaps = generateCode(genCodeRequest, genTableDO); if (CollectionUtils.isEmpty(codeMaps)) { return Collections.emptyList(); } List<INode<String>> result = new ArrayList<>(); for (Map<String, String> codeMap : codeMaps) { codeMap.forEach((k, v) -> { createTreeNode(result, k, v); }); } return TreeUtils.buildList(result); } private void createTreeNode(List<INode<String>> result, String path, String code) { if (!StringUtils.hasText(path)) return; List<String> split = StrUtil.split(path, File.separator); for (int i = 0; i < split.size(); i++) { String id = StringUtils.collectionToDelimitedString(split.subList(0, i + 1), File.separator); String parentId = StringUtils.collectionToDelimitedString(split.subList(0, i), File.separator); String label = split.get(i); TreeNode<String> treeNode = new TreeNode<>(id, parentId, label.length()); treeNode.put("label", label); treeNode.put("fileType", "0"); if (StringUtils.hasText(code)) { treeNode.put("fileType", "1"); treeNode.put("code", code); } result.add(treeNode); } } /** * 代码下载 * * @param genCodeRequest {@link GenCodeRequest} * @return byte[] 数据 * @throws Exception Exception */ @Override public byte[] downloadCode(GenCodeRequest genCodeRequest) throws Exception { List<String> tableIds = genCodeRequest.getTableIds(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(outputStream, StandardCharsets.UTF_8); zip.setComment("小糊涂代码生成器"); // 添加到zip zip.putNextEntry(new ZipEntry("使用说明(不能完全依赖生成的代码!).txt")); IoUtil.write(zip, StandardCharsets.UTF_8, false, ""); zip.flush(); zip.closeEntry(); for (String tableId : tableIds) { GenTableDO genTableDO = genTableMapper.findById(tableId).orElse(null); List<Map<String, String>> codeMaps = generateCode(genCodeRequest, genTableDO); for (Map<String, String> codeMap : codeMaps) { codeMap.forEach((k, v) -> { try { //这里要对空白文件夹作处理 zip.putNextEntry(new ZipEntry(k + (StringUtils.hasText(v) ? "" : "/"))); IoUtil.write(zip, StandardCharsets.UTF_8, false, v); zip.flush(); zip.closeEntry(); } catch (Exception e) { log.error("下载错误 {}", e.getMessage()); } }); } } IoUtil.close(zip); return outputStream.toByteArray(); } public List<Map<String, String>> generateCode(GenCodeRequest genCodeRequest, GenTableDO genTableDO) { List<Map<String, String>> result = new ArrayList<>(); if (Objects.isNull(genTableDO)) return result; String configId = genTableDO.getConfigId(); String id = genTableDO.getId(); String genDbId = genTableDO.getGenDbId(); GenDatabaseDO genDatabaseDO = genDatabaseMapper.findById(genDbId).orElse(null); VelocityContext velocityContext = GenerateTool.initVelocityContext(genCodeRequest, genDatabaseDO, genTableDO); List<GenTableColumnDO> tableColumnDOS = genTableColumnMapper.selectList(GenTableColumnDO::getTableId, id); GenCodeConfigDO genCodeConfigDO = genCodeConfigMapper.selectById(configId);
package com.xht.cloud.generate.core.service.impl; /** * 描述 :代码生成器核心任务 * * @author : 小糊涂 **/ @Slf4j @Service @RequiredArgsConstructor public class GenerateCoreServiceImpl implements IGenerateCoreService { private final GenTableMapper genTableMapper; private final GenCodeConfigMapper genCodeConfigMapper; private final GenDatabaseMapper genDatabaseMapper; private final GenTableColumnMapper genTableColumnMapper; private final GenCodeTemplateMapper genCodeTemplateMapper; /** * 查看代码 * * @param genCodeRequest {@link GenCodeRequest} * @param tableId 表id * @return 代码文件树的格式 */ @Override public List<INode<String>> viewCode(GenCodeRequest genCodeRequest, String tableId) { GenTableDO genTableDO = genTableMapper.findById(tableId).orElse(null); List<Map<String, String>> codeMaps = generateCode(genCodeRequest, genTableDO); if (CollectionUtils.isEmpty(codeMaps)) { return Collections.emptyList(); } List<INode<String>> result = new ArrayList<>(); for (Map<String, String> codeMap : codeMaps) { codeMap.forEach((k, v) -> { createTreeNode(result, k, v); }); } return TreeUtils.buildList(result); } private void createTreeNode(List<INode<String>> result, String path, String code) { if (!StringUtils.hasText(path)) return; List<String> split = StrUtil.split(path, File.separator); for (int i = 0; i < split.size(); i++) { String id = StringUtils.collectionToDelimitedString(split.subList(0, i + 1), File.separator); String parentId = StringUtils.collectionToDelimitedString(split.subList(0, i), File.separator); String label = split.get(i); TreeNode<String> treeNode = new TreeNode<>(id, parentId, label.length()); treeNode.put("label", label); treeNode.put("fileType", "0"); if (StringUtils.hasText(code)) { treeNode.put("fileType", "1"); treeNode.put("code", code); } result.add(treeNode); } } /** * 代码下载 * * @param genCodeRequest {@link GenCodeRequest} * @return byte[] 数据 * @throws Exception Exception */ @Override public byte[] downloadCode(GenCodeRequest genCodeRequest) throws Exception { List<String> tableIds = genCodeRequest.getTableIds(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(outputStream, StandardCharsets.UTF_8); zip.setComment("小糊涂代码生成器"); // 添加到zip zip.putNextEntry(new ZipEntry("使用说明(不能完全依赖生成的代码!).txt")); IoUtil.write(zip, StandardCharsets.UTF_8, false, ""); zip.flush(); zip.closeEntry(); for (String tableId : tableIds) { GenTableDO genTableDO = genTableMapper.findById(tableId).orElse(null); List<Map<String, String>> codeMaps = generateCode(genCodeRequest, genTableDO); for (Map<String, String> codeMap : codeMaps) { codeMap.forEach((k, v) -> { try { //这里要对空白文件夹作处理 zip.putNextEntry(new ZipEntry(k + (StringUtils.hasText(v) ? "" : "/"))); IoUtil.write(zip, StandardCharsets.UTF_8, false, v); zip.flush(); zip.closeEntry(); } catch (Exception e) { log.error("下载错误 {}", e.getMessage()); } }); } } IoUtil.close(zip); return outputStream.toByteArray(); } public List<Map<String, String>> generateCode(GenCodeRequest genCodeRequest, GenTableDO genTableDO) { List<Map<String, String>> result = new ArrayList<>(); if (Objects.isNull(genTableDO)) return result; String configId = genTableDO.getConfigId(); String id = genTableDO.getId(); String genDbId = genTableDO.getGenDbId(); GenDatabaseDO genDatabaseDO = genDatabaseMapper.findById(genDbId).orElse(null); VelocityContext velocityContext = GenerateTool.initVelocityContext(genCodeRequest, genDatabaseDO, genTableDO); List<GenTableColumnDO> tableColumnDOS = genTableColumnMapper.selectList(GenTableColumnDO::getTableId, id); GenCodeConfigDO genCodeConfigDO = genCodeConfigMapper.selectById(configId);
List<ConfigTreeDTO> configTreeDTOS = GenerateTool.convertToConfigTreeDTO(genCodeConfigDO.getConfigInfo());
4
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,293
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
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) {
0
2023-12-08 14:13:04+00:00
16k
quentin452/Garden-Stuff-Continuation
src/main/resources/com/jaquadro/minecraft/gardencore/integration/PlantMegaPackIntegration.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.PlantRegistry; import com.jaquadro.minecraft.gardencore.api.plant.IPlantInfo; import com.jaquadro.minecraft.gardencore.api.plant.PlantItem; import com.jaquadro.minecraft.gardencore.api.plant.PlantSize; import com.jaquadro.minecraft.gardencore.api.plant.PlantType; import com.jaquadro.minecraft.gardencore.block.BlockGarden; import com.jaquadro.minecraft.gardencore.block.tile.TileEntityGarden; import cpw.mods.fml.common.Loader; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import plantmegapack.bin.PMPRenderers; import plantmegapack.block.PMPBlockPlant; import plantmegapack.common.PMPPlantGrowthType;
12,468
package com.jaquadro.minecraft.gardencore.integration; public class PlantMegaPackIntegration { public static final String MOD_ID = "plantmegapack"; public static void init() { if (Loader.isModLoaded("plantmegapack")) { GardenCoreAPI.instance().registerBonemealHandler(new PlantMegaPackIntegration.BonemealHandler()); PlantRegistry plantRegistry = PlantRegistry.instance(); PlantMegaPackIntegration.PlantInfo resolver = new PlantMegaPackIntegration.PlantInfo(); plantRegistry.registerPlantInfo((String)"plantmegapack", resolver); plantRegistry.registerPlantRenderer(PMPRenderers.renderPlantID, PlantRegistry.CROSSED_SQUARES_RENDERER); } } public static class PlantInfo implements IPlantInfo { public int getPlantHeight(Block block, int meta) { if (block != null && block instanceof PMPBlockPlant) { PMPBlockPlant plantBlock = (PMPBlockPlant)block; return plantBlock.plantData.attributes.growthType == PMPPlantGrowthType.DOUBLE && meta >= 2 ? 2 : 1; } else { return 1; } } public int getPlantSectionMeta(Block block, int meta, int section) { if (block != null && block instanceof PMPBlockPlant) { PMPBlockPlant plantBlock = (PMPBlockPlant)block; if (plantBlock.plantData.attributes.growthType == PMPPlantGrowthType.DOUBLE) { switch(section) { case 1: return meta; case 2: return meta >= 2 ? meta + 1 : meta; } } return meta; } else { return meta; } } public PlantType getPlantTypeClass(Block block, int meta) { if (block != null && block instanceof PMPBlockPlant) { PMPBlockPlant plantBlock = (PMPBlockPlant)block; switch(plantBlock.plantData.attributes.renderType) { case CROP: case NORMAL: case STALK: case STAR: return PlantType.GROUND; case EPIPHYTE_HORIZONTAL: case EPIPHYTE_VERTICAL: return PlantType.SIDE; case FLAT: case GROUNDCOVER: return PlantType.GROUND_COVER; case FLOATING_FLAT: return PlantType.AQUATIC_COVER; case FLOATING_FLOWER: case FLOATING_PLANT: return PlantType.AQUATIC_SURFACE; case IMMERSED: return PlantType.AQUATIC_EMERGENT; case VINE_FLOWER: case VINE_NORMAL: case VINE_RANDOM: case VINE_VANILLA: return PlantType.HANGING_SIDE; case WATER: case WATER_FLAT: return PlantType.AQUATIC; default: return PlantType.INVALID; } } else { return PlantType.INVALID; } }
package com.jaquadro.minecraft.gardencore.integration; public class PlantMegaPackIntegration { public static final String MOD_ID = "plantmegapack"; public static void init() { if (Loader.isModLoaded("plantmegapack")) { GardenCoreAPI.instance().registerBonemealHandler(new PlantMegaPackIntegration.BonemealHandler()); PlantRegistry plantRegistry = PlantRegistry.instance(); PlantMegaPackIntegration.PlantInfo resolver = new PlantMegaPackIntegration.PlantInfo(); plantRegistry.registerPlantInfo((String)"plantmegapack", resolver); plantRegistry.registerPlantRenderer(PMPRenderers.renderPlantID, PlantRegistry.CROSSED_SQUARES_RENDERER); } } public static class PlantInfo implements IPlantInfo { public int getPlantHeight(Block block, int meta) { if (block != null && block instanceof PMPBlockPlant) { PMPBlockPlant plantBlock = (PMPBlockPlant)block; return plantBlock.plantData.attributes.growthType == PMPPlantGrowthType.DOUBLE && meta >= 2 ? 2 : 1; } else { return 1; } } public int getPlantSectionMeta(Block block, int meta, int section) { if (block != null && block instanceof PMPBlockPlant) { PMPBlockPlant plantBlock = (PMPBlockPlant)block; if (plantBlock.plantData.attributes.growthType == PMPPlantGrowthType.DOUBLE) { switch(section) { case 1: return meta; case 2: return meta >= 2 ? meta + 1 : meta; } } return meta; } else { return meta; } } public PlantType getPlantTypeClass(Block block, int meta) { if (block != null && block instanceof PMPBlockPlant) { PMPBlockPlant plantBlock = (PMPBlockPlant)block; switch(plantBlock.plantData.attributes.renderType) { case CROP: case NORMAL: case STALK: case STAR: return PlantType.GROUND; case EPIPHYTE_HORIZONTAL: case EPIPHYTE_VERTICAL: return PlantType.SIDE; case FLAT: case GROUNDCOVER: return PlantType.GROUND_COVER; case FLOATING_FLAT: return PlantType.AQUATIC_COVER; case FLOATING_FLOWER: case FLOATING_PLANT: return PlantType.AQUATIC_SURFACE; case IMMERSED: return PlantType.AQUATIC_EMERGENT; case VINE_FLOWER: case VINE_NORMAL: case VINE_RANDOM: case VINE_VANILLA: return PlantType.HANGING_SIDE; case WATER: case WATER_FLAT: return PlantType.AQUATIC; default: return PlantType.INVALID; } } else { return PlantType.INVALID; } }
public PlantSize getPlantSizeClass(Block block, int meta) {
5
2023-12-12 08:13:16+00:00
16k
Zergatul/java-scripting-language
src/test/java/com/zergatul/scripting/tests/FloatsTest.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.BoolStorage; import com.zergatul.scripting.helpers.FloatStorage; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List;
13,579
package com.zergatul.scripting.tests; public class FloatsTest { @BeforeEach public void clean() {
package com.zergatul.scripting.tests; public class FloatsTest { @BeforeEach public void clean() {
ApiRoot.boolStorage = new BoolStorage();
1
2023-12-10 00:37:27+00:00
16k
muchfish/ruoyi-vue-pro-sample
yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/sms/SmsTemplateServiceImplTest.java
[ { "identifier": "CommonStatusEnum", "path": "yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/enums/CommonStatusEnum.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum CommonStatusEnum implements IntArrayValuable {\n\n ENABLE(0, \"开启\"),\n DISABLE(1, \"关闭\");\...
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum; import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.collection.ArrayUtils; import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.sms.core.client.SmsClient; import cn.iocoder.yudao.framework.sms.core.client.SmsCommonResult; import cn.iocoder.yudao.framework.sms.core.client.dto.SmsTemplateRespDTO; import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateCreateReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateExportReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplatePageReqVO; import cn.iocoder.yudao.module.system.controller.admin.sms.vo.template.SmsTemplateUpdateReqVO; import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsChannelDO; import cn.iocoder.yudao.module.system.dal.dataobject.sms.SmsTemplateDO; import cn.iocoder.yudao.module.system.dal.mysql.sms.SmsTemplateMapper; import cn.iocoder.yudao.module.system.enums.sms.SmsTemplateTypeEnum; import com.google.common.collect.Lists; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import javax.annotation.Resource; import java.util.List; import java.util.function.Consumer; import static cn.hutool.core.util.RandomUtil.randomEle; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime; import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals; import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException; import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*; import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when;
13,016
package cn.iocoder.yudao.module.system.service.sms; @Import(SmsTemplateServiceImpl.class) public class SmsTemplateServiceImplTest extends BaseDbUnitTest { @Resource private SmsTemplateServiceImpl smsTemplateService; @Resource private SmsTemplateMapper smsTemplateMapper; @MockBean private SmsChannelService smsChannelService; @MockBean private SmsClient smsClient; @Test public void testParseTemplateContentParams() { // 准备参数 String content = "正在进行登录操作{operation},您的验证码是{code}"; // mock 方法 // 调用 List<String> params = smsTemplateService.parseTemplateContentParams(content); // 断言 assertEquals(Lists.newArrayList("operation", "code"), params); } @Test @SuppressWarnings("unchecked") public void testCreateSmsTemplate_success() { // 准备参数 SmsTemplateCreateReqVO reqVO = randomPojo(SmsTemplateCreateReqVO.class, o -> { o.setContent("正在进行登录操作{operation},您的验证码是{code}"); o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setType(randomEle(SmsTemplateTypeEnum.values()).getType()); // 保证 type 的 范围 }); // mock Channel 的方法 SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> { o.setId(reqVO.getChannelId()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 保证 status 开启,创建必须处于这个状态 }); when(smsChannelService.getSmsChannel(eq(channelDO.getId()))).thenReturn(channelDO); // mock 获得 API 短信模板成功 when(smsChannelService.getSmsClient(eq(reqVO.getChannelId()))).thenReturn(smsClient); when(smsClient.getSmsTemplate(eq(reqVO.getApiTemplateId()))).thenReturn(randomPojo(SmsCommonResult.class, SmsTemplateRespDTO.class, o -> o.setCode(GlobalErrorCodeConstants.SUCCESS.getCode()))); // 调用 Long smsTemplateId = smsTemplateService.createSmsTemplate(reqVO); // 断言 assertNotNull(smsTemplateId); // 校验记录的属性是否正确 SmsTemplateDO smsTemplate = smsTemplateMapper.selectById(smsTemplateId); assertPojoEquals(reqVO, smsTemplate); assertEquals(Lists.newArrayList("operation", "code"), smsTemplate.getParams()); assertEquals(channelDO.getCode(), smsTemplate.getChannelCode()); } @Test @SuppressWarnings("unchecked") public void testUpdateSmsTemplate_success() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO(); smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 SmsTemplateUpdateReqVO reqVO = randomPojo(SmsTemplateUpdateReqVO.class, o -> { o.setId(dbSmsTemplate.getId()); // 设置更新的 ID o.setContent("正在进行登录操作{operation},您的验证码是{code}"); o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setType(randomEle(SmsTemplateTypeEnum.values()).getType()); // 保证 type 的 范围 }); // mock 方法 SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> { o.setId(reqVO.getChannelId()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 保证 status 开启,创建必须处于这个状态 }); when(smsChannelService.getSmsChannel(eq(channelDO.getId()))).thenReturn(channelDO); // mock 获得 API 短信模板成功 when(smsChannelService.getSmsClient(eq(reqVO.getChannelId()))).thenReturn(smsClient); when(smsClient.getSmsTemplate(eq(reqVO.getApiTemplateId()))).thenReturn(randomPojo(SmsCommonResult.class, SmsTemplateRespDTO.class, o -> o.setCode(GlobalErrorCodeConstants.SUCCESS.getCode()))); // 调用 smsTemplateService.updateSmsTemplate(reqVO); // 校验是否更新正确 SmsTemplateDO smsTemplate = smsTemplateMapper.selectById(reqVO.getId()); // 获取最新的 assertPojoEquals(reqVO, smsTemplate); assertEquals(Lists.newArrayList("operation", "code"), smsTemplate.getParams()); assertEquals(channelDO.getCode(), smsTemplate.getChannelCode()); } @Test public void testUpdateSmsTemplate_notExists() { // 准备参数 SmsTemplateUpdateReqVO reqVO = randomPojo(SmsTemplateUpdateReqVO.class); // 调用, 并断言异常 assertServiceException(() -> smsTemplateService.updateSmsTemplate(reqVO), SMS_TEMPLATE_NOT_EXISTS); } @Test public void testDeleteSmsTemplate_success() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO(); smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbSmsTemplate.getId(); // 调用 smsTemplateService.deleteSmsTemplate(id); // 校验数据不存在了 assertNull(smsTemplateMapper.selectById(id)); } @Test public void testDeleteSmsTemplate_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> smsTemplateService.deleteSmsTemplate(id), SMS_TEMPLATE_NOT_EXISTS); } @Test public void testGetSmsTemplatePage() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomPojo(SmsTemplateDO.class, o -> { // 等会查询到 o.setType(SmsTemplateTypeEnum.PROMOTION.getType()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCode("tudou"); o.setContent("芋道源码"); o.setApiTemplateId("yunai"); o.setChannelId(1L); o.setCreateTime(buildTime(2021, 11, 11)); }); smsTemplateMapper.insert(dbSmsTemplate); // 测试 type 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setType(SmsTemplateTypeEnum.VERIFICATION_CODE.getType()))); // 测试 status 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 code 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setCode("yuanma"))); // 测试 content 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setContent("源码"))); // 测试 apiTemplateId 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setApiTemplateId("nai"))); // 测试 channelId 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setChannelId(2L))); // 测试 createTime 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setCreateTime(buildTime(2021, 12, 12)))); // 准备参数 SmsTemplatePageReqVO reqVO = new SmsTemplatePageReqVO(); reqVO.setType(SmsTemplateTypeEnum.PROMOTION.getType()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setCode("tu"); reqVO.setContent("芋道"); reqVO.setApiTemplateId("yu"); reqVO.setChannelId(1L);
package cn.iocoder.yudao.module.system.service.sms; @Import(SmsTemplateServiceImpl.class) public class SmsTemplateServiceImplTest extends BaseDbUnitTest { @Resource private SmsTemplateServiceImpl smsTemplateService; @Resource private SmsTemplateMapper smsTemplateMapper; @MockBean private SmsChannelService smsChannelService; @MockBean private SmsClient smsClient; @Test public void testParseTemplateContentParams() { // 准备参数 String content = "正在进行登录操作{operation},您的验证码是{code}"; // mock 方法 // 调用 List<String> params = smsTemplateService.parseTemplateContentParams(content); // 断言 assertEquals(Lists.newArrayList("operation", "code"), params); } @Test @SuppressWarnings("unchecked") public void testCreateSmsTemplate_success() { // 准备参数 SmsTemplateCreateReqVO reqVO = randomPojo(SmsTemplateCreateReqVO.class, o -> { o.setContent("正在进行登录操作{operation},您的验证码是{code}"); o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setType(randomEle(SmsTemplateTypeEnum.values()).getType()); // 保证 type 的 范围 }); // mock Channel 的方法 SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> { o.setId(reqVO.getChannelId()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 保证 status 开启,创建必须处于这个状态 }); when(smsChannelService.getSmsChannel(eq(channelDO.getId()))).thenReturn(channelDO); // mock 获得 API 短信模板成功 when(smsChannelService.getSmsClient(eq(reqVO.getChannelId()))).thenReturn(smsClient); when(smsClient.getSmsTemplate(eq(reqVO.getApiTemplateId()))).thenReturn(randomPojo(SmsCommonResult.class, SmsTemplateRespDTO.class, o -> o.setCode(GlobalErrorCodeConstants.SUCCESS.getCode()))); // 调用 Long smsTemplateId = smsTemplateService.createSmsTemplate(reqVO); // 断言 assertNotNull(smsTemplateId); // 校验记录的属性是否正确 SmsTemplateDO smsTemplate = smsTemplateMapper.selectById(smsTemplateId); assertPojoEquals(reqVO, smsTemplate); assertEquals(Lists.newArrayList("operation", "code"), smsTemplate.getParams()); assertEquals(channelDO.getCode(), smsTemplate.getChannelCode()); } @Test @SuppressWarnings("unchecked") public void testUpdateSmsTemplate_success() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO(); smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 SmsTemplateUpdateReqVO reqVO = randomPojo(SmsTemplateUpdateReqVO.class, o -> { o.setId(dbSmsTemplate.getId()); // 设置更新的 ID o.setContent("正在进行登录操作{operation},您的验证码是{code}"); o.setStatus(randomEle(CommonStatusEnum.values()).getStatus()); // 保证 status 的范围 o.setType(randomEle(SmsTemplateTypeEnum.values()).getType()); // 保证 type 的 范围 }); // mock 方法 SmsChannelDO channelDO = randomPojo(SmsChannelDO.class, o -> { o.setId(reqVO.getChannelId()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); // 保证 status 开启,创建必须处于这个状态 }); when(smsChannelService.getSmsChannel(eq(channelDO.getId()))).thenReturn(channelDO); // mock 获得 API 短信模板成功 when(smsChannelService.getSmsClient(eq(reqVO.getChannelId()))).thenReturn(smsClient); when(smsClient.getSmsTemplate(eq(reqVO.getApiTemplateId()))).thenReturn(randomPojo(SmsCommonResult.class, SmsTemplateRespDTO.class, o -> o.setCode(GlobalErrorCodeConstants.SUCCESS.getCode()))); // 调用 smsTemplateService.updateSmsTemplate(reqVO); // 校验是否更新正确 SmsTemplateDO smsTemplate = smsTemplateMapper.selectById(reqVO.getId()); // 获取最新的 assertPojoEquals(reqVO, smsTemplate); assertEquals(Lists.newArrayList("operation", "code"), smsTemplate.getParams()); assertEquals(channelDO.getCode(), smsTemplate.getChannelCode()); } @Test public void testUpdateSmsTemplate_notExists() { // 准备参数 SmsTemplateUpdateReqVO reqVO = randomPojo(SmsTemplateUpdateReqVO.class); // 调用, 并断言异常 assertServiceException(() -> smsTemplateService.updateSmsTemplate(reqVO), SMS_TEMPLATE_NOT_EXISTS); } @Test public void testDeleteSmsTemplate_success() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomSmsTemplateDO(); smsTemplateMapper.insert(dbSmsTemplate);// @Sql: 先插入出一条存在的数据 // 准备参数 Long id = dbSmsTemplate.getId(); // 调用 smsTemplateService.deleteSmsTemplate(id); // 校验数据不存在了 assertNull(smsTemplateMapper.selectById(id)); } @Test public void testDeleteSmsTemplate_notExists() { // 准备参数 Long id = randomLongId(); // 调用, 并断言异常 assertServiceException(() -> smsTemplateService.deleteSmsTemplate(id), SMS_TEMPLATE_NOT_EXISTS); } @Test public void testGetSmsTemplatePage() { // mock 数据 SmsTemplateDO dbSmsTemplate = randomPojo(SmsTemplateDO.class, o -> { // 等会查询到 o.setType(SmsTemplateTypeEnum.PROMOTION.getType()); o.setStatus(CommonStatusEnum.ENABLE.getStatus()); o.setCode("tudou"); o.setContent("芋道源码"); o.setApiTemplateId("yunai"); o.setChannelId(1L); o.setCreateTime(buildTime(2021, 11, 11)); }); smsTemplateMapper.insert(dbSmsTemplate); // 测试 type 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setType(SmsTemplateTypeEnum.VERIFICATION_CODE.getType()))); // 测试 status 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus()))); // 测试 code 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setCode("yuanma"))); // 测试 content 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setContent("源码"))); // 测试 apiTemplateId 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setApiTemplateId("nai"))); // 测试 channelId 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setChannelId(2L))); // 测试 createTime 不匹配 smsTemplateMapper.insert(ObjectUtils.cloneIgnoreId(dbSmsTemplate, o -> o.setCreateTime(buildTime(2021, 12, 12)))); // 准备参数 SmsTemplatePageReqVO reqVO = new SmsTemplatePageReqVO(); reqVO.setType(SmsTemplateTypeEnum.PROMOTION.getType()); reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus()); reqVO.setCode("tu"); reqVO.setContent("芋道"); reqVO.setApiTemplateId("yu"); reqVO.setChannelId(1L);
reqVO.setCreateTime(buildBetweenTime(2021, 11, 1, 2021, 12, 1));
17
2023-12-08 02:48:42+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;
11,333
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; private Coordinate endPx; // properties for elapsed time, boolean isMoving and current position private static float elapsedTime; private static float moveDuration; public static boolean isMoving; public boolean movingFinished; private Stack pieceStack; private Image pieceImage; public moveBotTile() { elapsedTime = 0; isMoving = false; movingFinished = false; } // method for starting the move public void startMove(int startX, int startY, int endX, int endY) { /* * Method to simulate a move (start of the Move) */ // coordinates this.start = startX; this.end = endX; // rerender Board with new Empty Variables SenetBoom.renderBoard(); // set the maximum duration fitting the length of the way that the soldier moves // per 50 pixel, add 0.5f to max duration // Begin: calculate Vector: startPx = SenetBoom.calculatePXbyTile(startX); endPx = SenetBoom.calculatePXbyTile(endX); Vector2 pointA = new Vector2(startPx.getX(), startPx.getY()); Vector2 pointB = new Vector2(endPx.getX(), endPx.getY()); Vector2 vectorAB = pointB.sub(pointA); float lengthVec = vectorAB.len(); int timefactor = (int) lengthVec / 50; moveDuration = timefactor * 0.75f; Tile[] gameBoard = Board.getBoard(); Tile startTile = gameBoard[start];
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; private Coordinate endPx; // properties for elapsed time, boolean isMoving and current position private static float elapsedTime; private static float moveDuration; public static boolean isMoving; public boolean movingFinished; private Stack pieceStack; private Image pieceImage; public moveBotTile() { elapsedTime = 0; isMoving = false; movingFinished = false; } // method for starting the move public void startMove(int startX, int startY, int endX, int endY) { /* * Method to simulate a move (start of the Move) */ // coordinates this.start = startX; this.end = endX; // rerender Board with new Empty Variables SenetBoom.renderBoard(); // set the maximum duration fitting the length of the way that the soldier moves // per 50 pixel, add 0.5f to max duration // Begin: calculate Vector: startPx = SenetBoom.calculatePXbyTile(startX); endPx = SenetBoom.calculatePXbyTile(endX); Vector2 pointA = new Vector2(startPx.getX(), startPx.getY()); Vector2 pointB = new Vector2(endPx.getX(), endPx.getY()); Vector2 vectorAB = pointB.sub(pointA); float lengthVec = vectorAB.len(); int timefactor = (int) lengthVec / 50; moveDuration = timefactor * 0.75f; Tile[] gameBoard = Board.getBoard(); Tile startTile = gameBoard[start];
if (startTile.getPiece().getColour() == Piece.Color.WHITE) {
3
2023-12-05 22:19:00+00:00
16k
fabriciofx/cactoos-pdf
src/test/java/com/github/fabriciofx/cactoos/pdf/DocumentTest.java
[ { "identifier": "Contents", "path": "src/main/java/com/github/fabriciofx/cactoos/pdf/content/Contents.java", "snippet": "public final class Contents extends ListEnvelope<Content> implements Object {\n /**\n * Ctor.\n *\n * @param objects An array of objects\n */\n public Contents(f...
import com.github.fabriciofx.cactoos.pdf.content.Contents; import com.github.fabriciofx.cactoos.pdf.content.Image; import com.github.fabriciofx.cactoos.pdf.content.Text; import com.github.fabriciofx.cactoos.pdf.id.Serial; import com.github.fabriciofx.cactoos.pdf.image.format.Jpeg; import com.github.fabriciofx.cactoos.pdf.image.format.Png; import com.github.fabriciofx.cactoos.pdf.page.DefaultPage; import com.github.fabriciofx.cactoos.pdf.pages.DefaultPages; import com.github.fabriciofx.cactoos.pdf.resource.font.Courier; import com.github.fabriciofx.cactoos.pdf.resource.font.Helvetica; import com.github.fabriciofx.cactoos.pdf.resource.font.Symbol; import com.github.fabriciofx.cactoos.pdf.resource.font.TimesRoman; import com.github.fabriciofx.cactoos.pdf.resource.font.ZapfDingbats; import org.cactoos.bytes.BytesOf; import org.cactoos.io.ResourceOf; import org.cactoos.text.TextOf; import org.hamcrest.core.IsEqual; import org.junit.jupiter.api.Test; import org.llorllale.cactoos.matchers.Assertion;
10,858
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf; /** * Test case for {@link Document}. * * @since 0.0.1 */ @SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.ExcessiveMethodLength"}) final class DocumentTest { @Test void buildDocumentHelloWorld() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 18); final byte[] actual = new Document( id, new DefaultPages( id, new DefaultPage( id, new Contents( new Text( id, font, 0, 500, 80, new TextOf("Hello World!") ) ) ) ) ).asBytes(); new Assertion<>( "Must match with hello world PDF document", new BytesOf(new ResourceOf("document/hello-world.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFileContent() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 12); final byte[] actual = new Document( id, new DefaultPages( id, new DefaultPage( id, new Contents( new Text( id, font, 20, 800, 100, new TextOf( new ResourceOf("text/20k_c1.txt") ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with PDF document with a text file", new BytesOf(new ResourceOf("document/text-20k.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFontsAndImages() throws Exception { final Id id = new Serial(); final Font times = new TimesRoman(id, 16);
/* * The MIT License (MIT) * * Copyright (C) 2023-2024 Fabrício Barros Cabral * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.fabriciofx.cactoos.pdf; /** * Test case for {@link Document}. * * @since 0.0.1 */ @SuppressWarnings({"PMD.AvoidDuplicateLiterals", "PMD.ExcessiveMethodLength"}) final class DocumentTest { @Test void buildDocumentHelloWorld() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 18); final byte[] actual = new Document( id, new DefaultPages( id, new DefaultPage( id, new Contents( new Text( id, font, 0, 500, 80, new TextOf("Hello World!") ) ) ) ) ).asBytes(); new Assertion<>( "Must match with hello world PDF document", new BytesOf(new ResourceOf("document/hello-world.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFileContent() throws Exception { final Id id = new Serial(); final Font font = new TimesRoman(id, 12); final byte[] actual = new Document( id, new DefaultPages( id, new DefaultPage( id, new Contents( new Text( id, font, 20, 800, 100, new TextOf( new ResourceOf("text/20k_c1.txt") ) ) ) ) ) ).asBytes(); new Assertion<>( "Must match with PDF document with a text file", new BytesOf(new ResourceOf("document/text-20k.pdf")).asBytes(), new IsEqual<>(actual) ).affirm(); } @Test void buildDocumentWithFontsAndImages() throws Exception { final Id id = new Serial(); final Font times = new TimesRoman(id, 16);
final Font helvetica = new Helvetica(id, 16);
9
2023-12-05 00:07:24+00:00
16k
sinbad-navigator/erp-crm
center/src/main/java/com/ec/web/controller/system/SysLoginController.java
[ { "identifier": "StringUtils", "path": "common/src/main/java/com/ec/common/utils/StringUtils.java", "snippet": "public class StringUtils extends org.apache.commons.lang3.StringUtils {\n /**\n * 空字符串\n */\n private static final String NULLSTR = \"\";\n\n /**\n * 下划线\n */\n pri...
import java.util.List; import java.util.Set; import com.ec.common.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.ec.common.constant.Constants; import com.ec.common.core.domain.AjaxResult; import com.ec.common.core.domain.entity.SysMenu; import com.ec.common.core.domain.entity.SysUser; import com.ec.common.core.domain.model.LoginBody; import com.ec.common.utils.SecurityUtils; import com.ec.auth.web.service.SysLoginService; import com.ec.auth.web.service.SysPermissionService; import com.ec.sys.service.ISysMenuService; import javax.servlet.http.HttpServletRequest;
12,303
package com.ec.web.controller.system; /** * 登录验证 * * @author ec */ @RestController public class SysLoginController { @Autowired private SysLoginService loginService; @Autowired
package com.ec.web.controller.system; /** * 登录验证 * * @author ec */ @RestController public class SysLoginController { @Autowired private SysLoginService loginService; @Autowired
private ISysMenuService menuService;
9
2023-12-07 14:23:12+00:00
16k
gaetanBloch/jhlite-gateway
src/main/java/com/mycompany/myapp/shared/pagination/infrastructure/secondary/JhipsterSampleApplicationPages.java
[ { "identifier": "Assert", "path": "src/main/java/com/mycompany/myapp/shared/error/domain/Assert.java", "snippet": "public class Assert {\n\n private Assert() {}\n\n /**\n * Ensure that the input is not null\n *\n * @param field\n * name of the field to check (will be displayed in exce...
import java.util.function.Function; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import com.mycompany.myapp.shared.error.domain.Assert; import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPage; import com.mycompany.myapp.shared.pagination.domain.JhipsterSampleApplicationPageable;
11,177
package com.mycompany.myapp.shared.pagination.infrastructure.secondary; public final class JhipsterSampleApplicationPages { private JhipsterSampleApplicationPages() {}
package com.mycompany.myapp.shared.pagination.infrastructure.secondary; public final class JhipsterSampleApplicationPages { private JhipsterSampleApplicationPages() {}
public static Pageable from(JhipsterSampleApplicationPageable pagination) {
2
2023-12-10 06:39:18+00:00
16k
Crydsch/the-one
src/report/SamplingReport.java
[ { "identifier": "DTNHost", "path": "src/core/DTNHost.java", "snippet": "public class DTNHost implements Comparable<DTNHost> {\n\tprivate static int count = 0;\n\tprivate int ID;\n\n\tprivate Coord destination;\t// where is it going\n\n\tprivate MessageRouter router;\n\tprivate MovementEngine movementEng...
import core.DTNHost; import core.Settings; import core.SettingsError; import core.SimClock; import core.UpdateListener; import java.util.List;
13,281
package report; /** * Abstract class that makes it easier to implement sampling reports. * * @author teemuk */ public abstract class SamplingReport extends Report implements UpdateListener { //========================================================================// // Settings //========================================================================// /** Interval in seconds between samples ({@value}). */ public static final String SAMPLE_INTERVAL_SETTING = "sampleInterval"; /** Default value for sample interval ({@value} seconds). */ public static final double DEFAULT_SAMPLE_INTERVAL = 60; //========================================================================// //========================================================================// // Instance vars //========================================================================// private double lastRecord = Double.MIN_VALUE; protected final double interval; //========================================================================// //========================================================================// // Subclass API //========================================================================// protected abstract void sample(final List<DTNHost> hosts); //========================================================================// //========================================================================// // Report //========================================================================// protected SamplingReport() { super(); // Set the sampling interval final Settings settings = super.getSettings(); this.interval = settings.getDouble(SAMPLE_INTERVAL_SETTING, DEFAULT_SAMPLE_INTERVAL); if (this.interval <= 0) {
package report; /** * Abstract class that makes it easier to implement sampling reports. * * @author teemuk */ public abstract class SamplingReport extends Report implements UpdateListener { //========================================================================// // Settings //========================================================================// /** Interval in seconds between samples ({@value}). */ public static final String SAMPLE_INTERVAL_SETTING = "sampleInterval"; /** Default value for sample interval ({@value} seconds). */ public static final double DEFAULT_SAMPLE_INTERVAL = 60; //========================================================================// //========================================================================// // Instance vars //========================================================================// private double lastRecord = Double.MIN_VALUE; protected final double interval; //========================================================================// //========================================================================// // Subclass API //========================================================================// protected abstract void sample(final List<DTNHost> hosts); //========================================================================// //========================================================================// // Report //========================================================================// protected SamplingReport() { super(); // Set the sampling interval final Settings settings = super.getSettings(); this.interval = settings.getDouble(SAMPLE_INTERVAL_SETTING, DEFAULT_SAMPLE_INTERVAL); if (this.interval <= 0) {
throw new SettingsError("Setting '" + SAMPLE_INTERVAL_SETTING
2
2023-12-10 15:51:41+00:00
16k
seleuco/MAME4droid-2024
android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/helpers/DialogHelper.java
[ { "identifier": "PRESS_WAIT", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/input/InputHandler.java", "snippet": "final static public int PRESS_WAIT = 100;" }, { "identifier": "Emulator", "path": "android-MAME4droid/app/src/main/java/com/seleuco/mame4droid/Emulator.jav...
import static com.seleuco.mame4droid.input.InputHandler.PRESS_WAIT; import android.app.AlertDialog; import android.app.Dialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.view.View; import com.seleuco.mame4droid.Emulator; import com.seleuco.mame4droid.MAME4droid; import com.seleuco.mame4droid.input.ControlCustomizer; import com.seleuco.mame4droid.views.IEmuView; import java.util.Arrays;
13,055
android.os.Process.killProcess(android.os.Process.myPid()); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Emulator.resume(); DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_EXIT); //dialog.cancel(); } }); dialog = builder.create(); break; case DIALOG_ERROR_WRITING: builder.setMessage("Error") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //System.exit(0); DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_ERROR_WRITING); mm.getMainHelper().restartApp(); //mm.showDialog(DialogHelper.DIALOG_LOAD_FILE_EXPLORER); } }); dialog = builder.create(); break; case DIALOG_INFO: builder.setMessage("Info") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; Emulator.resume(); mm.removeDialog(DIALOG_INFO); } }); dialog = builder.create(); break; case DIALOG_OPTIONS: case DIALOG_FULLSCREEN: CharSequence[] items1 = {"Load State", "Save State", "Help", "Settings", "Keyboard"}; CharSequence[] items2 = {"Help", "Settings", "Keyboard"}; CharSequence[] items3 = {"Exit", "Load State", "Save State", "Help", "Settings", "Keyboard"}; CharSequence[] items4 = {"Exit", "Help", "Settings", "Keyboard"}; boolean saveload = Emulator.isInGameButNotInMenu() && Emulator.getValue(Emulator.PAUSE)!=1; final int a = id == DIALOG_FULLSCREEN ? 0 : 1; final int b = saveload ? 0 : 2; if (a == 1) builder.setTitle("Choose an option from the menu."); CharSequence[] items = saveload ? (id == DIALOG_OPTIONS ? items1 : items3) : (id == DIALOG_OPTIONS ? items2 : items4); boolean notKeyboard = !mm.getPrefsHelper().isVirtualKeyboardEnabled() || mm.getInputHandler().getKeyboard().isKeyboardConnected() || mm.getMainHelper().isAndroidTV(); if(notKeyboard) items = Arrays.copyOf(items, items.length-1); builder.setCancelable(true); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0 && a == 0) { mm.showDialog(DialogHelper.DIALOG_EXIT); //if (Emulator.isInMenu()) { /* Emulator.setValue(Emulator.EXIT_GAME, 1); Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.EXIT_GAME, 0); */ /* } else if (!Emulator.isInGame()) mm.showDialog(DialogHelper.DIALOG_EXIT); else { Emulator.setValue(Emulator.EXIT_GAME, 1); Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.EXIT_GAME, 0); } */ } else if (item == 1 - a && b == 0) { Emulator.resume(); Emulator.setValue(Emulator.LOADSTATE, 1); Emulator.setSaveorload(true); //Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.LOADSTATE, 0); } else if (item == 2 - a && b == 0) { Emulator.resume(); Emulator.setValue(Emulator.SAVESTATE, 1); Emulator.setSaveorload(true); //Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.SAVESTATE, 0); } else if (item == 3 - a - b) { mm.getMainHelper().showHelp(); } else if (item == 4 - a - b) { mm.getMainHelper().showSettings(); } else if (item == 5 - a - b) {
/* * This file is part of MAME4droid. * * Copyright (C) 2015 David Valdeita (Seleuco) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses>. * * Linking MAME4droid statically or dynamically with other modules is * making a combined work based on MAME4droid. Thus, the terms and * conditions of the GNU General Public License cover the whole * combination. * * In addition, as a special exception, the copyright holders of MAME4droid * give you permission to combine MAME4droid with free software programs * or libraries that are released under the GNU LGPL and with code included * in the standard release of MAME under the MAME License (or modified * versions of such code, with unchanged license). You may copy and * distribute such a system following the terms of the GNU GPL for MAME4droid * and the licenses of the other code concerned, provided that you include * the source code of that other code when and as the GNU GPL requires * distribution of source code. * * Note that people who make modified versions of MAME4idroid are not * obligated to grant this special exception for their modified versions; it * is their choice whether to do so. The GNU General Public License * gives permission to release a modified version without this exception; * this exception also makes it possible to release a modified version * which carries forward this exception. * * MAME4droid is dual-licensed: Alternatively, you can license MAME4droid * under a MAME license, as set out in http://mamedev.org/ */ package com.seleuco.mame4droid.helpers; public class DialogHelper { public static int savedDialog = DialogHelper.DIALOG_NONE; public final static int DIALOG_NONE = -1; public final static int DIALOG_EXIT = 1; public final static int DIALOG_ERROR_WRITING = 2; public final static int DIALOG_INFO = 3; public final static int DIALOG_OPTIONS = 5; public final static int DIALOG_FULLSCREEN = 7; public final static int DIALOG_FINISH_CUSTOM_LAYOUT = 10; public final static int DIALOG_EMU_RESTART = 11; public final static int DIALOG_NO_PERMISSIONS = 12; public final static int DIALOG_ROMs = 13; protected MAME4droid mm = null; static protected String errorMsg; static protected String infoMsg; public void setErrorMsg(String errorMsg) { DialogHelper.errorMsg = errorMsg; } public void setInfoMsg(String infoMsg) { DialogHelper.infoMsg = infoMsg; } public DialogHelper(MAME4droid value) { mm = value; } public Dialog createDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(mm); switch (id) { case DIALOG_FINISH_CUSTOM_LAYOUT: builder.setMessage("Do you want to save changes?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT); ControlCustomizer.setEnabled(false); mm.getInputHandler().getControlCustomizer().saveDefinedControlLayout(); mm.getEmuView().setVisibility(View.VISIBLE); mm.getEmuView().requestFocus(); Emulator.resume(); mm.getInputView().invalidate(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_FINISH_CUSTOM_LAYOUT); ControlCustomizer.setEnabled(false); mm.getInputHandler().getControlCustomizer().discardDefinedControlLayout(); mm.getEmuView().setVisibility(View.VISIBLE); mm.getEmuView().requestFocus(); Emulator.resume(); mm.getInputView().invalidate(); } }); dialog = builder.create(); break; case DIALOG_ROMs: String message = ""; message += "Where do you have stored or want to store your ROM files?\n\n" + "By default, an empty internal folder will be used (but you should manually copy your ROMs files there using a PC). You can also select a folder with ROMs files from your external storage which will " + "need to be authorized in the next step so MAME4droid can read the ROMS from it.\n\n" + "Also, if you select an external storage folder, your ROMs files will not be deleted when the app is uninstalled and you can use an Android file manager to move your ROMs there without needing a PC."; builder.setMessage(message) .setCancelable(false) .setPositiveButton("Internal", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_ROMs); if (mm.getMainHelper().isAndroidTV()) mm.getMainHelper().setInstallationDirType(MainHelper.INSTALLATION_DIR_MEDIA_FOLDER); else mm.getMainHelper().setInstallationDirType(MainHelper.INSTALLATION_DIR_FILES_DIR); mm.getPrefsHelper().setROMsDIR(""); mm.getPrefsHelper().setSAF_Uri(null); Thread t = new Thread(new Runnable() { public void run() { mm.runMAME4droid(); }}); t.start(); //mm.runMAME4droid(); } }) .setNegativeButton("External Storage", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_ROMs); try { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); mm.startActivityForResult(intent, MainHelper.REQUEST_CODE_OPEN_DIRECTORY); //throw new ActivityNotFoundException("TEST"); } catch (ActivityNotFoundException e) { String msg = "Your device doesn't have the native android file manager needed to authorize external storage reading."; if (mm.getMainHelper().isAndroidTV()) msg += "\n\nSome Android TV devices don't include the OS document picker which is needed to grant folder permissions for the apps on Android 11+. As an alternative, select default which use the App Media Folder which is supported on all devices and is created at Android/media/[app package name]. Move any emulator files into that folder with a file manager so the app can access them without any special permissions."; mm.getDialogHelper().showMessage(msg, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { android.os.Process.killProcess(android.os.Process.myPid()); } }); } } }); dialog = builder.create(); break; case DIALOG_EXIT: builder.setMessage("Are you sure you want to exit from app?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //System.exit(0); mm.finishAndRemoveTask(); android.os.Process.killProcess(android.os.Process.myPid()); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Emulator.resume(); DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_EXIT); //dialog.cancel(); } }); dialog = builder.create(); break; case DIALOG_ERROR_WRITING: builder.setMessage("Error") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { //System.exit(0); DialogHelper.savedDialog = DIALOG_NONE; mm.removeDialog(DIALOG_ERROR_WRITING); mm.getMainHelper().restartApp(); //mm.showDialog(DialogHelper.DIALOG_LOAD_FILE_EXPLORER); } }); dialog = builder.create(); break; case DIALOG_INFO: builder.setMessage("Info") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { DialogHelper.savedDialog = DIALOG_NONE; Emulator.resume(); mm.removeDialog(DIALOG_INFO); } }); dialog = builder.create(); break; case DIALOG_OPTIONS: case DIALOG_FULLSCREEN: CharSequence[] items1 = {"Load State", "Save State", "Help", "Settings", "Keyboard"}; CharSequence[] items2 = {"Help", "Settings", "Keyboard"}; CharSequence[] items3 = {"Exit", "Load State", "Save State", "Help", "Settings", "Keyboard"}; CharSequence[] items4 = {"Exit", "Help", "Settings", "Keyboard"}; boolean saveload = Emulator.isInGameButNotInMenu() && Emulator.getValue(Emulator.PAUSE)!=1; final int a = id == DIALOG_FULLSCREEN ? 0 : 1; final int b = saveload ? 0 : 2; if (a == 1) builder.setTitle("Choose an option from the menu."); CharSequence[] items = saveload ? (id == DIALOG_OPTIONS ? items1 : items3) : (id == DIALOG_OPTIONS ? items2 : items4); boolean notKeyboard = !mm.getPrefsHelper().isVirtualKeyboardEnabled() || mm.getInputHandler().getKeyboard().isKeyboardConnected() || mm.getMainHelper().isAndroidTV(); if(notKeyboard) items = Arrays.copyOf(items, items.length-1); builder.setCancelable(true); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { if (item == 0 && a == 0) { mm.showDialog(DialogHelper.DIALOG_EXIT); //if (Emulator.isInMenu()) { /* Emulator.setValue(Emulator.EXIT_GAME, 1); Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.EXIT_GAME, 0); */ /* } else if (!Emulator.isInGame()) mm.showDialog(DialogHelper.DIALOG_EXIT); else { Emulator.setValue(Emulator.EXIT_GAME, 1); Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.EXIT_GAME, 0); } */ } else if (item == 1 - a && b == 0) { Emulator.resume(); Emulator.setValue(Emulator.LOADSTATE, 1); Emulator.setSaveorload(true); //Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.LOADSTATE, 0); } else if (item == 2 - a && b == 0) { Emulator.resume(); Emulator.setValue(Emulator.SAVESTATE, 1); Emulator.setSaveorload(true); //Emulator.resume(); try { Thread.sleep(PRESS_WAIT); } catch (InterruptedException e) { } Emulator.setValue(Emulator.SAVESTATE, 0); } else if (item == 3 - a - b) { mm.getMainHelper().showHelp(); } else if (item == 4 - a - b) { mm.getMainHelper().showSettings(); } else if (item == 5 - a - b) {
((IEmuView) mm.getEmuView()).showSoftKeyboard();
4
2023-12-18 11:16:18+00:00
16k
Swofty-Developments/HypixelSkyBlock
generic/src/main/java/net/swofty/types/generic/gui/inventory/inventories/GUIMinionRecipes.java
[ { "identifier": "ItemStackCreator", "path": "generic/src/main/java/net/swofty/types/generic/gui/inventory/ItemStackCreator.java", "snippet": "public class ItemStackCreator {\n\n public static ItemStack.Builder createNamedItemStack(Material material, String name) {\n return ItemStack.builder(ma...
import net.minestom.server.event.inventory.InventoryCloseEvent; import net.minestom.server.event.inventory.InventoryPreClickEvent; import net.minestom.server.inventory.Inventory; import net.minestom.server.inventory.InventoryType; import net.minestom.server.item.ItemStack; import net.minestom.server.item.Material; import net.swofty.types.generic.gui.inventory.ItemStackCreator; import net.swofty.types.generic.gui.inventory.SkyBlockInventoryGUI; import net.swofty.types.generic.gui.inventory.inventories.sbmenu.crafting.GUIRecipe; import net.swofty.types.generic.gui.inventory.item.GUIClickableItem; import net.swofty.types.generic.item.SkyBlockItem; import net.swofty.types.generic.item.attribute.attributes.ItemAttributeMinionData; import net.swofty.types.generic.item.updater.NonPlayerItemUpdater; import net.swofty.types.generic.minion.MinionRegistry; import net.swofty.types.generic.user.SkyBlockPlayer; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger;
12,271
package net.swofty.types.generic.gui.inventory.inventories; public class GUIMinionRecipes extends SkyBlockInventoryGUI { private static final int[] RECIPE_SLOTS = new int[]{ 11, 12, 13, 14, 15, 21, 22, 23, 30, 31, 32 }; SkyBlockInventoryGUI previousGUI; MinionRegistry registry; public GUIMinionRecipes(MinionRegistry registry, SkyBlockInventoryGUI previousGUI) { super(registry.getDisplay() + " Recipes", InventoryType.CHEST_6_ROW); this.registry = registry; this.previousGUI = previousGUI; } @Override public void onOpen(InventoryGUIOpenEvent e) {
package net.swofty.types.generic.gui.inventory.inventories; public class GUIMinionRecipes extends SkyBlockInventoryGUI { private static final int[] RECIPE_SLOTS = new int[]{ 11, 12, 13, 14, 15, 21, 22, 23, 30, 31, 32 }; SkyBlockInventoryGUI previousGUI; MinionRegistry registry; public GUIMinionRecipes(MinionRegistry registry, SkyBlockInventoryGUI previousGUI) { super(registry.getDisplay() + " Recipes", InventoryType.CHEST_6_ROW); this.registry = registry; this.previousGUI = previousGUI; } @Override public void onOpen(InventoryGUIOpenEvent e) {
fill(ItemStackCreator.createNamedItemStack(Material.BLACK_STAINED_GLASS_PANE));
0
2023-12-14 09:51:15+00:00
16k
litongjava/next-jfinal
src/main/java/com/jfinal/core/ActionHandler.java
[ { "identifier": "Invocation", "path": "src/main/java/com/jfinal/aop/Invocation.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class Invocation {\n\n private static final Object[] NULL_ARGS = new Object[0]; // Prevent new Object[0] by jvm for args of method invoking\n\n private Action acti...
import java.util.function.BiFunction; import com.jfinal.aop.Invocation; import com.jfinal.config.Constants; import com.jfinal.core.paragetter.JsonRequest; import com.jfinal.handler.Handler; import com.jfinal.kit.ReflectKit; import com.jfinal.log.Log; import com.jfinal.render.Render; import com.jfinal.render.RenderException; import com.jfinal.render.RenderManager; import com.jfinal.servlet.http.HttpServletRequest; import com.jfinal.servlet.http.HttpServletResponse;
14,018
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * 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.jfinal.core; /** * ActionHandler */ public class ActionHandler extends Handler { protected boolean devMode; protected ActionMapping actionMapping; protected ControllerFactory controllerFactory; protected ActionReporter actionReporter; protected static final RenderManager renderManager = RenderManager.me(); private static final Log log = Log.getLog(ActionHandler.class); public static boolean resolveJson = false; // 默认 JsonRequestFactory
/** * Copyright (c) 2011-2023, James Zhan 詹波 (jfinal@126.com). * * 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.jfinal.core; /** * ActionHandler */ public class ActionHandler extends Handler { protected boolean devMode; protected ActionMapping actionMapping; protected ControllerFactory controllerFactory; protected ActionReporter actionReporter; protected static final RenderManager renderManager = RenderManager.me(); private static final Log log = Log.getLog(ActionHandler.class); public static boolean resolveJson = false; // 默认 JsonRequestFactory
private static BiFunction<String, HttpServletRequest, JsonRequest> jsonRequestFactory = (jsonString, req) -> {
9
2023-12-19 10:58:33+00:00
16k
HypixelSkyblockmod/ChromaHud
src/java/xyz/apfelmus/cheeto/client/modules/world/SecretAura.java
[ { "identifier": "CF4M", "path": "src/java/xyz/apfelmus/cf4m/CF4M.java", "snippet": "public enum CF4M {\n INSTANCE;\n\n public String packName;\n public String dir;\n public IConfiguration configuration;\n public ClassManager classManager;\n public EventManager eventManager;\n public...
import com.mojang.authlib.GameProfile; import java.util.ArrayList; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockLever; import net.minecraft.block.BlockSkull; import net.minecraft.block.state.IBlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.inventory.GuiChest; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import xyz.apfelmus.cf4m.CF4M; import xyz.apfelmus.cf4m.annotation.Event; import xyz.apfelmus.cf4m.annotation.Setting; import xyz.apfelmus.cf4m.annotation.module.Enable; import xyz.apfelmus.cf4m.annotation.module.Module; import xyz.apfelmus.cf4m.module.Category; import xyz.apfelmus.cheeto.client.events.ClientChatReceivedEvent; import xyz.apfelmus.cheeto.client.events.ClientTickEvent; import xyz.apfelmus.cheeto.client.events.PlayerInteractEvent; import xyz.apfelmus.cheeto.client.events.Render3DEvent; import xyz.apfelmus.cheeto.client.events.WorldUnloadEvent; import xyz.apfelmus.cheeto.client.settings.BooleanSetting; import xyz.apfelmus.cheeto.client.settings.FloatSetting; import xyz.apfelmus.cheeto.client.settings.IntegerSetting; import xyz.apfelmus.cheeto.client.utils.client.RotationUtils; import xyz.apfelmus.cheeto.client.utils.render.Render3DUtils; import xyz.apfelmus.cheeto.client.utils.skyblock.SkyblockUtils;
13,228
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * com.mojang.authlib.GameProfile * net.minecraft.block.Block * net.minecraft.block.BlockChest * net.minecraft.block.BlockLever * net.minecraft.block.BlockSkull * net.minecraft.block.state.IBlockState * net.minecraft.client.Minecraft * net.minecraft.client.gui.inventory.GuiChest * net.minecraft.init.Blocks * net.minecraft.tileentity.TileEntityChest * net.minecraft.tileentity.TileEntitySkull * net.minecraft.util.BlockPos * net.minecraft.util.EnumFacing * net.minecraft.util.MathHelper * net.minecraft.util.MovingObjectPosition * net.minecraft.util.MovingObjectPosition$MovingObjectType * net.minecraft.util.Vec3 * net.minecraftforge.event.entity.player.PlayerInteractEvent$Action */ package xyz.apfelmus.cheeto.client.modules.world; @Module(name="SecretAura", category=Category.WORLD) public class SecretAura implements Runnable { @Setting(name="ScanRange") private IntegerSetting scanRange = new IntegerSetting(7, 0, 8); @Setting(name="ClickRange") private FloatSetting clickRange = new FloatSetting(Float.valueOf(5.0f), Float.valueOf(0.0f), Float.valueOf(8.0f)); @Setting(name="ClickSlot") private IntegerSetting clickSlot = new IntegerSetting(0, 0, 8); @Setting(name="Chests") private BooleanSetting chests = new BooleanSetting(true); @Setting(name="ChestClose") private BooleanSetting chestClose = new BooleanSetting(true); @Setting(name="Levers") private BooleanSetting levers = new BooleanSetting(true); @Setting(name="Essences") private BooleanSetting essences = new BooleanSetting(true); @Setting(name="StonklessStonk") private BooleanSetting stonklessStonk = new BooleanSetting(true); private static Minecraft mc = Minecraft.func_71410_x(); private static List<BlockPos> clicked = new ArrayList<BlockPos>(); private int delayMs = 500; private Thread thread; private List<BlockPos> blocksNear = new ArrayList<BlockPos>(); private boolean inChest = false; private BlockPos selected; private static BlockPos lastPos; @Enable public void onEnable() { this.blocksNear.clear(); clicked.clear(); this.inChest = false; this.selected = null; lastPos = null; } @Event
/* * Decompiled with CFR 0.150. * * Could not load the following classes: * com.mojang.authlib.GameProfile * net.minecraft.block.Block * net.minecraft.block.BlockChest * net.minecraft.block.BlockLever * net.minecraft.block.BlockSkull * net.minecraft.block.state.IBlockState * net.minecraft.client.Minecraft * net.minecraft.client.gui.inventory.GuiChest * net.minecraft.init.Blocks * net.minecraft.tileentity.TileEntityChest * net.minecraft.tileentity.TileEntitySkull * net.minecraft.util.BlockPos * net.minecraft.util.EnumFacing * net.minecraft.util.MathHelper * net.minecraft.util.MovingObjectPosition * net.minecraft.util.MovingObjectPosition$MovingObjectType * net.minecraft.util.Vec3 * net.minecraftforge.event.entity.player.PlayerInteractEvent$Action */ package xyz.apfelmus.cheeto.client.modules.world; @Module(name="SecretAura", category=Category.WORLD) public class SecretAura implements Runnable { @Setting(name="ScanRange") private IntegerSetting scanRange = new IntegerSetting(7, 0, 8); @Setting(name="ClickRange") private FloatSetting clickRange = new FloatSetting(Float.valueOf(5.0f), Float.valueOf(0.0f), Float.valueOf(8.0f)); @Setting(name="ClickSlot") private IntegerSetting clickSlot = new IntegerSetting(0, 0, 8); @Setting(name="Chests") private BooleanSetting chests = new BooleanSetting(true); @Setting(name="ChestClose") private BooleanSetting chestClose = new BooleanSetting(true); @Setting(name="Levers") private BooleanSetting levers = new BooleanSetting(true); @Setting(name="Essences") private BooleanSetting essences = new BooleanSetting(true); @Setting(name="StonklessStonk") private BooleanSetting stonklessStonk = new BooleanSetting(true); private static Minecraft mc = Minecraft.func_71410_x(); private static List<BlockPos> clicked = new ArrayList<BlockPos>(); private int delayMs = 500; private Thread thread; private List<BlockPos> blocksNear = new ArrayList<BlockPos>(); private boolean inChest = false; private BlockPos selected; private static BlockPos lastPos; @Enable public void onEnable() { this.blocksNear.clear(); clicked.clear(); this.inChest = false; this.selected = null; lastPos = null; } @Event
public void onTick(ClientTickEvent event) {
3
2023-12-21 16:22:25+00:00
16k
emtee40/ApkSignatureKill-pc
app/src/main/java/org/jf/dexlib2/builder/instruction/BuilderInstruction20t.java
[ { "identifier": "Format", "path": "app/src/main/java/org/jf/dexlib2/Format.java", "snippet": "public enum Format {\n Format10t(2),\n Format10x(2),\n Format11n(2),\n Format11x(2),\n Format12x(2),\n Format20bc(4),\n Format20t(4),\n Format21c(4),\n Format21ih(4),\n Format21lh(...
import androidx.annotation.NonNull; import org.jf.dexlib2.Format; import org.jf.dexlib2.Opcode; import org.jf.dexlib2.builder.BuilderOffsetInstruction; import org.jf.dexlib2.builder.Label; import org.jf.dexlib2.iface.instruction.formats.Instruction20t;
13,796
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.builder.instruction; public class BuilderInstruction20t extends BuilderOffsetInstruction implements Instruction20t { public static final Format FORMAT = Format.Format20t; public BuilderInstruction20t(@NonNull Opcode opcode,
/* * Copyright 2012, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.jf.dexlib2.builder.instruction; public class BuilderInstruction20t extends BuilderOffsetInstruction implements Instruction20t { public static final Format FORMAT = Format.Format20t; public BuilderInstruction20t(@NonNull Opcode opcode,
@NonNull Label target) {
3
2023-12-16 11:11:16+00:00
16k
123yyh123/xiaofanshu
xfs-modules-server/xfs-user-server/src/main/java/com/yyh/xfs/user/service/impl/UserServiceImpl.java
[ { "identifier": "Result", "path": "xfs-common/common-base/src/main/java/com/yyh/xfs/common/domain/Result.java", "snippet": "@Setter\n@Getter\n@ToString\n@AllArgsConstructor\n@NoArgsConstructor\npublic class Result<T> implements Serializable {\n private Integer code;\n private String msg;\n priv...
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yyh.xfs.common.domain.Result; import com.yyh.xfs.common.myEnum.ExceptionMsgEnum; import com.yyh.xfs.common.redis.constant.RedisConstant; import com.yyh.xfs.common.redis.utils.RedisCache; import com.yyh.xfs.common.redis.utils.RedisKey; import com.yyh.xfs.common.utils.CodeUtil; import com.yyh.xfs.common.utils.Md5Util; import com.yyh.xfs.common.utils.ResultUtil; import com.yyh.xfs.common.utils.TimeUtil; import com.yyh.xfs.common.web.exception.BusinessException; import com.yyh.xfs.common.web.exception.SystemException; import com.yyh.xfs.common.web.properties.JwtProperties; import com.yyh.xfs.common.web.utils.IPUtils; import com.yyh.xfs.common.web.utils.JWTUtil; import com.yyh.xfs.user.domain.UserAttentionDO; import com.yyh.xfs.user.domain.UserDO; import com.yyh.xfs.user.mapper.UserAttentionMapper; import com.yyh.xfs.user.mapper.UserFansMapper; import com.yyh.xfs.user.service.UserService; import com.yyh.xfs.user.mapper.UserMapper; import com.yyh.xfs.user.vo.RegisterInfoVO; import com.yyh.xfs.user.vo.UserTrtcVO; import com.yyh.xfs.user.vo.UserVO; import com.yyh.xfs.user.vo.ViewUserVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.servlet.http.HttpServletRequest; import java.sql.Date; import java.util.HashMap; import java.util.Map; import java.util.Objects;
14,190
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override public Result<UserVO> login(String phoneNumber, String password) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); // 利用MD5加密密码,并且通过手机号给密码加盐 // String md5Password = Md5Util.getMd5(phoneNumber + password); // TODO 暂时使用死密码,方便测试 String md5Password = "@yangyahao5036"; queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber).eq(UserDO::getPassword, md5Password); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PASSWORD_ERROR); } return generateUserVO(userDO); } /** * 第三方登录验证 * * @param type 登录类型 * @param code 第三方账号的唯一标识 * @return UserDO */ @Override public Result<UserVO> otherLogin(Integer type, String code) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(LOGIN_TYPE_MAP.get(type), code); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { return ResultUtil.errorPost("该第三方账号未绑定"); } return generateUserVO(userDO); } /** * 第三方登录并绑定手机号 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<UserVO> bindPhone(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_BIND_PHONE_CODE, registerInfoVO.getPhoneNumber()), registerInfoVO.getSmsCode()); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, registerInfoVO.getPhoneNumber()); UserDO userDO = this.getOne(queryWrapper); if (Objects.nonNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_EXIST); } // 注册 UserDO newUserDO = registerAccountByThird(registerInfoVO); return generateUserVO(newUserDO); } /** * 重置密码 * * @param phoneNumber 手机号 * @param password 密码 * @param smsCode 验证码 * @return Result<?> */ @Override public Result<?> resetPassword(String phoneNumber, String password, String smsCode) { boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_RESET_PASSWORD_PHONE_CODE, phoneNumber), smsCode); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_NOT_REGISTER); } // 利用MD5加密密码,并且通过手机号给密码加盐
package com.yyh.xfs.user.service.impl; /** * @author yyh * @date 2023-12-11 * 用户服务实现 */ @Service @Slf4j public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService { private static final String DEFAULT_NICKNAME_PREFIX = "小番薯用户"; private final JwtProperties jwtProperties; private final RedisCache redisCache; private final HttpServletRequest request; private final UserAttentionMapper userAttentionMapper; private final UserFansMapper userFansMapper; public UserServiceImpl(RedisCache redisCache, JwtProperties jwtProperties, HttpServletRequest request, UserAttentionMapper userAttentionMapper, UserFansMapper userFansMapper) { this.redisCache = redisCache; this.jwtProperties = jwtProperties; this.request = request; this.userAttentionMapper = userAttentionMapper; this.userFansMapper = userFansMapper; } /** * 登录类型和数据库字段的映射 */ private static final Map<Integer, SFunction<UserDO, String>> LOGIN_TYPE_MAP = new HashMap<>(); /** * 初始化 */ @PostConstruct public void postConstruct() { LOGIN_TYPE_MAP.put(1, UserDO::getWxOpenId); LOGIN_TYPE_MAP.put(2, UserDO::getQqOpenId); LOGIN_TYPE_MAP.put(3, UserDO::getFacebookOpenId); } /** * 手机号登录 * * @param phoneNumber 手机号 * @param password 密码 * @return UserDO */ @Override public Result<UserVO> login(String phoneNumber, String password) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); // 利用MD5加密密码,并且通过手机号给密码加盐 // String md5Password = Md5Util.getMd5(phoneNumber + password); // TODO 暂时使用死密码,方便测试 String md5Password = "@yangyahao5036"; queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber).eq(UserDO::getPassword, md5Password); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PASSWORD_ERROR); } return generateUserVO(userDO); } /** * 第三方登录验证 * * @param type 登录类型 * @param code 第三方账号的唯一标识 * @return UserDO */ @Override public Result<UserVO> otherLogin(Integer type, String code) { QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(LOGIN_TYPE_MAP.get(type), code); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { return ResultUtil.errorPost("该第三方账号未绑定"); } return generateUserVO(userDO); } /** * 第三方登录并绑定手机号 * * @param registerInfoVO 注册信息 * @return UserDO */ @Override public Result<UserVO> bindPhone(RegisterInfoVO registerInfoVO) { // 检验验证码是否正确 boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_BIND_PHONE_CODE, registerInfoVO.getPhoneNumber()), registerInfoVO.getSmsCode()); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, registerInfoVO.getPhoneNumber()); UserDO userDO = this.getOne(queryWrapper); if (Objects.nonNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_EXIST); } // 注册 UserDO newUserDO = registerAccountByThird(registerInfoVO); return generateUserVO(newUserDO); } /** * 重置密码 * * @param phoneNumber 手机号 * @param password 密码 * @param smsCode 验证码 * @return Result<?> */ @Override public Result<?> resetPassword(String phoneNumber, String password, String smsCode) { boolean b = checkSmsCode( RedisKey.build(RedisConstant.REDIS_KEY_SMS_RESET_PASSWORD_PHONE_CODE, phoneNumber), smsCode); if (!b) { throw new BusinessException(ExceptionMsgEnum.SMS_CODE_ERROR); } QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>(); queryWrapper.lambda().eq(UserDO::getPhoneNumber, phoneNumber); UserDO userDO = this.getOne(queryWrapper); if (Objects.isNull(userDO)) { throw new BusinessException(ExceptionMsgEnum.PHONE_NUMBER_NOT_REGISTER); } // 利用MD5加密密码,并且通过手机号给密码加盐
String md5 = Md5Util.getMd5(phoneNumber + password);
6
2023-12-15 08:13:42+00:00
16k
Blawuken/MicroG-Extended
play-services-core/src/main/java/org/microg/gms/auth/login/LoginActivity.java
[ { "identifier": "AuthConstants", "path": "play-services-basement/src/main/java/org/microg/gms/auth/AuthConstants.java", "snippet": "public class AuthConstants {\n public static final String DEFAULT_ACCOUNT = \"<<default account>>\";\n public static final String SCOPE_GET_ACCOUNT_ID = \"^^_account_...
import android.accounts.Account; import android.accounts.AccountManager; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.text.TextUtils; import android.util.Base64; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.webkit.CookieManager; import android.webkit.JavascriptInterface; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.RelativeLayout; import android.widget.TextView; import androidx.annotation.StringRes; import androidx.preference.PreferenceManager; import androidx.webkit.WebViewClientCompat; import com.google.android.gms.R; import org.json.JSONArray; import org.microg.gms.auth.AuthConstants; import org.microg.gms.auth.AuthManager; import org.microg.gms.auth.AuthRequest; import org.microg.gms.auth.AuthResponse; import org.microg.gms.checkin.CheckinManager; import org.microg.gms.checkin.LastCheckinInfo; import org.microg.gms.common.HttpFormClient; import org.microg.gms.common.Utils; import org.microg.gms.people.PeopleManager; import org.microg.gms.profile.Build; import org.microg.gms.profile.ProfileManager; import java.io.IOException; import java.security.MessageDigest; import java.util.Locale; import static android.accounts.AccountManager.PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE; import static android.accounts.AccountManager.VISIBILITY_USER_MANAGED_VISIBLE; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1; import static android.os.Build.VERSION_CODES.HONEYCOMB; import static android.os.Build.VERSION_CODES.LOLLIPOP; import static android.telephony.TelephonyManager.SIM_STATE_UNKNOWN; import static android.view.KeyEvent.KEYCODE_BACK; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; import static android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT; import static org.microg.gms.auth.AuthPrefs.isAuthVisible; import static org.microg.gms.checkin.CheckinPreferences.isSpoofingEnabled; import static org.microg.gms.checkin.CheckinPreferences.setSpoofingEnabled; import static org.microg.gms.common.Constants.GMS_PACKAGE_NAME; import static org.microg.gms.common.Constants.GMS_VERSION_CODE; import static org.microg.gms.common.Constants.GOOGLE_GMS_PACKAGE_NAME;
12,000
@SuppressLint("SetJavaScriptEnabled") private static void prepareWebViewSettings(Context context, WebSettings settings) { ProfileManager.ensureInitialized(context); settings.setUserAgentString(Build.INSTANCE.generateWebViewUserAgentString(settings.getUserAgentString()) + MAGIC_USER_AGENT); settings.setJavaScriptEnabled(true); settings.setSupportMultipleWindows(false); settings.setSaveFormData(false); settings.setAllowFileAccess(false); settings.setDatabaseEnabled(false); settings.setNeedInitialFocus(false); settings.setUseWideViewPort(false); settings.setSupportZoom(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); } private void start() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (LastCheckinInfo.read(this).getAndroidId() == 0) { new Thread(() -> { Runnable next; next = checkin(false) ? this::loadLoginPage : () -> showError(R.string.auth_general_error_desc); LoginActivity.this.runOnUiThread(next); }).start(); } else { loadLoginPage(); } } else { showError(R.string.no_network_error_desc); } } private void showError(int errorRes) { setTitle(R.string.sorry); findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) { new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service("ac2dm") .token(oAuthToken).isAccessToken() .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { Account account = new Account(response.email, accountType); if (accountManager.addAccountExplicitly(account, response.token, null)) { accountManager.setAuthToken(account, "SID", response.Sid); accountManager.setAuthToken(account, "LSID", response.LSid); accountManager.setUserData(account, "flags", "1"); accountManager.setUserData(account, "services", response.services); accountManager.setUserData(account, "oauthAccessToken", "1"); accountManager.setUserData(account, "firstName", response.firstName); accountManager.setUserData(account, "lastName", response.lastName); if (!TextUtils.isEmpty(response.accountId)) accountManager.setUserData(account, "GoogleUserId", response.accountId); retrieveGmsToken(account); setResult(RESULT_OK); } else { Log.w(TAG, "Account NOT created!"); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private void retrieveGmsToken(final Account account) {
/* * Copyright (C) 2013-2017 microG Project Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.microg.gms.auth.login; public class LoginActivity extends AssistantActivity { public static final String TMPL_NEW_ACCOUNT = "new_account"; public static final String EXTRA_TMPL = "tmpl"; public static final String EXTRA_EMAIL = "email"; public static final String EXTRA_TOKEN = "masterToken"; public static final int STATUS_BAR_DISABLE_BACK = 0x00400000; private static final String TAG = "GmsAuthLoginBrowser"; private static final String EMBEDDED_SETUP_URL = "https://accounts.google.com/EmbeddedSetup"; private static final String PROGRAMMATIC_AUTH_URL = "https://accounts.google.com/o/oauth2/programmatic_auth"; private static final String GOOGLE_SUITE_URL = "https://accounts.google.com/signin/continue"; private static final String MAGIC_USER_AGENT = " MinuteMaid"; private static final String COOKIE_OAUTH_TOKEN = "oauth_token"; private WebView webView; private String accountType; private AccountManager accountManager; private InputMethodManager inputMethodManager; private ViewGroup authContent; private int state = 0; @SuppressLint("AddJavascriptInterface") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); accountType = AuthConstants.DEFAULT_ACCOUNT_TYPE; accountManager = AccountManager.get(LoginActivity.this); inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); webView = createWebView(this); webView.addJavascriptInterface(new JsBridge(), "mm"); authContent = (ViewGroup) findViewById(R.id.auth_content); ((ViewGroup) findViewById(R.id.auth_root)).addView(webView); webView.setWebViewClient(new WebViewClientCompat() { @Override public void onPageFinished(WebView view, String url) { Log.d(TAG, "pageFinished: " + view.getUrl()); Uri uri = Uri.parse(view.getUrl()); // Begin login. // Only required if client code does not invoke showView() via JSBridge if ("identifier".equals(uri.getFragment()) || uri.getPath().endsWith("/identifier")) runOnUiThread(() -> webView.setVisibility(VISIBLE)); // Normal login. if ("close".equals(uri.getFragment())) closeWeb(false); // Google Suite login. if (url.startsWith(GOOGLE_SUITE_URL)) closeWeb(false); // IDK when this is called. if (url.startsWith(PROGRAMMATIC_AUTH_URL)) closeWeb(true); } }); if (getIntent().hasExtra(EXTRA_TOKEN)) { if (getIntent().hasExtra(EXTRA_EMAIL)) { AccountManager accountManager = AccountManager.get(this); Account account = new Account(getIntent().getStringExtra(EXTRA_EMAIL), accountType); accountManager.addAccountExplicitly(account, getIntent().getStringExtra(EXTRA_TOKEN), null); if (isAuthVisible(this) && SDK_INT >= 26) { accountManager.setAccountVisibility(account, PACKAGE_NAME_KEY_LEGACY_NOT_VISIBLE, VISIBILITY_USER_MANAGED_VISIBLE); } retrieveGmsToken(account); } else { retrieveRtToken(getIntent().getStringExtra(EXTRA_TOKEN)); } } else if (android.os.Build.VERSION.SDK_INT < 21) { init(); } else { setMessage(R.string.auth_before_connect); setSpoofButtonText(R.string.brand_spoof_button); setNextButtonText(R.string.auth_sign_in); } } @Override protected void onNextButtonClicked() { super.onNextButtonClicked(); state++; if (state == 1) { if (isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, false); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } @Override protected void onHuaweiButtonClicked() { super.onHuaweiButtonClicked(); state++; if (state == 1) { PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("pref_hide_launcher_icon", false).apply(); if (!isSpoofingEnabled(this)) { LastCheckinInfo.clear(this); setSpoofingEnabled(this, true); } init(); } else if (state == -1) { setResult(RESULT_CANCELED); finish(); } } private void init() { setTitle(R.string.just_a_sec); setSpoofButtonText(null); setNextButtonText(null); View loading = getLayoutInflater().inflate(R.layout.login_assistant_loading, authContent, false); authContent.removeAllViews(); authContent.addView(loading); setMessage(R.string.auth_connecting); CookieManager.getInstance().setAcceptCookie(true); if (SDK_INT >= LOLLIPOP) { CookieManager.getInstance().removeAllCookies(value -> start()); } else { //noinspection deprecation CookieManager.getInstance().removeAllCookie(); start(); } } private static WebView createWebView(Context context) { WebView webView = new WebView(context); if (SDK_INT < LOLLIPOP) { webView.setVisibility(VISIBLE); } else { webView.setVisibility(INVISIBLE); } webView.setLayoutParams(new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); webView.setBackgroundColor(Color.TRANSPARENT); prepareWebViewSettings(context, webView.getSettings()); return webView; } @SuppressLint("SetJavaScriptEnabled") private static void prepareWebViewSettings(Context context, WebSettings settings) { ProfileManager.ensureInitialized(context); settings.setUserAgentString(Build.INSTANCE.generateWebViewUserAgentString(settings.getUserAgentString()) + MAGIC_USER_AGENT); settings.setJavaScriptEnabled(true); settings.setSupportMultipleWindows(false); settings.setSaveFormData(false); settings.setAllowFileAccess(false); settings.setDatabaseEnabled(false); settings.setNeedInitialFocus(false); settings.setUseWideViewPort(false); settings.setSupportZoom(false); settings.setJavaScriptCanOpenWindowsAutomatically(false); } private void start() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { if (LastCheckinInfo.read(this).getAndroidId() == 0) { new Thread(() -> { Runnable next; next = checkin(false) ? this::loadLoginPage : () -> showError(R.string.auth_general_error_desc); LoginActivity.this.runOnUiThread(next); }).start(); } else { loadLoginPage(); } } else { showError(R.string.no_network_error_desc); } } private void showError(int errorRes) { setTitle(R.string.sorry); findViewById(R.id.progress_bar).setVisibility(View.INVISIBLE); setMessage(errorRes); } private void setMessage(@StringRes int res) { setMessage(getText(res)); } private void setMessage(CharSequence text) { ((TextView) findViewById(R.id.description_text)).setText(text); } private void loadLoginPage() { String tmpl = getIntent().hasExtra(EXTRA_TMPL) ? getIntent().getStringExtra(EXTRA_TMPL) : TMPL_NEW_ACCOUNT; webView.loadUrl(buildUrl(tmpl, Utils.getLocale(this))); } protected void runScript(String js) { runOnUiThread(() -> webView.loadUrl("javascript:" + js)); } private void closeWeb(boolean programmaticAuth) { setMessage(R.string.auth_finalize); runOnUiThread(() -> webView.setVisibility(INVISIBLE)); String cookies = CookieManager.getInstance().getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL); String[] temp = cookies.split(";"); for (String ar1 : temp) { if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) { String[] temp1 = ar1.split("="); retrieveRtToken(temp1[1]); return; } } showError(R.string.auth_general_error_desc); } private void retrieveRtToken(String oAuthToken) { new AuthRequest().fromContext(this) .appIsGms() .callerIsGms() .service("ac2dm") .token(oAuthToken).isAccessToken() .addAccount() .getAccountId() .getResponseAsync(new HttpFormClient.Callback<AuthResponse>() { @Override public void onResponse(AuthResponse response) { Account account = new Account(response.email, accountType); if (accountManager.addAccountExplicitly(account, response.token, null)) { accountManager.setAuthToken(account, "SID", response.Sid); accountManager.setAuthToken(account, "LSID", response.LSid); accountManager.setUserData(account, "flags", "1"); accountManager.setUserData(account, "services", response.services); accountManager.setUserData(account, "oauthAccessToken", "1"); accountManager.setUserData(account, "firstName", response.firstName); accountManager.setUserData(account, "lastName", response.lastName); if (!TextUtils.isEmpty(response.accountId)) accountManager.setUserData(account, "GoogleUserId", response.accountId); retrieveGmsToken(account); setResult(RESULT_OK); } else { Log.w(TAG, "Account NOT created!"); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } } @Override public void onException(Exception exception) { Log.w(TAG, "onException", exception); runOnUiThread(() -> { showError(R.string.auth_general_error_desc); setNextButtonText(android.R.string.ok); }); state = -2; } }); } private void retrieveGmsToken(final Account account) {
final AuthManager authManager = new AuthManager(this, account.name, GOOGLE_GMS_PACKAGE_NAME, "ac2dm");
1
2023-12-17 16:14:53+00:00
16k
Yolka5/FTC-Imu3
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.bosch.BNO055IMU; import com.qualcomm.hardware.lynx.LynxModule; 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.PIDFCoefficients; import com.qualcomm.robotcore.hardware.VoltageSensor; import com.qualcomm.robotcore.hardware.configuration.typecontainers.MotorConfigurationType; 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;
11,210
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(2, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 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); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private BNO055IMU imu; private VoltageSensor batteryVoltageSensor; public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_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(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS; imu.initialize(parameters); // TODO: If the hub containing the IMU you are using is mounted so that the "REV" logo does // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.) // // | +Z axis // | // | // | // _______|_____________ +Y axis // / |_____________/|__________ // / REV / EXPANSION // // / / HUB // // /_______/_____________// // |_______/_____________|/ // / // / +X axis // // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location // // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y. // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); 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);
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(2, 0, 0); public static PIDCoefficients HEADING_PID = new PIDCoefficients(1, 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); private TrajectoryFollower follower; private DcMotorEx leftFront, leftRear, rightRear, rightFront; private List<DcMotorEx> motors; private BNO055IMU imu; private VoltageSensor batteryVoltageSensor; public SampleMecanumDrive(HardwareMap hardwareMap) { super(kV, kA, kStatic, TRACK_WIDTH, TRACK_WIDTH, LATERAL_MULTIPLIER); follower = new HolonomicPIDVAFollower(TRANSLATIONAL_PID, TRANSLATIONAL_PID, HEADING_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(BNO055IMU.class, "imu"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.RADIANS; imu.initialize(parameters); // TODO: If the hub containing the IMU you are using is mounted so that the "REV" logo does // not face up, remap the IMU axes so that the z-axis points upward (normal to the floor.) // // | +Z axis // | // | // | // _______|_____________ +Y axis // / |_____________/|__________ // / REV / EXPANSION // // / / HUB // // /_______/_____________// // |_______/_____________|/ // / // / +X axis // // This diagram is derived from the axes in section 3.4 https://www.bosch-sensortec.com/media/boschsensortec/downloads/datasheets/bst-bno055-ds000.pdf // and the placement of the dot/orientation from https://docs.revrobotics.com/rev-control-system/control-system-overview/dimensions#imu-location // // For example, if +Y in this diagram faces downwards, you would use AxisDirection.NEG_Y. // BNO055IMUUtil.remapZAxis(imu, AxisDirection.NEG_Y); leftFront = hardwareMap.get(DcMotorEx.class, "leftFront"); rightRear = hardwareMap.get(DcMotorEx.class, "rightRear"); leftRear = hardwareMap.get(DcMotorEx.class, "leftRear"); rightFront = hardwareMap.get(DcMotorEx.class, "rightFront"); motors = Arrays.asList(leftFront, leftRear, rightRear, rightFront); 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) {
8
2023-12-15 16:57:19+00:00
16k
Frig00/Progetto-Ing-Software
src/main/java/it/unipv/po/aioobe/trenissimo/model/titolodiviaggio/CorsaSingola.java
[ { "identifier": "Acquisto", "path": "src/main/java/it/unipv/po/aioobe/trenissimo/model/acquisto/Acquisto.java", "snippet": "public abstract class Acquisto {\n\n private final LocalDateTime dataAcquisto;\n private double prezzoTot;\n private final IPuntiFedeltaStrategy puntiFedeltaStrategy;\n\n ...
import it.unipv.po.aioobe.trenissimo.model.acquisto.Acquisto; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.StoricoAcquistiEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.entity.TitoloViaggioEntity; import it.unipv.po.aioobe.trenissimo.model.persistence.service.StoricoAcquistiService; import it.unipv.po.aioobe.trenissimo.model.persistence.service.TitoloViaggioService; import it.unipv.po.aioobe.trenissimo.model.titolodiviaggio.enumeration.TipoTitoloViaggio; import it.unipv.po.aioobe.trenissimo.model.user.Account; import it.unipv.po.aioobe.trenissimo.model.viaggio.Viaggio; import org.jetbrains.annotations.NotNull;
11,097
package it.unipv.po.aioobe.trenissimo.model.titolodiviaggio; /** * Classe che modellizza un biglietto corsa singola. * * @author ArrayIndexOutOfBoundsException */ public class CorsaSingola extends Acquisto { private final TipoTitoloViaggio tipo; private double prezzo; private final String id; private final Viaggio viaggio; /** * Costruttore utilizzato per creare un biglietto corsa singola. * * @param tipo * @param viaggio */ public CorsaSingola(TipoTitoloViaggio tipo, @NotNull Viaggio viaggio) { super(); this.tipo = tipo; this.id = "CS" + System.nanoTime(); this.viaggio = viaggio; this.prezzo = viaggio.getPrezzoTot(); } public Viaggio getViaggio() { return viaggio; } public TipoTitoloViaggio getTipo() { return this.tipo; } @Override public double getPrezzo() { return this.prezzo; } @Override public void setPrezzo(double prezzo) { this.prezzo = prezzo; } @Override public String getId() { return this.id; } /** * Metodo che implementa il metodo astratto della superclasse, Viene richiamato quando si vuole fare un pagamento * di un biglietto corsa singola. <br> * Il metodo salva nel database il titolo di viaggio, e, se si è loggati, verrà salvato anche nello storico acquisti. * * @return "true" se il pagamento è andato a buon fine. "false" altrimenti. */ @Override public boolean pagare() { try { StoricoAcquistiService storicoAcquistiService = new StoricoAcquistiService(); StoricoAcquistiEntity storicoAcquistiEntity = new StoricoAcquistiEntity(); TitoloViaggioService titoloViaggioService = new TitoloViaggioService(); TitoloViaggioEntity titoloViaggioEntity = new TitoloViaggioEntity(); titoloViaggioService.persist(titoloViaggioEntity.toTitoloViaggioEntity(this)); storicoAcquistiEntity = storicoAcquistiEntity.toStoricoAcquistiEntity(this);
package it.unipv.po.aioobe.trenissimo.model.titolodiviaggio; /** * Classe che modellizza un biglietto corsa singola. * * @author ArrayIndexOutOfBoundsException */ public class CorsaSingola extends Acquisto { private final TipoTitoloViaggio tipo; private double prezzo; private final String id; private final Viaggio viaggio; /** * Costruttore utilizzato per creare un biglietto corsa singola. * * @param tipo * @param viaggio */ public CorsaSingola(TipoTitoloViaggio tipo, @NotNull Viaggio viaggio) { super(); this.tipo = tipo; this.id = "CS" + System.nanoTime(); this.viaggio = viaggio; this.prezzo = viaggio.getPrezzoTot(); } public Viaggio getViaggio() { return viaggio; } public TipoTitoloViaggio getTipo() { return this.tipo; } @Override public double getPrezzo() { return this.prezzo; } @Override public void setPrezzo(double prezzo) { this.prezzo = prezzo; } @Override public String getId() { return this.id; } /** * Metodo che implementa il metodo astratto della superclasse, Viene richiamato quando si vuole fare un pagamento * di un biglietto corsa singola. <br> * Il metodo salva nel database il titolo di viaggio, e, se si è loggati, verrà salvato anche nello storico acquisti. * * @return "true" se il pagamento è andato a buon fine. "false" altrimenti. */ @Override public boolean pagare() { try { StoricoAcquistiService storicoAcquistiService = new StoricoAcquistiService(); StoricoAcquistiEntity storicoAcquistiEntity = new StoricoAcquistiEntity(); TitoloViaggioService titoloViaggioService = new TitoloViaggioService(); TitoloViaggioEntity titoloViaggioEntity = new TitoloViaggioEntity(); titoloViaggioService.persist(titoloViaggioEntity.toTitoloViaggioEntity(this)); storicoAcquistiEntity = storicoAcquistiEntity.toStoricoAcquistiEntity(this);
if (Account.getLoggedIn())
6
2023-12-21 10:41:11+00:00
16k
pan2013e/ppt4j
framework/src/main/java/ppt4j/Main.java
[ { "identifier": "PatchAnalyzer", "path": "framework/src/main/java/ppt4j/analysis/patch/PatchAnalyzer.java", "snippet": "@Log4j\npublic class PatchAnalyzer {\n\n @Property(\"ppt4j.analysis.patch.presence_threshold\")\n private static double PATCH_PRESENCE_THRESHOLD;\n\n @Property(\"ppt4j.feature...
import ppt4j.analysis.patch.PatchAnalyzer; import ppt4j.database.Vulnerability; import ppt4j.factory.DatabaseFactory; import ppt4j.util.ExecDriver; import ppt4j.util.PropertyUtils; import ppt4j.util.ResourceUtils; import ppt4j.util.StringUtils; import lombok.AllArgsConstructor; import org.apache.commons.cli.*; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays;
10,811
package ppt4j; public final class Main { private static final String VM_OPTIONS = "-javaagent:lib/aspectjweaver-1.9.19.jar " + "-Xss2m -XX:CompilerThreadStackSize=2048 -XX:VMThreadStackSize=2048 " + "--add-opens java.base/java.lang=ALL-UNNAMED " + "--add-opens java.base/java.lang.reflect=ALL-UNNAMED"; private static final Options options = new Options(); private static final HelpFormatter formatter = new HelpFormatter(); private static final String cmdLineSyntax = "java -cp [...] ppt4j.Main "; @AllArgsConstructor public enum Command { ANALYZE("analyze"); public final String name; } private static String cmdLineSyntax() { return cmdLineSyntax + "[<options>] <command> <args>\n" + """ Commands: analyze <db-id> <gt-type> Analyze a binary for a vulnerability in the dataset Options: """; } private static String[] init(String[] args) { options.addOption("config", "config", true, "Set path to a custom *.properties file with ISO-8859-1 encoding"); options.addOption("h", "help", false, "Print help message and exit"); Option configs = Option.builder("X") .hasArgs() .valueSeparator('=') .desc("Add or override existing properties, e.g. -Xppt4j.database.root=~/database") .build(); options.addOption(configs); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args, true); if (cmd.hasOption("h")) { formatter.printHelp(cmdLineSyntax(), options); System.exit(0); } if (cmd.hasOption("config")) { PropertyUtils.load( new FileInputStream(cmd.getOptionValue("config"))); } else {
package ppt4j; public final class Main { private static final String VM_OPTIONS = "-javaagent:lib/aspectjweaver-1.9.19.jar " + "-Xss2m -XX:CompilerThreadStackSize=2048 -XX:VMThreadStackSize=2048 " + "--add-opens java.base/java.lang=ALL-UNNAMED " + "--add-opens java.base/java.lang.reflect=ALL-UNNAMED"; private static final Options options = new Options(); private static final HelpFormatter formatter = new HelpFormatter(); private static final String cmdLineSyntax = "java -cp [...] ppt4j.Main "; @AllArgsConstructor public enum Command { ANALYZE("analyze"); public final String name; } private static String cmdLineSyntax() { return cmdLineSyntax + "[<options>] <command> <args>\n" + """ Commands: analyze <db-id> <gt-type> Analyze a binary for a vulnerability in the dataset Options: """; } private static String[] init(String[] args) { options.addOption("config", "config", true, "Set path to a custom *.properties file with ISO-8859-1 encoding"); options.addOption("h", "help", false, "Print help message and exit"); Option configs = Option.builder("X") .hasArgs() .valueSeparator('=') .desc("Add or override existing properties, e.g. -Xppt4j.database.root=~/database") .build(); options.addOption(configs); CommandLineParser parser = new DefaultParser(); try { CommandLine cmd = parser.parse(options, args, true); if (cmd.hasOption("h")) { formatter.printHelp(cmdLineSyntax(), options); System.exit(0); } if (cmd.hasOption("config")) { PropertyUtils.load( new FileInputStream(cmd.getOptionValue("config"))); } else {
PropertyUtils.load(ResourceUtils.readProperties());
5
2023-12-14 15:33:50+00:00
16k
f1den/MrCrayfishGunMod
src/main/java/com/mrcrayfish/guns/client/GunRenderType.java
[ { "identifier": "Reference", "path": "src/main/java/com/mrcrayfish/guns/Reference.java", "snippet": "public class Reference\n{\n\tpublic static final String MOD_ID = \"cgm\";\n}" }, { "identifier": "GunRenderingHandler", "path": "src/main/java/com/mrcrayfish/guns/client/handler/GunRenderingH...
import com.mojang.blaze3d.vertex.DefaultVertexFormat; import com.mojang.blaze3d.vertex.VertexFormat; import com.mrcrayfish.guns.Reference; import com.mrcrayfish.guns.client.handler.GunRenderingHandler; import com.mrcrayfish.guns.client.render.ScreenTextureState; import net.minecraft.client.renderer.RenderStateShard; import net.minecraft.client.renderer.RenderType;
11,949
package com.mrcrayfish.guns.client; /** * Author: MrCrayfish */ public final class GunRenderType extends RenderType { private static final RenderType BULLET_TRAIL = RenderType.create(Reference.MOD_ID + ":projectile_trail", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, VertexFormat.Mode.QUADS, 256, true, true, RenderType.CompositeState.builder().setShaderState(RenderStateShard.POSITION_COLOR_LIGHTMAP_SHADER).setCullState(NO_CULL).setTransparencyState(TRANSLUCENT_TRANSPARENCY).createCompositeState(false)); @Deprecated(since = "1.3.0", forRemoval = true)
package com.mrcrayfish.guns.client; /** * Author: MrCrayfish */ public final class GunRenderType extends RenderType { private static final RenderType BULLET_TRAIL = RenderType.create(Reference.MOD_ID + ":projectile_trail", DefaultVertexFormat.POSITION_COLOR_LIGHTMAP, VertexFormat.Mode.QUADS, 256, true, true, RenderType.CompositeState.builder().setShaderState(RenderStateShard.POSITION_COLOR_LIGHTMAP_SHADER).setCullState(NO_CULL).setTransparencyState(TRANSLUCENT_TRANSPARENCY).createCompositeState(false)); @Deprecated(since = "1.3.0", forRemoval = true)
private static final RenderType SCREEN = RenderType.create(Reference.MOD_ID + ":screen_texture", DefaultVertexFormat.NEW_ENTITY, VertexFormat.Mode.QUADS, 256, true, false, RenderType.CompositeState.builder().setShaderState(RenderStateShard.NEW_ENTITY_SHADER).setTexturingState(ScreenTextureState.instance()).setLightmapState(LIGHTMAP).setOverlayState(OVERLAY).createCompositeState(false));
2
2023-12-18 15:04:35+00:00
16k
thebatmanfuture/fofa_search
src/main/java/org/fofaviewer/controllers/MainController.java
[ { "identifier": "SaveOptionCallback", "path": "src/main/java/org/fofaviewer/callback/SaveOptionCallback.java", "snippet": "public interface SaveOptionCallback{\n default void setProjectName(String name){}\n default String getProjectName(){\n return null;\n }\n}" }, { "identifier"...
import java.io.BufferedReader; import java.io.File; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.control.Alert; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.stage.FileChooser; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.HttpsURLConnection; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.ResourceBundle; import java.util.Set; import javafx.scene.control.Alert; import javafx.scene.control.Tab; import javafx.scene.control.TableView; import javafx.scene.layout.BorderPane; import javafx.stage.DirectoryChooser; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ProgressBar; import javafx.scene.control.Alert.AlertType; import javafx.scene.layout.Region; import javafx.stage.FileChooser; import javafx.stage.StageStyle; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.fxml.FXML; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.text.Font; import org.controlsfx.control.StatusBar; import org.controlsfx.dialog.CommandLinksDialog; import org.controlsfx.dialog.ProgressDialog; import org.fofaviewer.bean.*; import org.fofaviewer.callback.SaveOptionCallback; import org.fofaviewer.controls.*; import org.fofaviewer.main.FofaConfig; import org.fofaviewer.callback.MainControllerCallback; import org.fofaviewer.request.Request; import org.fofaviewer.callback.RequestCallback; import org.fofaviewer.utils.DataUtil; import org.fofaviewer.utils.RequestUtil; import org.controlsfx.control.textfield.TextFields; import org.fofaviewer.utils.ResourceBundleUtil; import java.awt.*; import java.io.*; import java.math.BigInteger; import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import org.fofaviewer.utils.SQLiteUtils; import org.tinylog.Logger;
13,061
try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) { int fileIndex = 1; int lineCount = 0; String line; BufferedWriter writer = null; while ((line = reader.readLine()) != null) { if (lineCount % 400 == 0) { if (writer != null) { writer.close(); } String fileName = outputFolderPath + File.separator + (fileIndex * 400 - 399) + "-" + (fileIndex * 400) + ".csv"; writer = new BufferedWriter(new FileWriter(fileName)); fileIndex++; } String modifiedLine = line + "," + getCurrentDate(); writer.write(modifiedLine); writer.newLine(); lineCount++; } if (writer != null) { writer.close(); } showAlert(Alert.AlertType.INFORMATION, "操作完成", "已转换成功"); } catch (IOException e) { showAlert(Alert.AlertType.ERROR, "错误", "无法读取文件或创建输出文件"); } } } private String createOutputFolder() { java.util.Date date = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); String folderName = sdf.format(date) + "-awvs"; String folderPath = "." + File.separator + folderName; File folder = new File(folderPath); if (!folder.exists()) { boolean created = folder.mkdirs(); if (!created) { showAlert(Alert.AlertType.ERROR, "错误", "无法创建输出文件夹"); } } return folderPath; } private String getCurrentDate() { java.util.Date date = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); } private void showAlert(Alert.AlertType alertType, String title, String message) { Alert alert = new Alert(alertType); alert.setTitle(title); alert.setHeaderText(null); alert.setContentText(message); alert.showAndWait(); } /** * 打开项目 */ @FXML private void openProject(){ if((Boolean) projectInfo.get("status")){ Alert dialog = DataUtil.showAlert(Alert.AlertType.CONFIRMATION, null, resourceBundle.getString("OPEN_NEW_PROCESS")); dialog.setOnCloseRequest(event -> { ButtonType btn = dialog.getResult(); if(btn.equals(ButtonType.OK)){//当前已打开一个项目点是 FileChooser chooser = new FileChooser(); chooser.setTitle(resourceBundle.getString("FILE_CHOOSER_TITLE")); File file = chooser.showOpenDialog(rootLayout.getScene().getWindow()); if(file != null){ String os = System.getProperty("os.name").toLowerCase(); String javaPath = System.getProperty("java.home") + System.getProperty("file.separator") + "bin" + System.getProperty("file.separator"); try { if(os.contains("windows")){ String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile().substring(1); javaPath += "java.exe"; Runtime.getRuntime().exec(new String[]{"cmd", "/c", javaPath, "-jar", jarPath, "-f", file.getAbsolutePath()}); }else{ String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile(); System.out.println(jarPath); javaPath += "java"; Runtime.getRuntime().exec(new String[]{"sh", "-c", "\"" + javaPath, "-jar", jarPath, "-f", file.getAbsolutePath(), "\""}); } }catch (IOException e) { Logger.error(e); } } }else{ //当前已打开一个项目点否 } }); dialog.showAndWait(); }else{ FileChooser chooser = new FileChooser(); chooser.setTitle(resourceBundle.getString("FILE_CHOOSER_TITLE")); File file = chooser.showOpenDialog(rootLayout.getScene().getWindow()); if(file != null){ openFile(file.getAbsolutePath()); } } } /** * 保存项目 */ @FXML private void saveProject(){ if(this.tabPane.getTabs().size() == 1){ DataUtil.showAlert(Alert.AlertType.WARNING, null, resourceBundle.getString("SAVE_PROJECT_ERROR")).showAndWait(); }else{
package org.fofaviewer.controllers; public class MainController { private Map<String, Object> projectInfo; private AutoHintTextField decoratedField; private static final RequestUtil helper = RequestUtil.getInstance(); private FofaConfig client; private final ResourceBundle resourceBundle; private final HashMap<CheckBox, String> keyMap = new HashMap<>(); @FXML private Menu help; @FXML private Menu project; @FXML private Menu urlFunction; @FXML private Menu urlCombination; @FXML private Menu awvs; @FXML private Menu urlslice; @FXML private MenuItem importFile; @FXML private MenuItem urlslicein; @FXML private Menu no_repeat; @FXML private MenuItem no_repeat_id; @FXML private MenuItem urlCsettings; @FXML private MenuItem awvsTran; // @FXML // private MenuItem startOn; @FXML private Menu rule; @FXML private Menu config; // @FXML // private MenuItem query_api; // @FXML // private MenuItem ; // @FXML // private MenuItem exportRule; @FXML private MenuItem about; @FXML private MenuItem setConfig; @FXML private MenuItem openProject; @FXML private MenuItem saveProject; @FXML private Button exportDataBtn; @FXML private Button exportAll; @FXML private Button searchBtn; @FXML private Label queryString; @FXML private VBox rootLayout; @FXML private TextField queryTF; // @FXML // private CheckBox checkHoneyPot; // @FXML // private CheckBox withFid; // @FXML // private CheckBox hostOnly; // 仅host @FXML private CheckBox isAll; // @FXML // private CheckBox title; // @FXML // private CheckBox cert; @FXML private CloseableTabPane tabPane; public MainController(){ this.resourceBundle = ResourceBundleUtil.getResource(); } /** * 初始化 */ @FXML private void initialize() { SQLiteUtils.init(); // keyMap.put(withFid, "fid"); // keyMap.put(hostOnly, "123host"); // keyMap.put(cert, "cert"); // keyMap.put(title, "title"); projectInfo = new HashMap<>(); projectInfo.put("status", Boolean.FALSE); projectInfo.put("name", ""); // title.setText(resourceBundle.getString("TITLE")); // cert.setText(resourceBundle.getString("CERT")); about.setText(resourceBundle.getString("ABOUT")); help.setText(resourceBundle.getString("HELP")); project.setText(resourceBundle.getString("PROJECT")); urlFunction.setText(resourceBundle.getString("URLFUNCTION")); no_repeat_id.setText(resourceBundle.getString("no_repeat_id")); // @FXML // private Menu urlFunction; // // @FXML // private Menu importTxt; importFile.setText(resourceBundle.getString("IMPORTFILE")); // startOn.setText(resourceBundle.getString("STARTFILE")); //urlCombination urlCombination.setText(resourceBundle.getString("URLCOMBINATION")); urlCsettings.setText(resourceBundle.getString("URLCSETTINGS")); awvsTran.setText(resourceBundle.getString("AWVSTRAN")); urlslicein.setText(resourceBundle.getString("urlslicein")); awvs.setText(resourceBundle.getString("AWVS")); urlslice.setText(resourceBundle.getString("urlslice")); no_repeat.setText(resourceBundle.getString("no_repeat")); config.setText(resourceBundle.getString("CONFIG_PANEL")); // rule.setText(resourceBundle.getString("RULE")); // query_api.setText(resourceBundle.getString("QUERY_API")); setConfig.setText(resourceBundle.getString("SET_CONFIG")); // createRule.setText(resourceBundle.getString("CREATE_RULE")); // .setText(resourceBundle.getString("EXPORT_RULE")); saveProject.setText(resourceBundle.getString("SAVE_PROJECT")); openProject.setText(resourceBundle.getString("OPEN_PROJECT")); searchBtn.setText(resourceBundle.getString("SEARCH")); exportAll.setText(resourceBundle.getString("EXPORT_ALL")); /* * * * * */ exportDataBtn.setText(resourceBundle.getString("EXPORT_BUTTON")); queryString.setText(resourceBundle.getString("QUERY_CONTENT")); // checkHoneyPot.setText(resourceBundle.getString("REMOVE_HONEYPOTS")); // withFid.setText(resourceBundle.getString("WITH_FID")); // hostOnly.setText(resourceBundle.getString("HOST_ONLY")); isAll.setText(resourceBundle.getString("IS_ALL")); decoratedField = new AutoHintTextField(queryTF); this.client = DataUtil.loadConfigure(); this.tabPane.setCallback(new MainControllerCallback() { @Override public void queryCall(List<String> strList) { query(strList); } }); //初始化起始页tab Tab tab = this.tabPane.getTab(resourceBundle.getString("HOMEPAGE")); Button queryCert = new Button(resourceBundle.getString("QUERY_BUTTON")); Button queryFavicon = new Button(resourceBundle.getString(("QUERY_BUTTON"))); Label label = new Label(resourceBundle.getString("CERT_LABEL")); Label faviconLabel = new Label(resourceBundle.getString("FAVICON_LABEL")); TextField tf = TextFields.createClearableTextField(); TextField favionTF = TextFields.createClearableTextField(); // 设置从文件导入favicon favionTF.setOnDragOver(event -> { if (event.getGestureSource() != favionTF){ event.acceptTransferModes(TransferMode.ANY); } }); favionTF.setOnDragDropped(event -> { Dragboard dragboard = event.getDragboard(); if (dragboard.hasFiles()){ try { File file = dragboard.getFiles().get(0); if (file != null && file.exists()) { favionTF.setText(file.getAbsolutePath()); } }catch (Exception e){ Logger.error(e.toString()); } } }); // Image image = new Image("api_doc_en.png"); ImageView view = new ImageView(new Image(Locale.getDefault().getLanguage().equals(Locale.CHINESE.getLanguage()) ? "/images/ddddddddd.png" : "/images/api_doc_en.png")); ScrollPane scrollPane = new ScrollPane(); scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER); scrollPane.setContent(view); view.setFitHeight(750D); view.setFitWidth(750D); scrollPane.setPrefWidth(760); tf.setPromptText(resourceBundle.getString("CERT_HINT")); favionTF.setPromptText(resourceBundle.getString("FAVICON_HINT")); tf.setPrefWidth(400); favionTF.setPrefWidth(400); label.setFont(Font.font(14)); faviconLabel.setFont(Font.font(14)); queryCert.setOnAction(event -> { String txt = tf.getText().trim(); if(!txt.isEmpty()){ String serialnumber = txt.replaceAll(" ", ""); BigInteger i = new BigInteger(serialnumber, 16); query(new ArrayList<String>(){{add("cert=\"" + i + "\"");}}); } }); queryFavicon.setOnAction(event -> { String text = favionTF.getText().trim(); if(!text.isEmpty()){ if(!text.startsWith("http")){ // 文件导入 String suffix = text.substring(text.lastIndexOf(".")+1).toLowerCase(); try { byte[] content = Files.readAllBytes(Paths.get(text)); switch (suffix){ case "jpg": case "png": case "ico": case "svg": String encode = java.util.Base64.getMimeEncoder().encodeToString(content); query(new ArrayList<String>(){{add("icon_hash=\"" + helper.getIconHash(encode) + "\"");}}); break; default: DataUtil.showAlert(Alert.AlertType.ERROR, null, resourceBundle.getString("ERROR_FILE")).showAndWait(); break; } } catch (IOException e) { DataUtil.showAlert(Alert.AlertType.ERROR, null, resourceBundle.getString("ERROR_FILE")).showAndWait(); Logger.error(e); } }else { // url导入 HashMap<String,String> res = helper.getImageFavicon(text); if(res != null){ if(res.get("code").equals("error")){ DataUtil.showAlert(Alert.AlertType.ERROR, null, res.get("msg")).showAndWait();return; } query(new ArrayList<String>(){{add(res.get("msg"));}}); } } } }); VBox vb = new VBox(); HBox hb = new HBox(); HBox faviconBox = new HBox(); HBox imageBox = new HBox(); vb.setSpacing(10); imageBox.getChildren().add(scrollPane); hb.getChildren().addAll(label, tf, queryCert); label.setPadding(new Insets(3)); faviconLabel.setPadding(new Insets(3,5,3,3)); hb.setPadding(new Insets(10)); hb.setSpacing(15); faviconBox.setSpacing(15); // 设置控件间距 hb.setAlignment(Pos.TOP_CENTER); faviconBox.setAlignment(Pos.TOP_CENTER); faviconBox.setPadding(new Insets(5,0,5,0)); imageBox.setAlignment(Pos.TOP_CENTER); imageBox.setPadding(new Insets(5,0,10,0)); faviconBox.getChildren().addAll(faviconLabel, favionTF, queryFavicon); vb.getChildren().addAll(hb, faviconBox, imageBox); tab.setContent(vb); } /** * 通过命令行参数传递要打开的项目文件 */ public void openFile(String fileName){ try { FileInputStream inputStream = new FileInputStream(fileName); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); List<String> list = new ArrayList<>(); String str; while((str = bufferedReader.readLine()) != null) { if(!str.equals("")){ //打印输出cccccccccccccccccccccccc // System.out.println(str); list.add(str); } } query(list); } catch (IOException e) { Logger.error(e); } } @FXML private void getQueryAPI(){ // Tab tab = this.tabPane.getCurrentTab(); // if(tab.getText().equals(resourceBundle.getString("HOMEPAGE"))){ // DataUtil.showAlert(Alert.AlertType.INFORMATION, null, resourceBundle.getString("COPY_QUERY_URL_FAILED")).showAndWait(); // }else{ // Clipboard clipboard = Clipboard.getSystemClipboard(); // ClipboardContent content = new ClipboardContent(); // content.putString(this.tabPane.getCurrentQuery(tab)); // clipboard.setContent(content); // DataUtil.showAlert(Alert.AlertType.INFORMATION, null, resourceBundle.getString("COPY_QUERY_URL_SUCCESS")).showAndWait(); // } } /** * 查询按钮点击事件,与fxml中命名绑定 */ @FXML private void queryAction(){ if(queryTF.getText() != null){ query(new ArrayList<String>(){{add(queryTF.getText());}}); } } /** * 关于 按钮 */ @FXML private void showAbout(){ List<CommandLinksDialog.CommandLinksButtonType> clb = Arrays.asList( new CommandLinksDialog.CommandLinksButtonType("https://thebatmanfuture.github.io", resourceBundle.getString("ABOUT_HINT1"), true), new CommandLinksDialog.CommandLinksButtonType("https://thebatmanfuture.github.io/gitbook/", resourceBundle.getString("ABOUT_HINT2"), true) ); CommandLinksDialog dialog = new CommandLinksDialog(clb); dialog.setOnCloseRequest(e -> { ButtonType result = dialog.getResult(); if(result.getButtonData() != ButtonBar.ButtonData.CANCEL_CLOSE){ URI uri = URI.create(result.getText()); Desktop dp = Desktop.getDesktop(); if (dp.isSupported(Desktop.Action.BROWSE)) { try { dp.browse(uri); } catch (IOException ex) { Logger.error(ex); } } } }); dialog.setTitle("fofa_search"); dialog.setContentText("塔菲"); dialog.showAndWait(); } /** * 配置设置 */ @FXML private void setConfig(){ SetConfiDialog dialog = new SetConfiDialog(resourceBundle.getString("CONFIG_PANEL")); dialog.showAndWait(); } @FXML private void no_repeat_func() { FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text Files", "*.txt")); File selectedFile = fileChooser.showOpenDialog(null); String fileName = selectedFile.getPath(); // System.out.println(fileName); try { // 读取原始文件 BufferedReader reader = new BufferedReader(new FileReader(fileName)); Set<String> uniqueLines = new HashSet<>(); String line; // 去重处理 while ((line = reader.readLine()) != null) { uniqueLines.add(line); } reader.close(); // 生成去重后的文件名 String outputFileName = fileName.replace(".txt", "[已去重].txt"); // 写入去重后的内容到新文件 BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName)); for (String uniqueLine : uniqueLines) { writer.write(uniqueLine); writer.newLine(); } writer.close(); // System.out.println("去重成功"); showAlert(Alert.AlertType.INFORMATION, "操作提示", "去重成功"); } catch (IOException e) { e.printStackTrace(); } } @FXML private void urlSettings(){ SetUrlCombination combination1 = new SetUrlCombination(resourceBundle.getString("URLCSETTINGS")); combination1.showAndWait(); } /** * url存活判断 */ @FXML private void urlLive(){ } @FXML private void urlslicefunc(){ FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text Files", "*.txt")); File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { String outputFolderPath = createOutputFolder(); try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) { int fileIndex = 1; int lineCount = 0; String line; BufferedWriter writer = null; while ((line = reader.readLine()) != null) { if (lineCount % 100 == 0) { if (writer != null) { writer.close(); } String fileName = outputFolderPath + File.separator + (fileIndex * 100 - 99) + "-" + (fileIndex * 100) + ".txt"; writer = new BufferedWriter(new FileWriter(fileName)); fileIndex++; } writer.write(line); writer.newLine(); lineCount++; } if (writer != null) { writer.close(); } showAlert(Alert.AlertType.INFORMATION, "操作完成", "已转换成功"); } catch (IOException e) { showAlert(Alert.AlertType.ERROR, "错误", "无法读取文件或创建输出文件"); } } } @FXML private void awvsTrans(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Text Files", "*.txt")); File selectedFile = fileChooser.showOpenDialog(null); if (selectedFile != null) { String outputFolderPath = createOutputFolder(); try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) { int fileIndex = 1; int lineCount = 0; String line; BufferedWriter writer = null; while ((line = reader.readLine()) != null) { if (lineCount % 400 == 0) { if (writer != null) { writer.close(); } String fileName = outputFolderPath + File.separator + (fileIndex * 400 - 399) + "-" + (fileIndex * 400) + ".csv"; writer = new BufferedWriter(new FileWriter(fileName)); fileIndex++; } String modifiedLine = line + "," + getCurrentDate(); writer.write(modifiedLine); writer.newLine(); lineCount++; } if (writer != null) { writer.close(); } showAlert(Alert.AlertType.INFORMATION, "操作完成", "已转换成功"); } catch (IOException e) { showAlert(Alert.AlertType.ERROR, "错误", "无法读取文件或创建输出文件"); } } } private String createOutputFolder() { java.util.Date date = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); String folderName = sdf.format(date) + "-awvs"; String folderPath = "." + File.separator + folderName; File folder = new File(folderPath); if (!folder.exists()) { boolean created = folder.mkdirs(); if (!created) { showAlert(Alert.AlertType.ERROR, "错误", "无法创建输出文件夹"); } } return folderPath; } private String getCurrentDate() { java.util.Date date = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd"); return sdf.format(date); } private void showAlert(Alert.AlertType alertType, String title, String message) { Alert alert = new Alert(alertType); alert.setTitle(title); alert.setHeaderText(null); alert.setContentText(message); alert.showAndWait(); } /** * 打开项目 */ @FXML private void openProject(){ if((Boolean) projectInfo.get("status")){ Alert dialog = DataUtil.showAlert(Alert.AlertType.CONFIRMATION, null, resourceBundle.getString("OPEN_NEW_PROCESS")); dialog.setOnCloseRequest(event -> { ButtonType btn = dialog.getResult(); if(btn.equals(ButtonType.OK)){//当前已打开一个项目点是 FileChooser chooser = new FileChooser(); chooser.setTitle(resourceBundle.getString("FILE_CHOOSER_TITLE")); File file = chooser.showOpenDialog(rootLayout.getScene().getWindow()); if(file != null){ String os = System.getProperty("os.name").toLowerCase(); String javaPath = System.getProperty("java.home") + System.getProperty("file.separator") + "bin" + System.getProperty("file.separator"); try { if(os.contains("windows")){ String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile().substring(1); javaPath += "java.exe"; Runtime.getRuntime().exec(new String[]{"cmd", "/c", javaPath, "-jar", jarPath, "-f", file.getAbsolutePath()}); }else{ String jarPath = this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile(); System.out.println(jarPath); javaPath += "java"; Runtime.getRuntime().exec(new String[]{"sh", "-c", "\"" + javaPath, "-jar", jarPath, "-f", file.getAbsolutePath(), "\""}); } }catch (IOException e) { Logger.error(e); } } }else{ //当前已打开一个项目点否 } }); dialog.showAndWait(); }else{ FileChooser chooser = new FileChooser(); chooser.setTitle(resourceBundle.getString("FILE_CHOOSER_TITLE")); File file = chooser.showOpenDialog(rootLayout.getScene().getWindow()); if(file != null){ openFile(file.getAbsolutePath()); } } } /** * 保存项目 */ @FXML private void saveProject(){ if(this.tabPane.getTabs().size() == 1){ DataUtil.showAlert(Alert.AlertType.WARNING, null, resourceBundle.getString("SAVE_PROJECT_ERROR")).showAndWait(); }else{
SaveOptionCallback callback = new SaveOptionCallback() {
0
2023-10-25 11:13:47+00:00
16k
Changbaiqi/yatori
yatori-console/src/main/java/com/cbq/yatori/console/run/Launch.java
[ { "identifier": "LoginResponseRequest", "path": "yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/loginresponse/LoginResponseRequest.java", "snippet": "@lombok.Data\npublic class LoginResponseRequest {\n @JsonProperty(\"code\")\n private long code;\n @JsonProperty(\"data\")\n...
import com.cbq.yatori.core.action.canghui.entity.loginresponse.LoginResponseRequest; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourse; import com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.MyCourseData; import com.cbq.yatori.core.action.enaea.entity.LoginAblesky; import com.cbq.yatori.core.action.enaea.entity.underwayproject.ResultList; import com.cbq.yatori.core.action.enaea.entity.underwayproject.UnderwayProjectRquest; import com.cbq.yatori.core.action.yinghua.CourseAction; import com.cbq.yatori.core.action.yinghua.CourseStudyAction; import com.cbq.yatori.core.action.yinghua.LoginAction; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseInform; import com.cbq.yatori.core.action.yinghua.entity.allcourse.CourseRequest; import com.cbq.yatori.core.entity.*; import com.cbq.yatori.core.utils.ConfigUtils; import com.cbq.yatori.core.utils.FileUtils; import com.cbq.yatori.core.utils.VerificationCodeUtil; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask;
11,470
accountCacheCangHui.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 LoginResponseRequest map=null; do { //获取验证码 File code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((map=com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user))==null); } while (map.getCode()==-1002); //对结果进行判定 if (map.getCode()==0) { accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), map.getMsg()); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //学习公社 case ENAEA -> { AccountCacheEnaea accountCacheEnaea = new AccountCacheEnaea(); user.setCache(accountCacheEnaea); //sS:101代表账号或密码错误, LoginAblesky loginAblesky = null; while((loginAblesky=com.cbq.yatori.core.action.enaea.LoginAction.toLogin(user))==null); //对结果进行判定 if (loginAblesky.getSS().equals("0")) { accountCacheEnaea.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), loginAblesky.getAlertMessage()); return; } } } } //刷课 for (User user : users) { switch (user.getAccountType()) { case YINGHUA -> { new Thread(()->{ //获取全部课程 CourseRequest allCourseList = null; while((allCourseList= CourseAction.getAllCourseRequest(user))==null); for (CourseInform courseInform : allCourseList.getResult().getList()) { //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getName())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getName())) continue; } } CourseStudyAction bulild = CourseStudyAction.builder() .user(user) .courseInform(courseInform) .newThread(true) .build(); bulild.toStudy(); } }).start(); } case CANGHUI -> { new Thread(()->{ //获取全部课程 // CourseRequest allCourseList = null; MyCourseData myCourseData = null; while((myCourseData= com.cbq.yatori.core.action.canghui.CourseAction.myCourseList(user))==null); for (MyCourse list : myCourseData.getLists()) { com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.Course courseInform = list.getCourse(); //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getTitle())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getTitle())) continue; } } com.cbq.yatori.core.action.canghui.CourseStudyAction bulild = com.cbq.yatori.core.action.canghui.CourseStudyAction.builder() .user(user) .courseInform(list) .newThread(true) .build(); bulild.toStudy(); } }).start(); } case ENAEA -> { new Thread(()->{ //获取正在进行的项目 UnderwayProjectRquest underwayProject = com.cbq.yatori.core.action.enaea.CourseAction.getUnderwayProject(user); //遍历获取所有正在学的课程项目
package com.cbq.yatori.console.run; /** * @author 长白崎 * @version 1.0 * @description: 加载启动程序 * @date 2023/10/31 8:45 */ @Slf4j public class Launch { private Config config; static { System.out.println(""" ___ \s ,---, ,--.'|_ ,--, \s /_ ./| | | :,' ,---. __ ,-.,--.'| \s ,---, | ' : : : ' : ' ,'\\ ,' ,'/ /|| |, \s /___/ \\. : | ,--.--. .;__,' / / / |' | |' |`--'_ \s . \\ \\ ,' ' / \\ | | | . ; ,. :| | ,',' ,'| \s \\ ; ` ,' .--. .-. |:__,'| : ' | |: :' : / ' | | \s \\ \\ ' \\__\\/: . . ' : |__' | .; :| | ' | | : \s ' \\ | ," .--.; | | | '.'| : |; : | ' : |__ \s \\ ; ; / / ,. | ; : ;\\ \\ / | , ; | | '.'|\s : \\ \\; : .' \\ | , / `----' ---' ; : ;\s \\ ' ;| , .-./ ---`-' | , / \s `--` `--`---' ---`-' \s Yatori v2.0.0-Beta.2 仅用于学习交流,请勿用于违法和商业用途!!! GitHub开源地址:https://github.com/Changbaiqi/brushlessons """); } /** * 初始化数据 */ public void init() { //加载配置文件 config = ConfigUtils.loadingConfig(); } public void toRun() { //获取账号列表----------------------------- List<User> users = config.getUsers(); //先进行登录---------------------------------------------- for (User user : users) { switch (user.getAccountType()) { //英华,创能 case YINGHUA -> { AccountCacheYingHua accountCacheYingHua = new AccountCacheYingHua(); user.setCache(accountCacheYingHua); //refresh_code:1代表密码错误, Map<String, Object> result = null; do { //获取SESSION String session = null; while ((session = LoginAction.getSESSION(user)) == null) ; accountCacheYingHua.setSession(session); //获取验证码 File code = null; while ((code = LoginAction.getCode(user)) == null) ; accountCacheYingHua.setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = LoginAction.toLogin(user)) == null) ; } while (!(Boolean) result.get("status") && ((String) result.get("msg")).contains("验证码有误")); //对结果进行判定 if ((Boolean) result.get("status")) { accountCacheYingHua.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) result.get("msg"))); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("更新成功")) { accountCacheYingHua.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheYingHua.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 Map<String, Object> map; do { //获取验证码 File code = LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 map = LoginAction.toLogin(user); } while (!(Boolean) map.get("status") && ((String) map.get("msg")).contains("验证码有误")); //对结果进行判定 if ((Boolean) map.get("status")) { accountCacheYingHua.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), ((String) map.get("msg"))); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //仓辉 case CANGHUI -> { AccountCacheCangHui accountCacheCangHui = new AccountCacheCangHui(); user.setCache(accountCacheCangHui); //refresh_code:1代表密码错误, LoginResponseRequest result=null; do { //获取SESSION String session = null; while ((session = com.cbq.yatori.core.action.canghui.LoginAction.getSESSION(user)) == null) ; accountCacheCangHui.setSession(session); //获取验证码 File code = null; while ((code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user)) == null) ; accountCacheCangHui.setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((result = com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user)) == null) ; } while (result.getCode()==-1002); //对结果进行判定 if (result.getCode()==0) { accountCacheCangHui.setToken(result.getData().getToken()); accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), result.getMsg()); return; } //为账号维持登录状态----------------------------------- new Thread(() -> { while (true) { Map online; //避免超时 while ((online = com.cbq.yatori.core.action.canghui.LoginAction.online(user)) == null) { try { Thread.sleep(1000 * 5); } catch (InterruptedException e) { throw new RuntimeException(e); } } //如果含有登录超时字样 if (((String) online.get("msg")).contains("成功")) { accountCacheCangHui.setStatus(1); } else if (((String) online.get("msg")).contains("登录超时")) { accountCacheCangHui.setStatus(2);//设定登录状态为超时 log.info("{}登录超时,正在重新登录...", user.getAccount()); //进行登录 LoginResponseRequest map=null; do { //获取验证码 File code = com.cbq.yatori.core.action.canghui.LoginAction.getCode(user); ((AccountCacheYingHua) user.getCache()).setCode(VerificationCodeUtil.aiDiscern(code)); FileUtils.deleteFile(code);//删除验证码文件 //进行登录操作 while ((map=com.cbq.yatori.core.action.canghui.LoginAction.toLogin(user))==null); } while (map.getCode()==-1002); //对结果进行判定 if (map.getCode()==0) { accountCacheCangHui.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), map.getMsg()); } } try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { throw new RuntimeException(e); } } }).start(); } //学习公社 case ENAEA -> { AccountCacheEnaea accountCacheEnaea = new AccountCacheEnaea(); user.setCache(accountCacheEnaea); //sS:101代表账号或密码错误, LoginAblesky loginAblesky = null; while((loginAblesky=com.cbq.yatori.core.action.enaea.LoginAction.toLogin(user))==null); //对结果进行判定 if (loginAblesky.getSS().equals("0")) { accountCacheEnaea.setStatus(1); log.info("{}登录成功!", user.getAccount()); } else { log.info("{}登录失败,服务器信息>>>{}", user.getAccount(), loginAblesky.getAlertMessage()); return; } } } } //刷课 for (User user : users) { switch (user.getAccountType()) { case YINGHUA -> { new Thread(()->{ //获取全部课程 CourseRequest allCourseList = null; while((allCourseList= CourseAction.getAllCourseRequest(user))==null); for (CourseInform courseInform : allCourseList.getResult().getList()) { //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getName())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getName())) continue; } } CourseStudyAction bulild = CourseStudyAction.builder() .user(user) .courseInform(courseInform) .newThread(true) .build(); bulild.toStudy(); } }).start(); } case CANGHUI -> { new Thread(()->{ //获取全部课程 // CourseRequest allCourseList = null; MyCourseData myCourseData = null; while((myCourseData= com.cbq.yatori.core.action.canghui.CourseAction.myCourseList(user))==null); for (MyCourse list : myCourseData.getLists()) { com.cbq.yatori.core.action.canghui.entity.mycourselistresponse.Course courseInform = list.getCourse(); //课程排除配置 if(user.getCoursesCostom()!=null) { if (user.getCoursesCostom().getExcludeCourses() != null) { if (user.getCoursesCostom().getExcludeCourses().size() != 0) if (user.getCoursesCostom().getExcludeCourses().contains(courseInform.getTitle())) continue; } //如果有指定课程包含设定,那么就执行 if (user.getCoursesCostom().getIncludeCourses() != null) { if (user.getCoursesCostom().getIncludeCourses().size() != 0) if (!user.getCoursesCostom().getIncludeCourses().contains(courseInform.getTitle())) continue; } } com.cbq.yatori.core.action.canghui.CourseStudyAction bulild = com.cbq.yatori.core.action.canghui.CourseStudyAction.builder() .user(user) .courseInform(list) .newThread(true) .build(); bulild.toStudy(); } }).start(); } case ENAEA -> { new Thread(()->{ //获取正在进行的项目 UnderwayProjectRquest underwayProject = com.cbq.yatori.core.action.enaea.CourseAction.getUnderwayProject(user); //遍历获取所有正在学的课程项目
for (ResultList resultList : underwayProject.getResult().getList()) {
4
2023-10-30 04:15:41+00:00
16k
sgware/sabre
src/edu/uky/cs/nil/sabre/comp/CompiledEvent.java
[ { "identifier": "Event", "path": "src/edu/uky/cs/nil/sabre/Event.java", "snippet": "public interface Event extends Simplifiable, Signed {\n\t\n\t@Override\n\tpublic default boolean isGround() {\n\t\treturn getSignature().isGround() && getPrecondition().isGround() && getEffect().isGround();\n\t}\n\t\n\t@...
import edu.uky.cs.nil.sabre.Event; import edu.uky.cs.nil.sabre.Fluent; import edu.uky.cs.nil.sabre.logic.Clause; import edu.uky.cs.nil.sabre.logic.Disjunction; import edu.uky.cs.nil.sabre.logic.Effect; import edu.uky.cs.nil.sabre.logic.Precondition; import edu.uky.cs.nil.sabre.util.Unique;
11,484
package edu.uky.cs.nil.sabre.comp; /** * A compiled event is a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() * ground} {@link Event event} which defines a {@link Unique unique} {@link * #getID() ID number} that corresponds to the event's index in its {@link * CompiledProblem#events compiled problem's set of events}, whose {@link * #getPrecondition() precondition} is in {@link * edu.uky.cs.nil.sabre.logic.Expression#toPrecondition() disjunctive normal * form}, and whose {@link #getEffect() effect} is {@link * edu.uky.cs.nil.sabre.logic.Expression#toEffect() a clause}. * * @author Stephen G. Ware */ public interface CompiledEvent extends Event, Unique { @Override public default boolean isGround() { return true; } @Override public default CompiledEvent simplify() { return this; } @Override public Disjunction<Clause<Precondition>> getPrecondition(); @Override public Clause<Effect> getEffect(); /** * Returns the event's unique ID number, which should correspond to this * event's index in its {@link CompiledProblem#events compiled problem's * set of events}. * * @return the event's unique ID number */ public int getID(); /** * Returns a {@link Clause clause} composed of every {@link Effect effect} * in {@link #getEffect() this event's effect} that has the given fluent * {@link edu.uky.cs.nil.sabre.logic.Assignment#fluent as its fluent}. The * returned clause may be empty if this event does not affect the given * fluent, or it may have several atoms if this event has several * conditional effects which might affect the given fluent. * * @param fluent the fluent which this event may affect * @return a clause of all ways this event could affect the given fluent */
package edu.uky.cs.nil.sabre.comp; /** * A compiled event is a {@link edu.uky.cs.nil.sabre.logic.Logical#isGround() * ground} {@link Event event} which defines a {@link Unique unique} {@link * #getID() ID number} that corresponds to the event's index in its {@link * CompiledProblem#events compiled problem's set of events}, whose {@link * #getPrecondition() precondition} is in {@link * edu.uky.cs.nil.sabre.logic.Expression#toPrecondition() disjunctive normal * form}, and whose {@link #getEffect() effect} is {@link * edu.uky.cs.nil.sabre.logic.Expression#toEffect() a clause}. * * @author Stephen G. Ware */ public interface CompiledEvent extends Event, Unique { @Override public default boolean isGround() { return true; } @Override public default CompiledEvent simplify() { return this; } @Override public Disjunction<Clause<Precondition>> getPrecondition(); @Override public Clause<Effect> getEffect(); /** * Returns the event's unique ID number, which should correspond to this * event's index in its {@link CompiledProblem#events compiled problem's * set of events}. * * @return the event's unique ID number */ public int getID(); /** * Returns a {@link Clause clause} composed of every {@link Effect effect} * in {@link #getEffect() this event's effect} that has the given fluent * {@link edu.uky.cs.nil.sabre.logic.Assignment#fluent as its fluent}. The * returned clause may be empty if this event does not affect the given * fluent, or it may have several atoms if this event has several * conditional effects which might affect the given fluent. * * @param fluent the fluent which this event may affect * @return a clause of all ways this event could affect the given fluent */
public default Clause<Effect> getEffect(Fluent fluent) {
1
2023-10-26 18:14:19+00:00
16k
granny/Pl3xMap
core/src/main/java/net/pl3x/map/core/image/TileImage.java
[ { "identifier": "Keyed", "path": "core/src/main/java/net/pl3x/map/core/Keyed.java", "snippet": "public abstract class Keyed {\n private final String key;\n\n /**\n * Create a new key identified object.\n *\n * @param key key for object\n */\n public Keyed(@NotNull String key) {\...
import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import net.pl3x.map.core.Keyed; import net.pl3x.map.core.configuration.Config; import net.pl3x.map.core.image.io.IO; import net.pl3x.map.core.markers.Point; import net.pl3x.map.core.util.Colors; import net.pl3x.map.core.util.FileUtil; import net.pl3x.map.core.world.World; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap;
12,000
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.core.image; public class TileImage extends Keyed { private static final Map<@NotNull Path, @NotNull ReadWriteLock> FILE_LOCKS = new ConcurrentHashMap<>(); public static final String DIR_PATH = "%d/%s/"; public static final String FILE_PATH = "%d_%d.%s"; private final World world; private final Point region; private final int[] pixels = new int[512 << 9]; private final IO.Type io; private boolean written = false; public TileImage(@NotNull String key, @NotNull World world, @NotNull Point region) { super(key); this.world = world; this.region = region;
/* * MIT License * * Copyright (c) 2020-2023 William Blake Galbreath * * 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 net.pl3x.map.core.image; public class TileImage extends Keyed { private static final Map<@NotNull Path, @NotNull ReadWriteLock> FILE_LOCKS = new ConcurrentHashMap<>(); public static final String DIR_PATH = "%d/%s/"; public static final String FILE_PATH = "%d_%d.%s"; private final World world; private final Point region; private final int[] pixels = new int[512 << 9]; private final IO.Type io; private boolean written = false; public TileImage(@NotNull String key, @NotNull World world, @NotNull Point region) { super(key); this.world = world; this.region = region;
this.io = IO.get(Config.WEB_TILE_FORMAT);
1
2023-10-26 01:14:31+00:00
16k
d0ge/sessionless
src/test/java/TornadoTest.java
[ { "identifier": "Attack", "path": "src/main/java/one/d4d/sessionless/itsdangerous/Attack.java", "snippet": "public enum Attack {\n @SerializedName(\"Known\")\n KNOWN(\"Known\"),\n @SerializedName(\"Fast\")\n FAST(\"Fast\"),\n @SerializedName(\"Balanced\")\n Balanced(\"Balanced\"),\n ...
import one.d4d.sessionless.itsdangerous.Attack; import one.d4d.sessionless.itsdangerous.BruteForce; import one.d4d.sessionless.itsdangerous.crypto.TornadoTokenSigner; import one.d4d.sessionless.itsdangerous.model.SignedToken; import one.d4d.sessionless.itsdangerous.model.SignedTokenObjectFinder; import one.d4d.sessionless.itsdangerous.model.TornadoSignedToken; import one.d4d.sessionless.keys.SecretKey; import one.d4d.sessionless.utils.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional;
11,153
public class TornadoTest { @Test void TornadoParserTest() { byte[] secret ="secret".getBytes(); String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoSignedToken token = (TornadoSignedToken) optionalToken.get(); TornadoTokenSigner s = new TornadoTokenSigner(secret, (byte)'|'); token.setSigner(s); Assertions.assertDoesNotThrow( ()-> { s.unsign(value.getBytes()); }); }else { Assertions.fail("Token not found."); } } @Test void BruteForceMultiThreatTornado() { String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Assertions.assertDoesNotThrow(() -> { Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoTokenSigner s = new TornadoTokenSigner(); optionalToken.get().setSigner(s); final List<String> secrets = Utils.readResourceForClass("/secrets", this.getClass()); final List<String> salts = Utils.readResourceForClass("/salts", this.getClass()); final List<SecretKey> knownKeys = new ArrayList<>();
public class TornadoTest { @Test void TornadoParserTest() { byte[] secret ="secret".getBytes(); String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoSignedToken token = (TornadoSignedToken) optionalToken.get(); TornadoTokenSigner s = new TornadoTokenSigner(secret, (byte)'|'); token.setSigner(s); Assertions.assertDoesNotThrow( ()-> { s.unsign(value.getBytes()); }); }else { Assertions.fail("Token not found."); } } @Test void BruteForceMultiThreatTornado() { String value = "2|1:0|10:1686150202|7:session|4:e30=|5e05eeef41715bc4b109138f00a37bbc580ca7e94ba9a21d5ec062b7aebff557"; Assertions.assertDoesNotThrow(() -> { Optional<SignedToken> optionalToken = SignedTokenObjectFinder.parseTornadoSignedToken("test", value); if (optionalToken.isPresent()) { TornadoTokenSigner s = new TornadoTokenSigner(); optionalToken.get().setSigner(s); final List<String> secrets = Utils.readResourceForClass("/secrets", this.getClass()); final List<String> salts = Utils.readResourceForClass("/salts", this.getClass()); final List<SecretKey> knownKeys = new ArrayList<>();
BruteForce bf = new BruteForce(secrets, salts, knownKeys, Attack.FAST, optionalToken.get());
0
2023-10-30 09:12:06+00:00
16k
LEAWIND/Third-Person
common/src/main/java/net/leawind/mc/thirdperson/event/ThirdPersonEvents.java
[ { "identifier": "ThirdPerson", "path": "common/src/main/java/net/leawind/mc/thirdperson/ThirdPerson.java", "snippet": "public class ThirdPerson {\n\tpublic static final Logger LOGGER = LoggerFactory.getLogger(ModConstants.MOD_ID);\n\tprivate static final ConfigManager CONFIG_MA...
import com.mojang.blaze3d.Blaze3D; import com.mojang.blaze3d.platform.Window; import dev.architectury.event.EventResult; import dev.architectury.event.events.client.ClientPlayerEvent; import dev.architectury.event.events.client.ClientRawInputEvent; import dev.architectury.event.events.client.ClientTickEvent; import net.leawind.mc.thirdperson.ThirdPerson; import net.leawind.mc.thirdperson.api.ModConstants; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetMode; import net.leawind.mc.thirdperson.api.cameraoffset.CameraOffsetScheme; import net.leawind.mc.thirdperson.core.CameraAgent; import net.leawind.mc.thirdperson.core.ModReferee; import net.leawind.mc.thirdperson.core.PlayerAgent; import net.leawind.mc.thirdperson.impl.config.Config; import net.leawind.mc.util.api.math.vector.Vector2d; import net.leawind.mc.util.math.LMath; import net.minecraft.client.CameraType; import net.minecraft.client.Minecraft; import net.minecraft.client.player.LocalPlayer; import net.minecraft.util.Mth; import net.minecraft.world.level.BlockGetter;
11,389
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; } Config config = ThirdPerson.getConfig(); CameraAgent.updateSmoothEyePosition(0.05);
package net.leawind.mc.thirdperson.event; public interface ThirdPersonEvents { static void register () { ClientTickEvent.CLIENT_PRE.register(ThirdPersonEvents::onClientTickPre); ClientPlayerEvent.CLIENT_PLAYER_RESPAWN.register(ThirdPersonEvents::onClientPlayerRespawn); ClientPlayerEvent.CLIENT_PLAYER_JOIN.register(ThirdPersonEvents::onClientPlayerJoin); ClientRawInputEvent.MOUSE_SCROLLED.register(ThirdPersonEvents::onMouseScrolled); } private static void onClientTickPre (Minecraft mc) { if (mc.isPaused()) { return; } Config config = ThirdPerson.getConfig(); CameraAgent.updateSmoothEyePosition(0.05);
PlayerAgent.updateSmoothRotations(0.05);
6
2023-10-31 05:52:36+00:00
16k
siam1026/siam-cloud
siam-goods/goods-provider/src/main/java/com/siam/package_goods/controller/admin/AdminGoodsController.java
[ { "identifier": "BasicResultCode", "path": "siam-common/src/main/java/com/siam/package_common/constant/BasicResultCode.java", "snippet": "public class BasicResultCode {\n public static final int ERR = 0;\n\n public static final int SUCCESS = 1;\n\n public static final int TOKEN_ERR = 2;\n}" }...
import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.siam.package_common.constant.BasicResultCode; import com.siam.package_common.constant.BusinessType; import com.siam.package_common.constant.Quantity; import com.siam.package_common.entity.BasicData; import com.siam.package_common.entity.BasicResult; import com.siam.package_common.exception.StoneCustomerException; import com.siam.package_common.util.OSSUtils; import com.siam.package_goods.entity.Goods; import com.siam.package_goods.entity.MenuGoodsRelation; import com.siam.package_goods.model.dto.GoodsMenuDto; import com.siam.package_goods.model.example.MenuGoodsRelationExample; import com.siam.package_goods.service.*; import com.siam.package_promotion.entity.Coupons; import com.siam.package_promotion.entity.CouponsGoodsRelation; import com.siam.package_promotion.feign.CouponsFeignApi; import com.siam.package_promotion.feign.CouponsGoodsRelationFeignApi; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.Map;
11,483
package com.siam.package_goods.controller.admin; @RestController @RequestMapping(value = "/rest/admin/goods") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台商品模块相关接口", description = "AdminGoodsController") public class AdminGoodsController { @Autowired private GoodsService goodsService; @Autowired private OSSUtils ossUtils; @Autowired private MenuGoodsRelationService menuGoodsRelationService; @Autowired private GoodsSpecificationService goodsSpecificationService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsRawmaterialRelationService goodsRawmaterialRelationService; @Autowired private CouponsFeignApi couponsFeignApi; @Autowired private CouponsGoodsRelationFeignApi couponsGoodsRelationFeignApi; @ApiOperation(value = "商品列表") @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) GoodsMenuDto param){ BasicData basicResult = new BasicData(); Page<Map<String, Object>> page = goodsService.getListByPageJoinMenu(param.getPageNo(), param.getPageSize(), param); return BasicResult.success(page); } @ApiOperation(value = "新增商品") @PostMapping(value = "/insert") public BasicResult insert(@RequestBody @Validated(value = {}) GoodsMenuDto param){ BasicResult basicResult = new BasicResult(); //商品的主图 等于 商品轮播图的第一张图 if(StringUtils.isNotBlank(param.getSubImages())){ param.setMainImage(param.getSubImages().split(",")[0]); } //添加商品记录 //设置默认库存为0 param.setStock(Quantity.INT_0); param.setMonthlySales(Quantity.INT_0); param.setTotalSales(Quantity.INT_0); param.setTotalComments(Quantity.INT_0); param.setCreateTime(new Date()); param.setUpdateTime(new Date()); //兑换商品所需积分数量新增时默认等于折扣价 param.setExchangePoints(param.getPrice().intValue()); goodsService.insertSelective(param); //建立商品与类别的关系 MenuGoodsRelation insertMenuGoodsRelation = new MenuGoodsRelation(); insertMenuGoodsRelation.setGoodsId(param.getId()); insertMenuGoodsRelation.setMenuId(param.getMenuId()); insertMenuGoodsRelation.setCreateTime(new Date()); insertMenuGoodsRelation.setUpdateTime(new Date()); menuGoodsRelationService.insertSelective(insertMenuGoodsRelation); //生成商品公共规格 goodsSpecificationService.insertPublicGoodsSpecification(param.getId()); //建立商品与系统默认优惠券ID-新人3折卷的关联关系
package com.siam.package_goods.controller.admin; @RestController @RequestMapping(value = "/rest/admin/goods") @Transactional(rollbackFor = Exception.class) @Api(tags = "后台商品模块相关接口", description = "AdminGoodsController") public class AdminGoodsController { @Autowired private GoodsService goodsService; @Autowired private OSSUtils ossUtils; @Autowired private MenuGoodsRelationService menuGoodsRelationService; @Autowired private GoodsSpecificationService goodsSpecificationService; @Autowired private GoodsSpecificationOptionService goodsSpecificationOptionService; @Autowired private ShoppingCartService shoppingCartService; @Autowired private GoodsRawmaterialRelationService goodsRawmaterialRelationService; @Autowired private CouponsFeignApi couponsFeignApi; @Autowired private CouponsGoodsRelationFeignApi couponsGoodsRelationFeignApi; @ApiOperation(value = "商品列表") @PostMapping(value = "/list") public BasicResult list(@RequestBody @Validated(value = {}) GoodsMenuDto param){ BasicData basicResult = new BasicData(); Page<Map<String, Object>> page = goodsService.getListByPageJoinMenu(param.getPageNo(), param.getPageSize(), param); return BasicResult.success(page); } @ApiOperation(value = "新增商品") @PostMapping(value = "/insert") public BasicResult insert(@RequestBody @Validated(value = {}) GoodsMenuDto param){ BasicResult basicResult = new BasicResult(); //商品的主图 等于 商品轮播图的第一张图 if(StringUtils.isNotBlank(param.getSubImages())){ param.setMainImage(param.getSubImages().split(",")[0]); } //添加商品记录 //设置默认库存为0 param.setStock(Quantity.INT_0); param.setMonthlySales(Quantity.INT_0); param.setTotalSales(Quantity.INT_0); param.setTotalComments(Quantity.INT_0); param.setCreateTime(new Date()); param.setUpdateTime(new Date()); //兑换商品所需积分数量新增时默认等于折扣价 param.setExchangePoints(param.getPrice().intValue()); goodsService.insertSelective(param); //建立商品与类别的关系 MenuGoodsRelation insertMenuGoodsRelation = new MenuGoodsRelation(); insertMenuGoodsRelation.setGoodsId(param.getId()); insertMenuGoodsRelation.setMenuId(param.getMenuId()); insertMenuGoodsRelation.setCreateTime(new Date()); insertMenuGoodsRelation.setUpdateTime(new Date()); menuGoodsRelationService.insertSelective(insertMenuGoodsRelation); //生成商品公共规格 goodsSpecificationService.insertPublicGoodsSpecification(param.getId()); //建立商品与系统默认优惠券ID-新人3折卷的关联关系
Coupons dbCoupons = couponsFeignApi.selectByPrimaryKey(BusinessType.NEW_PEOPLE_COUPONS_ID).getData();
1
2023-10-26 10:45:10+00:00
16k
oghenevovwerho/yaa
src/main/java/yaa/semantic/passes/fs6/ifs/LookUpSwitch.java
[ { "identifier": "F6Utils", "path": "src/main/java/yaa/semantic/passes/fs6/F6Utils.java", "snippet": "public class F6Utils {\r\n public static void saveClass4Writing(String internalName) {\r\n var classFileData = new ClassFileData();\r\n classFileData.internalName = internalName;\r\n\r\n if (fs...
import yaa.ast.*; import yaa.semantic.passes.fs6.F6Utils; import org.objectweb.asm.Label; import yaa.pojos.GlobalData; import java.util.HashMap; import java.util.TreeMap; import static yaa.semantic.passes.fs6.F6.mw; import static java.lang.Integer.parseInt; import static org.objectweb.asm.Opcodes.GOTO;
12,765
package yaa.semantic.passes.fs6.ifs; public class LookUpSwitch { public static void handleLookUpSwitch(IfStmt ctx) { var cases = ctx.cases; var labels = new SwitchLabeller(cases.size()); var end$jump = new Label(); var keys = new int[cases.size()]; //The elements of a look-up switch must be sorted by their keys var values = new TreeMap<Integer, Integer>(); for (int i = 0; i < cases.size(); i++) { var e_value = cases.get(i).case_condition; if (e_value instanceof Decimal decimal) { values.put(parseInt(decimal.token.content), i); } else if (e_value instanceof Shorted shorted) { values.put(parseInt(shorted.token.neededContent), i); } else if (e_value instanceof Byted byted) { values.put(parseInt(byted.token.neededContent), i); } else if (e_value instanceof Basex basex && (basex.xToken.isShorted || basex.xToken.isInt || basex.xToken.isLong || basex.xToken.isByte)) { values.put(parseInt(basex.xToken.content, basex.xToken.base), i); } else if (e_value instanceof Cha cha) { values.put(Character.hashCode(cha.content.toString().charAt(0)), i); } labels.putLabel(new Label()); } var i = 0; for (var value : values.entrySet()) { keys[i++] = value.getKey(); } var defaultJump = new Label(); var jumpIndices = new HashMap<String, Integer>();
package yaa.semantic.passes.fs6.ifs; public class LookUpSwitch { public static void handleLookUpSwitch(IfStmt ctx) { var cases = ctx.cases; var labels = new SwitchLabeller(cases.size()); var end$jump = new Label(); var keys = new int[cases.size()]; //The elements of a look-up switch must be sorted by their keys var values = new TreeMap<Integer, Integer>(); for (int i = 0; i < cases.size(); i++) { var e_value = cases.get(i).case_condition; if (e_value instanceof Decimal decimal) { values.put(parseInt(decimal.token.content), i); } else if (e_value instanceof Shorted shorted) { values.put(parseInt(shorted.token.neededContent), i); } else if (e_value instanceof Byted byted) { values.put(parseInt(byted.token.neededContent), i); } else if (e_value instanceof Basex basex && (basex.xToken.isShorted || basex.xToken.isInt || basex.xToken.isLong || basex.xToken.isByte)) { values.put(parseInt(basex.xToken.content, basex.xToken.base), i); } else if (e_value instanceof Cha cha) { values.put(Character.hashCode(cha.content.toString().charAt(0)), i); } labels.putLabel(new Label()); } var i = 0; for (var value : values.entrySet()) { keys[i++] = value.getKey(); } var defaultJump = new Label(); var jumpIndices = new HashMap<String, Integer>();
mw().visitLookupSwitchInsn(defaultJump, keys, labels.labels);
2
2023-10-26 17:41:13+00:00
16k
quentin452/DangerRPG-Continuation
src/main/java/mixac1/dangerrpg/init/RPGItems.java
[ { "identifier": "RPGItemRarity", "path": "src/main/java/mixac1/dangerrpg/init/RPGOther.java", "snippet": "public static abstract class RPGItemRarity {\n\n public static EnumRarity common = EnumHelper.addRarity(\"common\", EnumChatFormatting.WHITE, \"Common\");\n\n public static EnumRarity uncommon...
import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; import mixac1.dangerrpg.init.RPGOther.RPGItemRarity; import mixac1.dangerrpg.item.ItemE; import mixac1.dangerrpg.item.RPGArmorMaterial; import mixac1.dangerrpg.item.RPGItemComponent; import mixac1.dangerrpg.item.RPGItemComponent.RPGArmorComponent; import mixac1.dangerrpg.item.RPGItemComponent.RPGToolComponent; import mixac1.dangerrpg.item.RPGToolMaterial; import mixac1.dangerrpg.item.armor.ItemMageArmor; import mixac1.dangerrpg.item.armor.ItemRPGArmor; import mixac1.dangerrpg.item.tool.*; import mixac1.dangerrpg.item.weapon.*; import mixac1.dangerrpg.util.Utils; import net.minecraft.item.Item;
10,991
public static Item katanaBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.KATANA); public static Item katanaBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.KATANA); public static Item katanaWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.KATANA); public static Item scytheWood = new ItemRPGWeapon(RPGToolMaterial.WOOD, RPGItemComponent.SCYTHE); public static Item scytheStone = new ItemRPGWeapon(RPGToolMaterial.STONE, RPGItemComponent.SCYTHE); public static Item scytheIron = new ItemRPGWeapon(RPGToolMaterial.IRON, RPGItemComponent.SCYTHE); public static Item scytheGold = new ItemRPGWeapon(RPGToolMaterial.GOLD, RPGItemComponent.SCYTHE); public static Item scytheDiamond = new ItemRPGWeapon(RPGToolMaterial.DIAMOND, RPGItemComponent.SCYTHE); public static Item scytheObsidian = new ItemRPGWeapon(RPGToolMaterial.OBSIDIAN, RPGItemComponent.SCYTHE); public static Item scytheBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.SCYTHE); public static Item scytheBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.SCYTHE); public static Item scytheWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.SCYTHE); public static Item hammerWood = new ItemRPGWeapon(RPGToolMaterial.WOOD, RPGItemComponent.HAMMER); public static Item hammerStone = new ItemRPGWeapon(RPGToolMaterial.STONE, RPGItemComponent.HAMMER); public static Item hammerIron = new ItemRPGWeapon(RPGToolMaterial.IRON, RPGItemComponent.HAMMER); public static Item hammerGold = new ItemRPGWeapon(RPGToolMaterial.GOLD, RPGItemComponent.HAMMER); public static Item hammerDiamond = new ItemRPGWeapon(RPGToolMaterial.DIAMOND, RPGItemComponent.HAMMER); public static Item hammerObsidian = new ItemRPGWeapon(RPGToolMaterial.OBSIDIAN, RPGItemComponent.HAMMER); public static Item hammerBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.HAMMER); public static Item hammerBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.HAMMER); public static Item hammerWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.HAMMER); public static Item tomahawkWood = new ItemRPGTomahawk(RPGToolMaterial.WOOD, RPGItemComponent.TOMAHAWK); public static Item tomahawkStone = new ItemRPGTomahawk(RPGToolMaterial.STONE, RPGItemComponent.TOMAHAWK); public static Item tomahawkIron = new ItemRPGTomahawk(RPGToolMaterial.IRON, RPGItemComponent.TOMAHAWK); public static Item tomahawkGold = new ItemRPGTomahawk(RPGToolMaterial.GOLD, RPGItemComponent.TOMAHAWK); public static Item tomahawkDiamond = new ItemRPGTomahawk(RPGToolMaterial.DIAMOND, RPGItemComponent.TOMAHAWK); public static Item tomahawkObsidian = new ItemRPGTomahawk(RPGToolMaterial.OBSIDIAN, RPGItemComponent.TOMAHAWK); public static Item tomahawkBedrock = new ItemRPGTomahawk(RPGToolMaterial.BEDROCK, RPGItemComponent.TOMAHAWK); public static Item tomahawkBlackMatter = new ItemRPGTomahawk( RPGToolMaterial.BLACK_MATTER, RPGItemComponent.TOMAHAWK); public static Item tomahawkWhiteMatter = new ItemRPGTomahawk( RPGToolMaterial.WHITE_MATTER, RPGItemComponent.TOMAHAWK); public static Item knifeWood = new ItemRPGKnife(RPGToolMaterial.WOOD, RPGItemComponent.KNIFE); public static Item knifeStone = new ItemRPGKnife(RPGToolMaterial.STONE, RPGItemComponent.KNIFE); public static Item knifeIron = new ItemRPGKnife(RPGToolMaterial.IRON, RPGItemComponent.KNIFE); public static Item knifeGold = new ItemRPGKnife(RPGToolMaterial.GOLD, RPGItemComponent.KNIFE); public static Item knifeDiamond = new ItemRPGKnife(RPGToolMaterial.DIAMOND, RPGItemComponent.KNIFE); public static Item knifeObsidian = new ItemRPGKnife(RPGToolMaterial.OBSIDIAN, RPGItemComponent.KNIFE); public static Item knifeBedrock = new ItemRPGKnife(RPGToolMaterial.BEDROCK, RPGItemComponent.KNIFE); public static Item knifeBlackMatter = new ItemRPGKnife(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.KNIFE); public static Item knifeWhiteMatter = new ItemRPGKnife(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.KNIFE); public static Item staffGold = new ItemRPGStaff(RPGToolMaterial.GOLD, RPGItemComponent.STAFF); public static Item staffDiamond = new ItemRPGStaff(RPGToolMaterial.DIAMOND, RPGItemComponent.STAFF); public static Item staffObsidian = new ItemRPGStaff(RPGToolMaterial.OBSIDIAN, RPGItemComponent.STAFF); public static Item staffBedrock = new ItemRPGStaff(RPGToolMaterial.BEDROCK, RPGItemComponent.STAFF); public static Item staffBlackMatter = new ItemRPGStaff(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.STAFF); public static Item staffWhiteMatter = new ItemRPGStaff(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.STAFF); public static Item powerStaffGold = new ItemPowerStaff(RPGToolMaterial.GOLD, RPGItemComponent.POWER_STAFF); public static Item powerStaffDiamond = new ItemPowerStaff(RPGToolMaterial.DIAMOND, RPGItemComponent.POWER_STAFF); public static Item powerStaffObsidian = new ItemPowerStaff(RPGToolMaterial.OBSIDIAN, RPGItemComponent.POWER_STAFF); public static Item powerStaffBedrock = new ItemPowerStaff(RPGToolMaterial.BEDROCK, RPGItemComponent.POWER_STAFF); public static Item powerStaffBlackMatter = new ItemPowerStaff( RPGToolMaterial.BLACK_MATTER, RPGItemComponent.POWER_STAFF); public static Item powerStaffWhiteMatter = new ItemPowerStaff( RPGToolMaterial.WHITE_MATTER, RPGItemComponent.POWER_STAFF); public static Item axeObsidian = new ItemRPGAxe(RPGToolMaterial.OBSIDIAN); public static Item axeBedrock = new ItemRPGAxe(RPGToolMaterial.BEDROCK); public static Item axeBlackMatter = new ItemRPGAxe(RPGToolMaterial.BLACK_MATTER); public static Item axeWhiteMatter = new ItemRPGAxe(RPGToolMaterial.WHITE_MATTER); public static Item hoeObsidian = new ItemRPGHoe(RPGToolMaterial.OBSIDIAN); public static Item hoeBedrock = new ItemRPGHoe(RPGToolMaterial.BEDROCK); public static Item hoeBlackMatter = new ItemRPGHoe(RPGToolMaterial.BLACK_MATTER); public static Item hoeWhiteMatter = new ItemRPGHoe(RPGToolMaterial.WHITE_MATTER); public static Item pickaxeObsidian = new ItemRPGPickaxe(RPGToolMaterial.OBSIDIAN); public static Item pickaxeBedrock = new ItemRPGPickaxe(RPGToolMaterial.BEDROCK); public static Item pickaxeBlackMatter = new ItemRPGPickaxe(RPGToolMaterial.BLACK_MATTER); public static Item pickaxeWhiteMatter = new ItemRPGPickaxe(RPGToolMaterial.WHITE_MATTER); public static Item shovelObsidian = new ItemRPGSpade(RPGToolMaterial.OBSIDIAN); public static Item shovelBedrock = new ItemRPGSpade(RPGToolMaterial.BEDROCK); public static Item shovelBlackMatter = new ItemRPGSpade(RPGToolMaterial.BLACK_MATTER); public static Item shovelWhiteMatter = new ItemRPGSpade(RPGToolMaterial.WHITE_MATTER); public static Item multitoolWood = new ItemRPGMultiTool(RPGToolMaterial.WOOD); public static Item multitoolStone = new ItemRPGMultiTool(RPGToolMaterial.STONE); public static Item multitoolIron = new ItemRPGMultiTool(RPGToolMaterial.IRON); public static Item multitoolGold = new ItemRPGMultiTool(RPGToolMaterial.GOLD); public static Item multitoolDiamond = new ItemRPGMultiTool(RPGToolMaterial.DIAMOND); public static Item multitoolObsidian = new ItemRPGMultiTool(RPGToolMaterial.OBSIDIAN); public static Item multitoolBedrock = new ItemRPGMultiTool(RPGToolMaterial.BEDROCK); public static Item multitoolBlackMatter = new ItemRPGMultiTool(RPGToolMaterial.BLACK_MATTER); public static Item multitoolWhiteMatter = new ItemRPGMultiTool(RPGToolMaterial.WHITE_MATTER); public static Item[] armorObsidian = ItemRPGArmor.createFullSet(RPGArmorMaterial.OBSIDIAN, RPGArmorComponent.ARMOR); public static Item[] armorBedrock = ItemRPGArmor.createFullSet(RPGArmorMaterial.BEDROCK, RPGArmorComponent.ARMOR); public static Item[] armorBlackMatter = ItemRPGArmor .createFullSet(RPGArmorMaterial.BLACK_MATTER, RPGArmorComponent.ARMOR); public static Item[] armorWhiteMatter = ItemRPGArmor .createFullSet(RPGArmorMaterial.WHITE_MATTER, RPGArmorComponent.ARMOR); public static Item[] mageArmorCloth = ItemMageArmor .createFullSet(RPGArmorMaterial.CLOTH, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorIron = ItemMageArmor .createFullSet(RPGArmorMaterial.IRON, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorGold = ItemMageArmor .createFullSet(RPGArmorMaterial.GOLD, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorDiamond = ItemMageArmor .createFullSet(RPGArmorMaterial.DIAMOND, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorObsidian = ItemMageArmor .createFullSet(RPGArmorMaterial.OBSIDIAN, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorBedrock = ItemMageArmor .createFullSet(RPGArmorMaterial.BEDROCK, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorBlackMatter = ItemMageArmor .createFullSet(RPGArmorMaterial.BLACK_MATTER, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorWhiteMatter = ItemMageArmor .createFullSet(RPGArmorMaterial.WHITE_MATTER, RPGArmorComponent.MAGE_ARMOR);
package mixac1.dangerrpg.init; public abstract class RPGItems { public static Item magicLeather = new ItemE("magic_leather"); public static Item compressedObsidian = new ItemE("compressed_obsidian"); public static Item compressedBedrock = new ItemE("compressed_bedrock"); public static Item blackMatter = new ItemE("black_matter"); public static Item whiteMatter = new ItemE("white_matter"); public static Item stickDiamond = new ItemE("stick_diamond"); public static Item stickObsidian = new ItemE("stick_obsidian"); public static Item stickBlackMatter = new ItemE("stick_black_matter"); public static Item stickWhiteMatter = new ItemE("stick_white_matter"); public static Item swordObsidian = new ItemRPGWeapon(RPGToolMaterial.OBSIDIAN, RPGItemComponent.SWORD); public static Item swordBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.SWORD); public static Item swordBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.SWORD); public static Item swordWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.SWORD); public static Item naginataWood = new ItemRPGWeapon(RPGToolMaterial.WOOD, RPGItemComponent.NAGINATA); public static Item naginataStone = new ItemRPGWeapon(RPGToolMaterial.STONE, RPGItemComponent.NAGINATA); public static Item naginataIron = new ItemRPGWeapon(RPGToolMaterial.IRON, RPGItemComponent.NAGINATA); public static Item naginataGold = new ItemRPGWeapon(RPGToolMaterial.GOLD, RPGItemComponent.NAGINATA); public static Item naginataDiamond = new ItemRPGWeapon(RPGToolMaterial.DIAMOND, RPGItemComponent.NAGINATA); public static Item naginataObsidian = new ItemRPGWeapon(RPGToolMaterial.OBSIDIAN, RPGItemComponent.NAGINATA); public static Item naginataBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.NAGINATA); public static Item naginataBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.NAGINATA); public static Item naginataWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.NAGINATA); public static Item katanaWood = new ItemRPGWeapon(RPGToolMaterial.WOOD, RPGItemComponent.KATANA); public static Item katanaStone = new ItemRPGWeapon(RPGToolMaterial.STONE, RPGItemComponent.KATANA); public static Item katanaIron = new ItemRPGWeapon(RPGToolMaterial.IRON, RPGItemComponent.KATANA); public static Item katanaGold = new ItemRPGWeapon(RPGToolMaterial.GOLD, RPGItemComponent.KATANA); public static Item katanaDiamond = new ItemRPGWeapon(RPGToolMaterial.DIAMOND, RPGItemComponent.KATANA); public static Item katanaObsidian = new ItemRPGWeapon(RPGToolMaterial.OBSIDIAN, RPGItemComponent.KATANA); public static Item katanaBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.KATANA); public static Item katanaBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.KATANA); public static Item katanaWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.KATANA); public static Item scytheWood = new ItemRPGWeapon(RPGToolMaterial.WOOD, RPGItemComponent.SCYTHE); public static Item scytheStone = new ItemRPGWeapon(RPGToolMaterial.STONE, RPGItemComponent.SCYTHE); public static Item scytheIron = new ItemRPGWeapon(RPGToolMaterial.IRON, RPGItemComponent.SCYTHE); public static Item scytheGold = new ItemRPGWeapon(RPGToolMaterial.GOLD, RPGItemComponent.SCYTHE); public static Item scytheDiamond = new ItemRPGWeapon(RPGToolMaterial.DIAMOND, RPGItemComponent.SCYTHE); public static Item scytheObsidian = new ItemRPGWeapon(RPGToolMaterial.OBSIDIAN, RPGItemComponent.SCYTHE); public static Item scytheBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.SCYTHE); public static Item scytheBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.SCYTHE); public static Item scytheWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.SCYTHE); public static Item hammerWood = new ItemRPGWeapon(RPGToolMaterial.WOOD, RPGItemComponent.HAMMER); public static Item hammerStone = new ItemRPGWeapon(RPGToolMaterial.STONE, RPGItemComponent.HAMMER); public static Item hammerIron = new ItemRPGWeapon(RPGToolMaterial.IRON, RPGItemComponent.HAMMER); public static Item hammerGold = new ItemRPGWeapon(RPGToolMaterial.GOLD, RPGItemComponent.HAMMER); public static Item hammerDiamond = new ItemRPGWeapon(RPGToolMaterial.DIAMOND, RPGItemComponent.HAMMER); public static Item hammerObsidian = new ItemRPGWeapon(RPGToolMaterial.OBSIDIAN, RPGItemComponent.HAMMER); public static Item hammerBedrock = new ItemRPGWeapon(RPGToolMaterial.BEDROCK, RPGItemComponent.HAMMER); public static Item hammerBlackMatter = new ItemRPGWeapon(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.HAMMER); public static Item hammerWhiteMatter = new ItemRPGWeapon(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.HAMMER); public static Item tomahawkWood = new ItemRPGTomahawk(RPGToolMaterial.WOOD, RPGItemComponent.TOMAHAWK); public static Item tomahawkStone = new ItemRPGTomahawk(RPGToolMaterial.STONE, RPGItemComponent.TOMAHAWK); public static Item tomahawkIron = new ItemRPGTomahawk(RPGToolMaterial.IRON, RPGItemComponent.TOMAHAWK); public static Item tomahawkGold = new ItemRPGTomahawk(RPGToolMaterial.GOLD, RPGItemComponent.TOMAHAWK); public static Item tomahawkDiamond = new ItemRPGTomahawk(RPGToolMaterial.DIAMOND, RPGItemComponent.TOMAHAWK); public static Item tomahawkObsidian = new ItemRPGTomahawk(RPGToolMaterial.OBSIDIAN, RPGItemComponent.TOMAHAWK); public static Item tomahawkBedrock = new ItemRPGTomahawk(RPGToolMaterial.BEDROCK, RPGItemComponent.TOMAHAWK); public static Item tomahawkBlackMatter = new ItemRPGTomahawk( RPGToolMaterial.BLACK_MATTER, RPGItemComponent.TOMAHAWK); public static Item tomahawkWhiteMatter = new ItemRPGTomahawk( RPGToolMaterial.WHITE_MATTER, RPGItemComponent.TOMAHAWK); public static Item knifeWood = new ItemRPGKnife(RPGToolMaterial.WOOD, RPGItemComponent.KNIFE); public static Item knifeStone = new ItemRPGKnife(RPGToolMaterial.STONE, RPGItemComponent.KNIFE); public static Item knifeIron = new ItemRPGKnife(RPGToolMaterial.IRON, RPGItemComponent.KNIFE); public static Item knifeGold = new ItemRPGKnife(RPGToolMaterial.GOLD, RPGItemComponent.KNIFE); public static Item knifeDiamond = new ItemRPGKnife(RPGToolMaterial.DIAMOND, RPGItemComponent.KNIFE); public static Item knifeObsidian = new ItemRPGKnife(RPGToolMaterial.OBSIDIAN, RPGItemComponent.KNIFE); public static Item knifeBedrock = new ItemRPGKnife(RPGToolMaterial.BEDROCK, RPGItemComponent.KNIFE); public static Item knifeBlackMatter = new ItemRPGKnife(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.KNIFE); public static Item knifeWhiteMatter = new ItemRPGKnife(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.KNIFE); public static Item staffGold = new ItemRPGStaff(RPGToolMaterial.GOLD, RPGItemComponent.STAFF); public static Item staffDiamond = new ItemRPGStaff(RPGToolMaterial.DIAMOND, RPGItemComponent.STAFF); public static Item staffObsidian = new ItemRPGStaff(RPGToolMaterial.OBSIDIAN, RPGItemComponent.STAFF); public static Item staffBedrock = new ItemRPGStaff(RPGToolMaterial.BEDROCK, RPGItemComponent.STAFF); public static Item staffBlackMatter = new ItemRPGStaff(RPGToolMaterial.BLACK_MATTER, RPGItemComponent.STAFF); public static Item staffWhiteMatter = new ItemRPGStaff(RPGToolMaterial.WHITE_MATTER, RPGItemComponent.STAFF); public static Item powerStaffGold = new ItemPowerStaff(RPGToolMaterial.GOLD, RPGItemComponent.POWER_STAFF); public static Item powerStaffDiamond = new ItemPowerStaff(RPGToolMaterial.DIAMOND, RPGItemComponent.POWER_STAFF); public static Item powerStaffObsidian = new ItemPowerStaff(RPGToolMaterial.OBSIDIAN, RPGItemComponent.POWER_STAFF); public static Item powerStaffBedrock = new ItemPowerStaff(RPGToolMaterial.BEDROCK, RPGItemComponent.POWER_STAFF); public static Item powerStaffBlackMatter = new ItemPowerStaff( RPGToolMaterial.BLACK_MATTER, RPGItemComponent.POWER_STAFF); public static Item powerStaffWhiteMatter = new ItemPowerStaff( RPGToolMaterial.WHITE_MATTER, RPGItemComponent.POWER_STAFF); public static Item axeObsidian = new ItemRPGAxe(RPGToolMaterial.OBSIDIAN); public static Item axeBedrock = new ItemRPGAxe(RPGToolMaterial.BEDROCK); public static Item axeBlackMatter = new ItemRPGAxe(RPGToolMaterial.BLACK_MATTER); public static Item axeWhiteMatter = new ItemRPGAxe(RPGToolMaterial.WHITE_MATTER); public static Item hoeObsidian = new ItemRPGHoe(RPGToolMaterial.OBSIDIAN); public static Item hoeBedrock = new ItemRPGHoe(RPGToolMaterial.BEDROCK); public static Item hoeBlackMatter = new ItemRPGHoe(RPGToolMaterial.BLACK_MATTER); public static Item hoeWhiteMatter = new ItemRPGHoe(RPGToolMaterial.WHITE_MATTER); public static Item pickaxeObsidian = new ItemRPGPickaxe(RPGToolMaterial.OBSIDIAN); public static Item pickaxeBedrock = new ItemRPGPickaxe(RPGToolMaterial.BEDROCK); public static Item pickaxeBlackMatter = new ItemRPGPickaxe(RPGToolMaterial.BLACK_MATTER); public static Item pickaxeWhiteMatter = new ItemRPGPickaxe(RPGToolMaterial.WHITE_MATTER); public static Item shovelObsidian = new ItemRPGSpade(RPGToolMaterial.OBSIDIAN); public static Item shovelBedrock = new ItemRPGSpade(RPGToolMaterial.BEDROCK); public static Item shovelBlackMatter = new ItemRPGSpade(RPGToolMaterial.BLACK_MATTER); public static Item shovelWhiteMatter = new ItemRPGSpade(RPGToolMaterial.WHITE_MATTER); public static Item multitoolWood = new ItemRPGMultiTool(RPGToolMaterial.WOOD); public static Item multitoolStone = new ItemRPGMultiTool(RPGToolMaterial.STONE); public static Item multitoolIron = new ItemRPGMultiTool(RPGToolMaterial.IRON); public static Item multitoolGold = new ItemRPGMultiTool(RPGToolMaterial.GOLD); public static Item multitoolDiamond = new ItemRPGMultiTool(RPGToolMaterial.DIAMOND); public static Item multitoolObsidian = new ItemRPGMultiTool(RPGToolMaterial.OBSIDIAN); public static Item multitoolBedrock = new ItemRPGMultiTool(RPGToolMaterial.BEDROCK); public static Item multitoolBlackMatter = new ItemRPGMultiTool(RPGToolMaterial.BLACK_MATTER); public static Item multitoolWhiteMatter = new ItemRPGMultiTool(RPGToolMaterial.WHITE_MATTER); public static Item[] armorObsidian = ItemRPGArmor.createFullSet(RPGArmorMaterial.OBSIDIAN, RPGArmorComponent.ARMOR); public static Item[] armorBedrock = ItemRPGArmor.createFullSet(RPGArmorMaterial.BEDROCK, RPGArmorComponent.ARMOR); public static Item[] armorBlackMatter = ItemRPGArmor .createFullSet(RPGArmorMaterial.BLACK_MATTER, RPGArmorComponent.ARMOR); public static Item[] armorWhiteMatter = ItemRPGArmor .createFullSet(RPGArmorMaterial.WHITE_MATTER, RPGArmorComponent.ARMOR); public static Item[] mageArmorCloth = ItemMageArmor .createFullSet(RPGArmorMaterial.CLOTH, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorIron = ItemMageArmor .createFullSet(RPGArmorMaterial.IRON, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorGold = ItemMageArmor .createFullSet(RPGArmorMaterial.GOLD, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorDiamond = ItemMageArmor .createFullSet(RPGArmorMaterial.DIAMOND, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorObsidian = ItemMageArmor .createFullSet(RPGArmorMaterial.OBSIDIAN, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorBedrock = ItemMageArmor .createFullSet(RPGArmorMaterial.BEDROCK, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorBlackMatter = ItemMageArmor .createFullSet(RPGArmorMaterial.BLACK_MATTER, RPGArmorComponent.MAGE_ARMOR); public static Item[] mageArmorWhiteMatter = ItemMageArmor .createFullSet(RPGArmorMaterial.WHITE_MATTER, RPGArmorComponent.MAGE_ARMOR);
public static Item shadowBow = new ItemRPGBow(RPGItemComponent.SHADOW_BOW, RPGItemRarity.mythic);
0
2023-10-31 21:00:14+00:00
16k
llllllxy/tiny-jdbc-boot-starter
src/main/java/org/tinycloud/jdbc/support/AbstractSqlSupport.java
[ { "identifier": "Criteria", "path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java", "snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond...
import org.springframework.jdbc.core.*; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.tinycloud.jdbc.criteria.Criteria; import org.tinycloud.jdbc.criteria.LambdaCriteria; import org.tinycloud.jdbc.exception.JdbcException; import org.tinycloud.jdbc.page.IPageHandle; import org.tinycloud.jdbc.page.Page; import org.tinycloud.jdbc.sql.SqlGenerator; import org.tinycloud.jdbc.sql.SqlProvider; import java.lang.reflect.ParameterizedType; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.*;
13,834
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate();
package org.tinycloud.jdbc.support; /** * jdbc抽象类,给出默认的支持 * * @author liuxingyu01 * @since 2022-03-11-16:49 **/ public abstract class AbstractSqlSupport<T, ID> implements ISqlSupport<T, ID>, IObjectSupport<T, ID> { protected abstract JdbcTemplate getJdbcTemplate();
protected abstract IPageHandle getPageHandle();
3
2023-10-25 14:44:59+00:00
16k
ansforge/SAMU-Hub-Modeles
src/main/java/com/hubsante/model/cisu/CreateCase.java
[ { "identifier": "AdditionalInformation", "path": "src/main/java/com/hubsante/model/cisu/AdditionalInformation.java", "snippet": "@JsonPropertyOrder({AdditionalInformation.JSON_PROPERTY_CUSTOM_MAP})\n@JsonTypeName(\"additionalInformation\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n\npublic class Add...
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.dataformat.xml.annotation.*; import com.hubsante.model.cisu.AdditionalInformation; import com.hubsante.model.cisu.Alert; import com.hubsante.model.cisu.Location; import com.hubsante.model.cisu.Qualification; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Arrays; import java.util.List; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty;
10,942
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.cisu; /** * CreateCase */ @JsonPropertyOrder( {CreateCase.JSON_PROPERTY_CASE_ID, CreateCase.JSON_PROPERTY_SENDER_CASE_ID, CreateCase.JSON_PROPERTY_CREATION, CreateCase.JSON_PROPERTY_REFERENCE_VERSION, CreateCase.JSON_PROPERTY_QUALIFICATION, CreateCase.JSON_PROPERTY_LOCATION, CreateCase.JSON_PROPERTY_INITIAL_ALERT, CreateCase.JSON_PROPERTY_NEW_ALERT, CreateCase.JSON_PROPERTY_ADDITIONAL_INFORMATION, CreateCase.JSON_PROPERTY_FREETEXT}) @JsonTypeName("createCase") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CreateCase { public static final String JSON_PROPERTY_CASE_ID = "caseId"; private String caseId; public static final String JSON_PROPERTY_SENDER_CASE_ID = "senderCaseId"; private String senderCaseId; public static final String JSON_PROPERTY_CREATION = "creation"; private OffsetDateTime creation; public static final String JSON_PROPERTY_REFERENCE_VERSION = "referenceVersion"; private String referenceVersion; public static final String JSON_PROPERTY_QUALIFICATION = "qualification"; private Qualification qualification; public static final String JSON_PROPERTY_LOCATION = "location"; private Location location; public static final String JSON_PROPERTY_INITIAL_ALERT = "initialAlert";
/** * Copyright © 2023-2024 Agence du Numerique en Sante (ANS) * * 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. */ /* * * * * * * * NOTE: This class is auto generated by OpenAPI Generator * (https://openapi-generator.tech). https://openapi-generator.tech Do not edit * the class manually. */ package com.hubsante.model.cisu; /** * CreateCase */ @JsonPropertyOrder( {CreateCase.JSON_PROPERTY_CASE_ID, CreateCase.JSON_PROPERTY_SENDER_CASE_ID, CreateCase.JSON_PROPERTY_CREATION, CreateCase.JSON_PROPERTY_REFERENCE_VERSION, CreateCase.JSON_PROPERTY_QUALIFICATION, CreateCase.JSON_PROPERTY_LOCATION, CreateCase.JSON_PROPERTY_INITIAL_ALERT, CreateCase.JSON_PROPERTY_NEW_ALERT, CreateCase.JSON_PROPERTY_ADDITIONAL_INFORMATION, CreateCase.JSON_PROPERTY_FREETEXT}) @JsonTypeName("createCase") @JsonInclude(JsonInclude.Include.NON_EMPTY) public class CreateCase { public static final String JSON_PROPERTY_CASE_ID = "caseId"; private String caseId; public static final String JSON_PROPERTY_SENDER_CASE_ID = "senderCaseId"; private String senderCaseId; public static final String JSON_PROPERTY_CREATION = "creation"; private OffsetDateTime creation; public static final String JSON_PROPERTY_REFERENCE_VERSION = "referenceVersion"; private String referenceVersion; public static final String JSON_PROPERTY_QUALIFICATION = "qualification"; private Qualification qualification; public static final String JSON_PROPERTY_LOCATION = "location"; private Location location; public static final String JSON_PROPERTY_INITIAL_ALERT = "initialAlert";
private Alert initialAlert;
1
2023-10-25 14:24:31+00:00
16k
sschr15/rgml-quilt
client/src/main/risugami/org/duvetmc/rgml/mixin/CrashScreenMixin.java
[ { "identifier": "Constants", "path": "client/src/main/java/org/duvetmc/mods/rgmlquilt/util/Constants.java", "snippet": "public class Constants {\n\tpublic static final String MOD_ID = \"rgml-quilt\";\n\tpublic static final String VERSION = QuiltLoader.getModContainer(MOD_ID).get().metadata().version().t...
import net.minecraft.unmapped.C_6406257; import org.duvetmc.mods.rgmlquilt.util.Constants; import org.duvetmc.rgml.BaseMod; import org.duvetmc.rgml.ModLoader; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.Constant; import org.spongepowered.asm.mixin.injection.ModifyConstant; import java.util.ArrayList; import java.util.List;
12,306
package org.duvetmc.rgml.mixin; @Mixin(C_6406257.class) public class CrashScreenMixin { @ModifyConstant(method = "<init>", constant = @Constant(stringValue = "OS: ")) private String rgml$injectRgmlMods(String os) { List<String> lines = new ArrayList<>(); lines.add("ModLoader Beta 1.8.1"); lines.add("RGML-Quilt " + Constants.VERSION);
package org.duvetmc.rgml.mixin; @Mixin(C_6406257.class) public class CrashScreenMixin { @ModifyConstant(method = "<init>", constant = @Constant(stringValue = "OS: ")) private String rgml$injectRgmlMods(String os) { List<String> lines = new ArrayList<>(); lines.add("ModLoader Beta 1.8.1"); lines.add("RGML-Quilt " + Constants.VERSION);
lines.add("Mods loaded: " + ModLoader.getLoadedMods().size());
2
2023-10-31 14:17:42+00:00
16k
simply-kel/AlinLib
src/main/java/ru/kelcuprum/alinlib/gui/screens/AlinaDemoScreen.java
[ { "identifier": "AlinLib", "path": "src/main/java/ru/kelcuprum/alinlib/AlinLib.java", "snippet": "public class AlinLib implements ClientModInitializer {\r\n public static final Logger LOG = LogManager.getLogger(\"AlinaLib\");\r\n public static Config bariumConfig = new Config(\"config/AlibLib/conf...
import net.minecraft.Util; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.AbstractWidget; import net.minecraft.client.gui.screens.*; import net.minecraft.network.chat.Component; import net.minecraft.resources.ResourceLocation; import ru.kelcuprum.alinlib.AlinLib; import ru.kelcuprum.alinlib.Colors; import ru.kelcuprum.alinlib.config.Localization; import ru.kelcuprum.alinlib.gui.InterfaceUtils; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonSprite; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxString; import ru.kelcuprum.alinlib.gui.components.sliders.SliderInteger; import ru.kelcuprum.alinlib.gui.components.sliders.SliderPercent; import ru.kelcuprum.alinlib.gui.components.text.TextBox; import ru.kelcuprum.alinlib.gui.components.buttons.ButtonBoolean; import ru.kelcuprum.alinlib.gui.components.buttons.Button; import ru.kelcuprum.alinlib.gui.components.editbox.EditBoxColor; import ru.kelcuprum.alinlib.gui.components.selector.SelectorStringButton; import ru.kelcuprum.alinlib.gui.toast.AlinaToast; import java.util.ArrayList; import java.util.List;
12,896
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png");
package ru.kelcuprum.alinlib.gui.screens; public class AlinaDemoScreen extends Screen { private final Screen parent; private static final ResourceLocation icon = new ResourceLocation("alinlib", "textures/gui/widget/test/well.png");
private static final Component TITLE = Component.literal("AlinLib");
0
2023-10-29 13:30:26+00:00
16k
LeoK99/swtw45WS21_reupload
src/main/java/com/buschmais/frontend/components/CreateNewGroupDialog.java
[ { "identifier": "AccessGroup", "path": "src/main/java/com/buschmais/backend/adrAccess/AccessGroup.java", "snippet": "@Document\n@Data\npublic class AccessGroup implements Comparable<AccessGroup> {\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsAndHashCode.Exclude\n\t@Id\n\tprivate String id;\n\n\t@Indexed\...
import com.buschmais.backend.adrAccess.AccessGroup; import com.buschmais.backend.adrAccess.AccessRights; import com.buschmais.backend.adrAccess.dataAccess.ADRAccessDao; import com.buschmais.backend.users.User; import com.buschmais.backend.users.dataAccess.UserDao; import com.buschmais.frontend.broadcasting.BroadcastListener; import com.buschmais.frontend.broadcasting.Broadcaster; import com.buschmais.frontend.vars.StringConstantsFrontend; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.checkbox.CheckboxGroup; import com.vaadin.flow.component.checkbox.CheckboxGroupVariant; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.icon.Icon; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import lombok.NonNull; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.buschmais.frontend.vars.StringConstantsFrontend.*;
12,163
package com.buschmais.frontend.components; @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-group-styles.css", themeFor = "vaadin-checkbox-group") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-styles.css", themeFor = "vaadin-checkbox") public class CreateNewGroupDialog extends Dialog { private final UserDao userDao; private final ADRAccessDao adrAccessDao; private VerticalLayout mainLayout; private HorizontalLayout manageLayout; private VerticalLayout boxandrightsLayout; private HorizontalLayout buttonsLayout; private Div membersDiv; private TextField groupname; private Button createButton; private Button cancelButton; private ComboBox<User> users; private CheckboxGroup<String> rightsbox; private Set<User> choosedUsers, selectUser; private Set<String> choosedRights; private List<String> rightsList; public CreateNewGroupDialog(@NonNull UserDao userDao, @NonNull ADRAccessDao adrAccessDao) { super(); this.userDao = userDao; this.adrAccessDao = adrAccessDao; this.setModal(true); this.setSizeUndefined(); this.setCloseOnEsc(true); this.setCloseOnOutsideClick(true); this.setResizable(true); this.setDraggable(true); this.setMinWidth("min-content"); this.setMinHeight("min-content"); this.setWidth("initial"); this.setMaxWidth("40%"); this.setHeight("initial"); this.setMaxHeight("90%"); mainLayout = new VerticalLayout(); manageLayout = new HorizontalLayout(); boxandrightsLayout = new VerticalLayout(); buttonsLayout = new HorizontalLayout(); membersDiv = new Div(); groupname = new TextField(); groupname.setLabel(StringConstantsFrontend.CREATENEWGROUP_NAME); groupname.setClearButtonVisible(true); manageLayout.add(membersDiv, boxandrightsLayout); mainLayout.add(groupname); mainLayout.add(manageLayout, buttonsLayout); this.add(mainLayout); selectUser = new HashSet<>(); choosedUsers = new HashSet<>(); usersboxConfigure(); rightsbox = new CheckboxGroup<>(); choosedRights = new HashSet<>(); rightsboxConfigure(); createButton = new Button(GENERAL_DIALOG_BUTTON_SAVE); createButton.addClassName("confirm-button"); cancelButton = new Button(GENERAL_DIALOG_BUTTON_CANCEL); cancelButton.addClassName("cancel-button"); buttonsLayout.add(createButton, cancelButton); buttonsConfigure(); } private void usersboxConfigure(){ selectUser.addAll(this.userDao.findAll()); users = new ComboBox<>(StringConstantsFrontend.CREATENEWGROUP_USERS); ComboBox.ItemFilter<User> filter = (user, filterString) -> user.getUserName().toLowerCase().startsWith(filterString.toLowerCase()); users.setItems(filter, selectUser); users.setItemLabelGenerator(User::getUserName); users.addValueChangeListener(event -> { if (event.getValue() != null) { User u = event.getValue(); Span userSpan = new Span(new Icon(VaadinIcon.CLOSE), new Span(u.getUserName())); userSpan.getElement().getThemeList().add("badge primary"); choosedUsers.add(u); membersDiv.add(userSpan); userSpan.addClickListener(e -> { choosedUsers.remove(u); membersDiv.remove(userSpan); selectUser.add(u); users.setItems(filter, selectUser); }); selectUser.remove(u); users.setItems(filter, selectUser); } }); boxandrightsLayout.add(users); } private void rightsboxConfigure(){ rightsbox.setLabel(StringConstantsFrontend.CREATENEWGROUP_RIGHTS); rightsbox.addThemeVariants(CheckboxGroupVariant.LUMO_VERTICAL); rightsList = new ArrayList<>(); rightsList.add(GROUP_READABLE); rightsList.add(GROUP_WRITABLE); rightsList.add(GROUP_VOTABLE); rightsbox.setItems(rightsList); boxandrightsLayout.add(rightsbox); } private void buttonsConfigure(){ createButton.addClickListener(event -> { synchronized (adrAccessDao) { if(!groupname.isEmpty()){
package com.buschmais.frontend.components; @CssImport(value = "./themes/adr-workbench/vaadin-components/buttons.css") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-group-styles.css", themeFor = "vaadin-checkbox-group") @CssImport(value = "./themes/adr-workbench/vaadin-components/vaadin-checkbox-styles.css", themeFor = "vaadin-checkbox") public class CreateNewGroupDialog extends Dialog { private final UserDao userDao; private final ADRAccessDao adrAccessDao; private VerticalLayout mainLayout; private HorizontalLayout manageLayout; private VerticalLayout boxandrightsLayout; private HorizontalLayout buttonsLayout; private Div membersDiv; private TextField groupname; private Button createButton; private Button cancelButton; private ComboBox<User> users; private CheckboxGroup<String> rightsbox; private Set<User> choosedUsers, selectUser; private Set<String> choosedRights; private List<String> rightsList; public CreateNewGroupDialog(@NonNull UserDao userDao, @NonNull ADRAccessDao adrAccessDao) { super(); this.userDao = userDao; this.adrAccessDao = adrAccessDao; this.setModal(true); this.setSizeUndefined(); this.setCloseOnEsc(true); this.setCloseOnOutsideClick(true); this.setResizable(true); this.setDraggable(true); this.setMinWidth("min-content"); this.setMinHeight("min-content"); this.setWidth("initial"); this.setMaxWidth("40%"); this.setHeight("initial"); this.setMaxHeight("90%"); mainLayout = new VerticalLayout(); manageLayout = new HorizontalLayout(); boxandrightsLayout = new VerticalLayout(); buttonsLayout = new HorizontalLayout(); membersDiv = new Div(); groupname = new TextField(); groupname.setLabel(StringConstantsFrontend.CREATENEWGROUP_NAME); groupname.setClearButtonVisible(true); manageLayout.add(membersDiv, boxandrightsLayout); mainLayout.add(groupname); mainLayout.add(manageLayout, buttonsLayout); this.add(mainLayout); selectUser = new HashSet<>(); choosedUsers = new HashSet<>(); usersboxConfigure(); rightsbox = new CheckboxGroup<>(); choosedRights = new HashSet<>(); rightsboxConfigure(); createButton = new Button(GENERAL_DIALOG_BUTTON_SAVE); createButton.addClassName("confirm-button"); cancelButton = new Button(GENERAL_DIALOG_BUTTON_CANCEL); cancelButton.addClassName("cancel-button"); buttonsLayout.add(createButton, cancelButton); buttonsConfigure(); } private void usersboxConfigure(){ selectUser.addAll(this.userDao.findAll()); users = new ComboBox<>(StringConstantsFrontend.CREATENEWGROUP_USERS); ComboBox.ItemFilter<User> filter = (user, filterString) -> user.getUserName().toLowerCase().startsWith(filterString.toLowerCase()); users.setItems(filter, selectUser); users.setItemLabelGenerator(User::getUserName); users.addValueChangeListener(event -> { if (event.getValue() != null) { User u = event.getValue(); Span userSpan = new Span(new Icon(VaadinIcon.CLOSE), new Span(u.getUserName())); userSpan.getElement().getThemeList().add("badge primary"); choosedUsers.add(u); membersDiv.add(userSpan); userSpan.addClickListener(e -> { choosedUsers.remove(u); membersDiv.remove(userSpan); selectUser.add(u); users.setItems(filter, selectUser); }); selectUser.remove(u); users.setItems(filter, selectUser); } }); boxandrightsLayout.add(users); } private void rightsboxConfigure(){ rightsbox.setLabel(StringConstantsFrontend.CREATENEWGROUP_RIGHTS); rightsbox.addThemeVariants(CheckboxGroupVariant.LUMO_VERTICAL); rightsList = new ArrayList<>(); rightsList.add(GROUP_READABLE); rightsList.add(GROUP_WRITABLE); rightsList.add(GROUP_VOTABLE); rightsbox.setItems(rightsList); boxandrightsLayout.add(rightsbox); } private void buttonsConfigure(){ createButton.addClickListener(event -> { synchronized (adrAccessDao) { if(!groupname.isEmpty()){
AccessRights ar = new AccessRights(false,false,false);
1
2023-10-25 15:18:06+00:00
16k
Java-Game-Engine-Merger/Libgdx-Processing
framework0001/framework0001-processing/src/main/java/pama1234/processing/game/duel/GameSystem.java
[ { "identifier": "Tools", "path": "framework0001/framework0001-processing/src/main/java/pama1234/math/Tools.java", "snippet": "public class Tools{\n public static float msq(float in) {\n if(in<0) return -(in*in);\n return in*in;\n }\n public static float sq(float a) {\n return a*a;\n }\n pu...
import pama1234.math.Tools; import pama1234.processing.game.duel.util.actor.ActorGroup; import pama1234.processing.game.duel.util.actor.PlayerActor; import pama1234.processing.game.duel.util.ai.ComputerPlayerEngine; import pama1234.processing.game.duel.util.ai.PlayerEngine; import pama1234.processing.game.duel.util.graphics.DrawUtil; import pama1234.processing.game.duel.util.graphics.GameBackground; import pama1234.processing.game.duel.util.graphics.Particle; import pama1234.processing.game.duel.util.graphics.ParticleBuilder; import pama1234.processing.game.duel.util.graphics.ParticleSet; import pama1234.processing.game.duel.util.player.DamagedPlayerActorState; import pama1234.processing.game.duel.util.player.DrawBowPlayerActorState; import pama1234.processing.game.duel.util.player.DrawLongbowPlayerActorState; import pama1234.processing.game.duel.util.player.DrawShortbowPlayerActorState; import pama1234.processing.game.duel.util.player.HumanPlayerEngine; import pama1234.processing.game.duel.util.player.MovePlayerActorState; import pama1234.processing.game.duel.util.state.GameSystemState; import pama1234.processing.game.duel.util.state.StartGameState; import processing.core.PConstants;
13,571
package pama1234.processing.game.duel; public final class GameSystem{ private final Duel duel; public final ActorGroup myGroup,otherGroup; public final ParticleSet commonParticleSet; public GameSystemState currentState; public float screenShakeValue; public final DamagedPlayerActorState damagedState; public final GameBackground currentBackground; public final boolean demoPlay; public boolean showsInstructionWindow; public GameSystem(Duel duel,boolean demo,boolean instruction) { this.duel=duel; // prepare ActorGroup myGroup=new ActorGroup(); otherGroup=new ActorGroup(); myGroup.enemyGroup=otherGroup; otherGroup.enemyGroup=myGroup; // prepare PlayerActorState final MovePlayerActorState moveState=new MovePlayerActorState(); final DrawBowPlayerActorState drawShortbowState=new DrawShortbowPlayerActorState(duel); final DrawBowPlayerActorState drawLongbowState=new DrawLongbowPlayerActorState(duel); damagedState=new DamagedPlayerActorState(duel); moveState.drawShortbowState=drawShortbowState; moveState.drawLongbowState=drawLongbowState; drawShortbowState.moveState=moveState; drawLongbowState.moveState=moveState; damagedState.moveState=moveState; // prepare PlayerActor PlayerEngine myEngine; if(demo) myEngine=new ComputerPlayerEngine(duel); else myEngine=new HumanPlayerEngine(duel.currentKeyInput); PlayerActor myPlayer=new PlayerActor(duel,myEngine,Tools.color(255.0f)); myPlayer.xPosition=Duel.INTERNAL_CANVAS_SIDE_LENGTH*0.5f; myPlayer.yPosition=Duel.INTERNAL_CANVAS_SIDE_LENGTH-100.0f; myPlayer.state=moveState; myGroup.setPlayer(myPlayer); PlayerEngine otherEngine=new ComputerPlayerEngine(duel); PlayerActor otherPlayer=new PlayerActor(duel,otherEngine,Tools.color(0.0f)); otherPlayer.xPosition=Duel.INTERNAL_CANVAS_SIDE_LENGTH*0.5f; otherPlayer.yPosition=100.0f; otherPlayer.state=moveState; otherGroup.setPlayer(otherPlayer); // other commonParticleSet=new ParticleSet(duel,2048);
package pama1234.processing.game.duel; public final class GameSystem{ private final Duel duel; public final ActorGroup myGroup,otherGroup; public final ParticleSet commonParticleSet; public GameSystemState currentState; public float screenShakeValue; public final DamagedPlayerActorState damagedState; public final GameBackground currentBackground; public final boolean demoPlay; public boolean showsInstructionWindow; public GameSystem(Duel duel,boolean demo,boolean instruction) { this.duel=duel; // prepare ActorGroup myGroup=new ActorGroup(); otherGroup=new ActorGroup(); myGroup.enemyGroup=otherGroup; otherGroup.enemyGroup=myGroup; // prepare PlayerActorState final MovePlayerActorState moveState=new MovePlayerActorState(); final DrawBowPlayerActorState drawShortbowState=new DrawShortbowPlayerActorState(duel); final DrawBowPlayerActorState drawLongbowState=new DrawLongbowPlayerActorState(duel); damagedState=new DamagedPlayerActorState(duel); moveState.drawShortbowState=drawShortbowState; moveState.drawLongbowState=drawLongbowState; drawShortbowState.moveState=moveState; drawLongbowState.moveState=moveState; damagedState.moveState=moveState; // prepare PlayerActor PlayerEngine myEngine; if(demo) myEngine=new ComputerPlayerEngine(duel); else myEngine=new HumanPlayerEngine(duel.currentKeyInput); PlayerActor myPlayer=new PlayerActor(duel,myEngine,Tools.color(255.0f)); myPlayer.xPosition=Duel.INTERNAL_CANVAS_SIDE_LENGTH*0.5f; myPlayer.yPosition=Duel.INTERNAL_CANVAS_SIDE_LENGTH-100.0f; myPlayer.state=moveState; myGroup.setPlayer(myPlayer); PlayerEngine otherEngine=new ComputerPlayerEngine(duel); PlayerActor otherPlayer=new PlayerActor(duel,otherEngine,Tools.color(0.0f)); otherPlayer.xPosition=Duel.INTERNAL_CANVAS_SIDE_LENGTH*0.5f; otherPlayer.yPosition=100.0f; otherPlayer.state=moveState; otherGroup.setPlayer(otherPlayer); // other commonParticleSet=new ParticleSet(duel,2048);
currentState=new StartGameState(duel);
17
2023-10-27 05:47:39+00:00
16k
llllllxy/tinycloud
tinycloud-user/src/main/java/org/tinycloud/user/service/impl/UcUserServiceImpl.java
[ { "identifier": "UcUser", "path": "tinycloud-bean/src/main/java/org/tinycloud/bean/entity/UcUser.java", "snippet": "@TableName(\"t_uc_user\")\n@ApiModel(value = \"UcUser对象\", description = \"系统用户信息表\")\npublic class UcUser implements Serializable {\n private static final long serialVersionUID = 1L;\n...
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.tinycloud.bean.entity.UcUser; import org.tinycloud.bean.param.UcUserPageQuery; import org.tinycloud.bean.vo.UcUserVo; import org.tinycloud.common.consts.GlobalConstant; import org.tinycloud.common.model.PageModel; import org.tinycloud.common.utils.LambdaUtils; import org.tinycloud.common.utils.StringUtils; import org.tinycloud.common.utils.bean.BeanUtils; import org.tinycloud.user.mapper.UcUserMapper; import org.tinycloud.user.service.UcUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.stream.Collectors;
11,849
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) {
package org.tinycloud.user.service.impl; @Service public class UcUserServiceImpl implements UcUserService { @Autowired private UcUserMapper ucUserMapper; /** * 根据id查询详情 * @param userId * @return */ @Override public UcUserVo detail(String userId) { UcUser ucUser = this.ucUserMapper.selectOne(Wrappers.<UcUser>lambdaQuery() .eq(UcUser::getUserId, userId) .eq(UcUser::getDelFlag, GlobalConstant.NOT_DELETED)); if (ucUser != null) {
return BeanUtils.transformBean(ucUser, UcUserVo.class);
7
2023-10-28 02:05:15+00:00
16k
llllllxy/bluewind-base
src/main/java/com/bluewind/base/module/system/auth/controller/AuthController.java
[ { "identifier": "BaseController", "path": "src/main/java/com/bluewind/base/common/base/BaseController.java", "snippet": "public abstract class BaseController {\n private static final Logger logger = LoggerFactory.getLogger(BaseController.class);\n public static final String RESULT_ROWS = \"rows\";...
import com.bluewind.base.common.base.BaseController; import com.bluewind.base.common.base.Result; import com.bluewind.base.common.config.auth.constant.AuthConstant; import com.bluewind.base.common.config.auth.util.AuthUtil; import com.bluewind.base.common.config.auth.util.PasswordUtils; import com.bluewind.base.common.config.auth.util.UserInfoUtil; import com.bluewind.base.common.util.redis.RedisUtils; import com.bluewind.base.common.util.web.CookieUtils; import com.bluewind.base.module.system.auth.service.AuthService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.subject.Subject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.UUID;
11,740
package com.bluewind.base.module.system.auth.controller; /** * @author liuxingyu01 * @date 2022-08-26 15:05 * @description 本地后台登录管理 **/ @RestController @Api(value = "本地后台登录管理", tags = "本地后台登录管理") public class AuthController extends BaseController { final static Logger logger = LoggerFactory.getLogger(AuthController.class); @Autowired private RedisUtils redisUtils; @Autowired private AuthService authService; @ApiOperation(value = "登录") @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET}) @ResponseBody public Result login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password, @RequestParam(value = "rememberMe", required = false) String rememberMe, HttpServletResponse response) { if (StringUtils.isBlank(username)) { return Result.error("账号不能为空!"); } if (StringUtils.isBlank(password)) { return Result.error("密码不能为空!"); } Subject subject = SecurityUtils.getSubject(); // 使用shiro认证
package com.bluewind.base.module.system.auth.controller; /** * @author liuxingyu01 * @date 2022-08-26 15:05 * @description 本地后台登录管理 **/ @RestController @Api(value = "本地后台登录管理", tags = "本地后台登录管理") public class AuthController extends BaseController { final static Logger logger = LoggerFactory.getLogger(AuthController.class); @Autowired private RedisUtils redisUtils; @Autowired private AuthService authService; @ApiOperation(value = "登录") @RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET}) @ResponseBody public Result login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password, @RequestParam(value = "rememberMe", required = false) String rememberMe, HttpServletResponse response) { if (StringUtils.isBlank(username)) { return Result.error("账号不能为空!"); } if (StringUtils.isBlank(password)) { return Result.error("密码不能为空!"); } Subject subject = SecurityUtils.getSubject(); // 使用shiro认证
UsernamePasswordToken userNamePasswordToken = new UsernamePasswordToken(username, PasswordUtils.getPassword(password));
4
2023-10-26 10:02:07+00:00
16k
danielbatres/orthodontic-dentistry-clinical-management
src/com/view/readPct/Pacientes.java
[ { "identifier": "ApplicationContext", "path": "src/com/context/ApplicationContext.java", "snippet": "public class ApplicationContext {\r\n public static SesionUsuario sesionUsuario;\r\n public static LoadingApp loading = new LoadingApp();\r\n public static LoadingApplication loadingApplication ...
import com.context.ApplicationContext; import com.context.ChoosedPalette; import com.helper.PacienteHelper; import com.utils.Styles; import com.utils.Tools; import javax.swing.JPanel; import javax.swing.border.MatteBorder;
13,238
package com.view.readPct; /** * * @author Daniel Batres * @version 1.0.0 * @since 18/09/22 */ public class Pacientes extends Styles { /** * Creates new form Pacientes */ public Pacientes() { initComponents(); styleMyComponentBaby(); setData(); } public void setData() {
package com.view.readPct; /** * * @author Daniel Batres * @version 1.0.0 * @since 18/09/22 */ public class Pacientes extends Styles { /** * Creates new form Pacientes */ public Pacientes() { initComponents(); styleMyComponentBaby(); setData(); } public void setData() {
ApplicationContext.pacientesListados.clear();
0
2023-10-26 19:35:40+00:00
16k
dawex/sigourney
trust-framework/verifiable-credentials-model/src/main/java/com/dawex/sigourney/trustframework/vc/model/v2310/serialization/JacksonModuleFactory.java
[ { "identifier": "FormatProvider", "path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/FormatProvider.java", "snippet": "public interface FormatProvider {\n\n\t/**\n\t * Returns the format matching the specified format name\n\...
import com.dawex.sigourney.trustframework.vc.core.Proof; import com.dawex.sigourney.trustframework.vc.core.SignedObject; import com.dawex.sigourney.trustframework.vc.core.jsonld.annotation.JsonLdContexts; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.FormatProvider; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdContextsSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.JsonLdSerializer; import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.SignedObjectJsonLdSerializer; import com.dawex.sigourney.trustframework.vc.model.shared.Did; import com.dawex.sigourney.trustframework.vc.model.shared.JsonWebKey2020; import com.dawex.sigourney.trustframework.vc.model.v2310.common.Address; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.AggregationOf; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.DataProductVerifiableCredential; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Distribution; import com.dawex.sigourney.trustframework.vc.model.v2310.dataproduct.Location; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationCredentialSubject; import com.dawex.sigourney.trustframework.vc.model.v2310.organisation.OrganisationVerifiableCredential; import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.module.SimpleModule; import java.util.function.Supplier;
13,177
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider)); module.addSerializer(OrganisationCredentialSubject.class, new JsonLdSerializer<>(OrganisationCredentialSubject.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier)); module.addSerializer(OrganisationVerifiableCredential.class, new JsonLdSerializer<>(OrganisationVerifiableCredential.class, formatProvider)); module.addSerializer(Proof.class, new JsonLdSerializer<>(Proof.class, formatProvider)); module.addSerializer(SignedObject.class, new SignedObjectJsonLdSerializer(formatProvider)); return module; } /** * Create a configured Jackson module for serializing data product verifiable credentials */ public static Module dataProductSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(AggregationOf.class, new JsonLdSerializer<>(AggregationOf.class, formatProvider)); module.addSerializer(DataProductCredentialSubject.class, new JsonLdSerializer<>(DataProductCredentialSubject.class, formatProvider)); module.addSerializer(Distribution.class, new JsonLdSerializer<>(Distribution.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier)); module.addSerializer(Location.class, new JsonLdSerializer<>(Location.class, formatProvider));
package com.dawex.sigourney.trustframework.vc.model.v2310.serialization; public class JacksonModuleFactory { /** * Create a configured Jackson module for serializing organisation verifiable credentials */ public static Module organisationSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(Address.class, new JsonLdSerializer<>(Address.class, formatProvider)); module.addSerializer(OrganisationCredentialSubject.class, new JsonLdSerializer<>(OrganisationCredentialSubject.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier)); module.addSerializer(OrganisationVerifiableCredential.class, new JsonLdSerializer<>(OrganisationVerifiableCredential.class, formatProvider)); module.addSerializer(Proof.class, new JsonLdSerializer<>(Proof.class, formatProvider)); module.addSerializer(SignedObject.class, new SignedObjectJsonLdSerializer(formatProvider)); return module; } /** * Create a configured Jackson module for serializing data product verifiable credentials */ public static Module dataProductSerializationModule(FormatProvider formatProvider, Supplier<String> baseIriSupplier) { final SimpleModule module = new SimpleModule(); module.addSerializer(AggregationOf.class, new JsonLdSerializer<>(AggregationOf.class, formatProvider)); module.addSerializer(DataProductCredentialSubject.class, new JsonLdSerializer<>(DataProductCredentialSubject.class, formatProvider)); module.addSerializer(Distribution.class, new JsonLdSerializer<>(Distribution.class, formatProvider)); module.addSerializer(JsonLdContexts.class, new JsonLdContextsSerializer(baseIriSupplier)); module.addSerializer(Location.class, new JsonLdSerializer<>(Location.class, formatProvider));
module.addSerializer(DataProductVerifiableCredential.class,
9
2023-10-25 16:10:40+00:00
16k
inceptive-tech/ENTSOEDataRetrieval
src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/ENTSOEDataFetcher.java
[ { "identifier": "DataRetrievalRuntimeException", "path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/exceptions/DataRetrievalRuntimeException.java", "snippet": "public class DataRetrievalRuntimeException extends RuntimeException{\n private static final Logger LOGGER = LogManager.getLogge...
import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.xml.bind.DataBindingException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import tech.inceptive.ai4czc.entsoedataretrieval.exceptions.DataRetrievalRuntimeException; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Area; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ColumnType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ContractMarketAgreement; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.DocumentType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.Params; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.inputs.ProcessType; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.GLMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.PublicationMarketDocument; import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument;
14,256
return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<PublicationMarketDocument> fetchPhysicalFlows(Area inDomain, Area outDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart1 = checker.checkAvailability("12.1.G", periodStart, inDomain); LocalDateTime dataStart2 = checker.checkAvailability("12.1.G", periodStart, outDomain); LocalDateTime dataStart; if (dataStart1.equals(dataStart2)) { dataStart = dataStart1; } else if (dataStart1.isAfter(dataStart2)) { dataStart = dataStart1; } else { dataStart = dataStart2; } LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toHours() < 24) { LOGGER.warn("Error, uncorrect duration. Expected at least 24 hours but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.AGGREGATED_ENERGY_DATA_REPORT.getId()); params.put(Params.IN_DOMAIN.getValue(), inDomain.getId()); params.put(Params.OUT_DOMAIN.getValue(), outDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String erroMsg = "Unable to correctly retrieve physical flows from " + outDomain.getPrettyName() + " to " + inDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, erroMsg, PublicationMarketDocument.class); } /** * Fetchs the transmission grid outages. * * @param inDomain * @param outDomain * @param periodStart * @param periodEnd * @return One document per outage (can be a lot) */ public List<UnavailabilityMarketDocument> fetchTransmissionGridOutages(Area inDomain, Area outDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("10.1.A&B", periodStart, inDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return new ArrayList<>(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return new ArrayList<>(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.TRANSMISSION_UNAVAILABILITY.getId()); params.put(Params.IN_DOMAIN.getValue(), inDomain.getId()); params.put(Params.OUT_DOMAIN.getValue(), outDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); try { return bridge.doZipGetOperation(params, BASE_URL, UnavailabilityMarketDocument.class); } catch (DataRetrievalRuntimeException ex) { LOGGER.catching(ex); LOGGER.warn("Unable to correctly retrieve outages between " + inDomain.getPrettyName() + " and " + outDomain.getPrettyName() + " for time between " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " and " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME)); return new ArrayList<>(); } } public List<UnavailabilityMarketDocument> fetchGenerationUnitOutages(Area biddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("15.1.A&B", periodStart, biddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return new ArrayList<>(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return new ArrayList<>(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.GENERATION_UNAVAILABILITY.getId()); params.put(Params.BIDDING_ZONE_DOMAIN.getValue(), biddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); try { return bridge.doZipGetOperation(params, BASE_URL, UnavailabilityMarketDocument.class); } catch (DataRetrievalRuntimeException ex) { LOGGER.catching(ex); LOGGER.warn("Unable to correctly retrieve generation outages at " + biddingZoneDomain.getPrettyName() + " for time between " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " and " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME)); return new ArrayList<>(); } } public Optional<PublicationMarketDocument> fetchWeekAheadCapacityForecast(Area inDomain, Area outDomain, LocalDateTime periodStart, LocalDateTime periodEnd) {
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package tech.inceptive.ai4czc.entsoedataretrieval.fetcher; /** * The fetcher using https://transparency.entsoe.eu/content/static_content/Static%20content/web%20api/Guide.html * allowing to retrieve data from all the suported API. This class only presents the API of what you can get, and return * the objects or nothing if there was a fetch problem. * * @author Andres Bel Alonso */ public class ENTSOEDataFetcher { private static final Logger LOGGER = LogManager.getLogger(ENTSOEDataFetcher.class); public static String BASE_URL = "https://web-api.tp.entsoe.eu/api"; private String authToken; private HttpBridge bridge; private DisponibilityChecker checker; public ENTSOEDataFetcher(String authToken, boolean useRequestCache) { this.authToken = authToken; this.bridge = new HttpBridge(useRequestCache); // TODO : fix server URL this.checker = new DisponibilityChecker(); } /** * One year limitation applies. Fetchs actual load (documentType : A65, ProcessType : A16) * * @return */ public Optional<GLMarketDocument> fetchActualLoad(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.A", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toMinutes() < 60) { LOGGER.warn("Error, uncorrect duration. Expected at least 60 minutes but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch actual load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchDayAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.B", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toHours() < 24) { LOGGER.warn("Error, uncorrect duration. Expected at least 24 hours but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.DAY_AHEAD.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); GLMarketDocument doc = null; String msg = "Unable to correctly fetch day ahead load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchWeekAheadLoadForecast(Area outBiddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("6.1.C", periodStart, outBiddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toDays() < 7) { LOGGER.warn("Error, uncorrect duration. Expected at least 7 days but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.SYSTEM_TOTAL_LOAD.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.WEEK_AHEAD.getId()); params.put(Params.OUT_BIDDINDZONE_DOMAIN.getValue(), outBiddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch week ahead load at " + outBiddingZoneDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<GLMarketDocument> fetchAggregatedGenerationType(Area inDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("16.1.B&C", periodStart, inDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toDays() < 7) { LOGGER.warn("Error, uncorrect duration. Expected at least 7 days but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.ACTUAL_GENERATION_PER_TYPE.getId()); params.put(Params.PROCESS_TYPE.getValue(), ProcessType.REALISED.getId()); params.put(Params.IN_DOMAIN.getValue(), inDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String msg = "Unable to correctly fetch aggregated generation per type on " + inDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, msg, GLMarketDocument.class); } public Optional<PublicationMarketDocument> fetchPhysicalFlows(Area inDomain, Area outDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart1 = checker.checkAvailability("12.1.G", periodStart, inDomain); LocalDateTime dataStart2 = checker.checkAvailability("12.1.G", periodStart, outDomain); LocalDateTime dataStart; if (dataStart1.equals(dataStart2)) { dataStart = dataStart1; } else if (dataStart1.isAfter(dataStart2)) { dataStart = dataStart1; } else { dataStart = dataStart2; } LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return Optional.empty(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return Optional.empty(); } if (gap.toHours() < 24) { LOGGER.warn("Error, uncorrect duration. Expected at least 24 hours but it was " + gap.toMinutes() + " minutes"); return Optional.empty(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.AGGREGATED_ENERGY_DATA_REPORT.getId()); params.put(Params.IN_DOMAIN.getValue(), inDomain.getId()); params.put(Params.OUT_DOMAIN.getValue(), outDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); String erroMsg = "Unable to correctly retrieve physical flows from " + outDomain.getPrettyName() + " to " + inDomain.getPrettyName() + " from " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " to " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME); return performGetOperation(params, erroMsg, PublicationMarketDocument.class); } /** * Fetchs the transmission grid outages. * * @param inDomain * @param outDomain * @param periodStart * @param periodEnd * @return One document per outage (can be a lot) */ public List<UnavailabilityMarketDocument> fetchTransmissionGridOutages(Area inDomain, Area outDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("10.1.A&B", periodStart, inDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return new ArrayList<>(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return new ArrayList<>(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.TRANSMISSION_UNAVAILABILITY.getId()); params.put(Params.IN_DOMAIN.getValue(), inDomain.getId()); params.put(Params.OUT_DOMAIN.getValue(), outDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); try { return bridge.doZipGetOperation(params, BASE_URL, UnavailabilityMarketDocument.class); } catch (DataRetrievalRuntimeException ex) { LOGGER.catching(ex); LOGGER.warn("Unable to correctly retrieve outages between " + inDomain.getPrettyName() + " and " + outDomain.getPrettyName() + " for time between " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " and " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME)); return new ArrayList<>(); } } public List<UnavailabilityMarketDocument> fetchGenerationUnitOutages(Area biddingZoneDomain, LocalDateTime periodStart, LocalDateTime periodEnd) { LocalDateTime dataStart = checker.checkAvailability("15.1.A&B", periodStart, biddingZoneDomain); LocalDateTime usedStart = periodStart; if (!periodStart.equals(dataStart)) { if (dataStart.isAfter(periodEnd)) { return new ArrayList<>(); } usedStart = dataStart; } Duration gap = Duration.between(usedStart, periodEnd); if (gap.toDays() > 365) { LOGGER.warn("Error, uncorrect duration. Expected request of less than 365 days, but was " + gap.toDays() + " days"); return new ArrayList<>(); } Map<String, String> params = new HashMap<>(); params.put(Params.SECURITY_TOKEN.getValue(), authToken); params.put(Params.DOCUMENT_TYPE.getValue(), DocumentType.GENERATION_UNAVAILABILITY.getId()); params.put(Params.BIDDING_ZONE_DOMAIN.getValue(), biddingZoneDomain.getId()); params.put(Params.PERIOD_START.getValue(), usedStart.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); params.put(Params.PERIOD_END.getValue(), periodEnd.format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))); try { return bridge.doZipGetOperation(params, BASE_URL, UnavailabilityMarketDocument.class); } catch (DataRetrievalRuntimeException ex) { LOGGER.catching(ex); LOGGER.warn("Unable to correctly retrieve generation outages at " + biddingZoneDomain.getPrettyName() + " for time between " + usedStart.format(DateTimeFormatter.ISO_DATE_TIME) + " and " + periodEnd.format(DateTimeFormatter.ISO_DATE_TIME)); return new ArrayList<>(); } } public Optional<PublicationMarketDocument> fetchWeekAheadCapacityForecast(Area inDomain, Area outDomain, LocalDateTime periodStart, LocalDateTime periodEnd) {
LocalDateTime date1 = checker.checkAvailability(ColumnType.WEEK_FORECAST_CAPACITY.getRelevantArticle(),
2
2023-10-30 09:09:53+00:00
16k
EricFan2002/SC2002
src/app/ui/camp/modificationview/OverlayCampStaffEditView.java
[ { "identifier": "CampModificationController", "path": "src/app/controller/camp/CampModificationController.java", "snippet": "public class CampModificationController {\n /**\n * Private constructor to prevent instantiation.\n */\n private CampModificationController() {\n }\n\n /**\n ...
import app.controller.camp.CampModificationController; import app.entity.camp.Camp; import app.entity.camp.CampDetails; import app.entity.user.Staff; import app.ui.camp.infomationview.OverlayCampInfoDisplayWithParticipantsView; import app.ui.overlayactions.OverlayNotification; import app.ui.widgets.WidgetButton; import app.ui.windows.ICallBack; import app.ui.windows.Window; import java.text.ParseException; import java.text.SimpleDateFormat;
11,165
package app.ui.camp.modificationview; /** * Represents an overlay view for staff to edit camp details. * Extends the OverlayCampInfoDisplayWithParticipantsView class. */ public class OverlayCampStaffEditView extends OverlayCampInfoDisplayWithParticipantsView { protected Camp camp; protected Staff staff;
package app.ui.camp.modificationview; /** * Represents an overlay view for staff to edit camp details. * Extends the OverlayCampInfoDisplayWithParticipantsView class. */ public class OverlayCampStaffEditView extends OverlayCampInfoDisplayWithParticipantsView { protected Camp camp; protected Staff staff;
protected Window mainWindow;
8
2023-11-01 05:18:29+00:00
16k
TNO/PPS
plugins/nl.esi.pps.tmsc.analysis.prototypes.ui/src/nl/esi/pps/tmsc/analysis/prototypes/ui/handlers/ActivitySeparationHandler.java
[ { "identifier": "DEFAULT_LOG_SEVERITIES", "path": "plugins/nl.esi.pps.common.ide.ui/src/nl/esi/pps/common/ide/ui/jobs/StatusReportingJob.java", "snippet": "public static final Collection<Integer> DEFAULT_LOG_SEVERITIES = Collections\n\t\t.unmodifiableCollection(Arrays.asList(IStatus.WARNING, IStatus.ERR...
import static nl.esi.pps.common.ide.ui.jobs.StatusReportingJob.DEFAULT_LOG_SEVERITIES; import static nl.esi.pps.tmsc.analysis.prototypes.ui.Activator.getPluginID; import static org.eclipse.core.runtime.IStatus.ERROR; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Named; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.e4.core.di.annotations.CanExecute; import org.eclipse.e4.core.di.annotations.Evaluate; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.core.di.annotations.Optional; import org.eclipse.e4.ui.services.IServiceConstants; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.jface.viewers.IStructuredSelection; import nl.esi.pps.common.core.runtime.ErrorStatusException; import nl.esi.pps.common.core.runtime.FailOnErrorStatus; import nl.esi.pps.common.core.runtime.jobs.IStatusJobFunction; import nl.esi.pps.common.core.runtime.jobs.JobUtils; import org.eclipse.lsat.common.emf.common.util.URIHelper; import org.eclipse.lsat.common.emf.ecore.resource.Persistor; import org.eclipse.lsat.common.emf.ecore.resource.PersistorFactory; import nl.esi.pps.common.ide.ui.jobs.StatusReportingJob; import org.eclipse.lsat.common.queries.QueryableIterable; import nl.esi.pps.preferences.PPSPreferences; import nl.esi.pps.tmsc.FullScopeTMSC; import nl.esi.pps.tmsc.TmscPlugin; import nl.esi.pps.tmsc.analysis.prototypes.ActivitySeparation; import nl.esi.pps.tmsc.rendering.RenderingProperties; import nl.esi.pps.tmsc.rendering.plot.ScopesRenderingStrategy;
12,608
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.analysis.prototypes.ui.handlers; public class ActivitySeparationHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (!PPSPreferences.isAdvancedFeaturesEnabled() || selection == null || selection.size() != 1) { return false; } Object selectedElement = selection.getFirstElement(); return selectedElement instanceof IFile && TmscPlugin.isTmscFile((IFile) selectedElement); } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection) { IFile modelIFile = (IFile) selection.getFirstElement(); IStatusJobFunction jobFunction = monitor -> doJob(modelIFile, monitor); String jobName = "Activity separation"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_LOG_SEVERITIES, DEFAULT_LOG_SEVERITIES); job.setUser(true); job.schedule(); }
/* * Copyright (c) 2018-2023 TNO and Contributors to the GitHub community * * This program and the accompanying materials are made available * under the terms of the MIT License which is available at * https://opensource.org/licenses/MIT * * SPDX-License-Identifier: MIT */ package nl.esi.pps.tmsc.analysis.prototypes.ui.handlers; public class ActivitySeparationHandler { @Evaluate @CanExecute public boolean canExecute(@Named(IServiceConstants.ACTIVE_SELECTION) @Optional IStructuredSelection selection) { if (!PPSPreferences.isAdvancedFeaturesEnabled() || selection == null || selection.size() != 1) { return false; } Object selectedElement = selection.getFirstElement(); return selectedElement instanceof IFile && TmscPlugin.isTmscFile((IFile) selectedElement); } @Execute public void execute(@Named(IServiceConstants.ACTIVE_SELECTION) IStructuredSelection selection) { IFile modelIFile = (IFile) selection.getFirstElement(); IStatusJobFunction jobFunction = monitor -> doJob(modelIFile, monitor); String jobName = "Activity separation"; Job job = new StatusReportingJob(jobName, jobFunction, getPluginID(), DEFAULT_LOG_SEVERITIES, DEFAULT_LOG_SEVERITIES); job.setUser(true); job.schedule(); }
public static IStatus doJob(IFile modelIFile, IProgressMonitor monitor) throws ErrorStatusException {
2
2023-10-30 16:00:25+00:00
16k
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE
src/main/java/com/cerbon/bosses_of_mass_destruction/event/BMDEvents.java
[ { "identifier": "BMDBlockEntities", "path": "src/main/java/com/cerbon/bosses_of_mass_destruction/block/BMDBlockEntities.java", "snippet": "public class BMDBlockEntities {\n public static final DeferredRegister<BlockEntityType<?>> BLOCKS_ENTITIES =\n DeferredRegister.create(ForgeRegistries....
import com.cerbon.bosses_of_mass_destruction.block.BMDBlockEntities; import com.cerbon.bosses_of_mass_destruction.block.BMDBlocks; import com.cerbon.bosses_of_mass_destruction.config.BMDConfig; import com.cerbon.bosses_of_mass_destruction.entity.BMDEntities; import com.cerbon.bosses_of_mass_destruction.item.BMDCreativeModeTabs; import com.cerbon.bosses_of_mass_destruction.item.BMDItems; import com.cerbon.bosses_of_mass_destruction.packet.BMDPacketHandler; import com.cerbon.bosses_of_mass_destruction.particle.BMDParticles; import com.cerbon.bosses_of_mass_destruction.util.BMDConstants; import me.shedaniel.autoconfig.AutoConfig; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.ConfigScreenHandler; import net.minecraftforge.client.event.RegisterParticleProvidersEvent; import net.minecraftforge.event.BuildCreativeModeTabContentsEvent; import net.minecraftforge.event.entity.EntityAttributeCreationEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.ModLoadingContext; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; import org.jetbrains.annotations.NotNull;
13,240
package com.cerbon.bosses_of_mass_destruction.event; public class BMDEvents { @Mod.EventBusSubscriber(modid = BMDConstants.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public static class ClientEvents { @SubscribeEvent protected static void onClientSetup(FMLClientSetupEvent event){ BMDEntities.initClient(); BMDItems.initClient(); BMDBlockEntities.initClient(); ModLoadingContext.get().registerExtensionPoint(ConfigScreenHandler.ConfigScreenFactory.class, () -> new ConfigScreenHandler.ConfigScreenFactory((client, parent) -> AutoConfig.getConfigScreen(BMDConfig.class, parent).get())); } @SubscribeEvent protected static void registerParticleProviders(final @NotNull RegisterParticleProvidersEvent event) {
package com.cerbon.bosses_of_mass_destruction.event; public class BMDEvents { @Mod.EventBusSubscriber(modid = BMDConstants.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT) public static class ClientEvents { @SubscribeEvent protected static void onClientSetup(FMLClientSetupEvent event){ BMDEntities.initClient(); BMDItems.initClient(); BMDBlockEntities.initClient(); ModLoadingContext.get().registerExtensionPoint(ConfigScreenHandler.ConfigScreenFactory.class, () -> new ConfigScreenHandler.ConfigScreenFactory((client, parent) -> AutoConfig.getConfigScreen(BMDConfig.class, parent).get())); } @SubscribeEvent protected static void registerParticleProviders(final @NotNull RegisterParticleProvidersEvent event) {
BMDParticles.initClient(event);
7
2023-10-25 16:28:17+00:00
16k
SmartGecko44/Spigot-Admin-Toys
src/main/java/org/gecko/wauh/Main.java
[ { "identifier": "Mirror", "path": "src/main/java/org/gecko/wauh/blocks/Mirror.java", "snippet": "public class Mirror implements Listener {\n private final Plugin plugin;\n private Block lastGlassBlock = null;\n\n public Mirror(Plugin plugin) {\n this.plugin = plugin;\n }\n\n public...
import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.plugin.java.JavaPlugin; import org.gecko.wauh.blocks.Mirror; import org.gecko.wauh.commands.*; import org.gecko.wauh.data.ConfigurationManager; import org.gecko.wauh.enchantments.enchants.weapons.bows.Aim; import org.gecko.wauh.enchantments.enchants.weapons.bows.BowListener; import org.gecko.wauh.enchantments.enchants.weapons.bows.Multishot; import org.gecko.wauh.enchantments.logic.EnchantmentHandler; import org.gecko.wauh.enchantments.enchants.weapons.swords.Disarm; import org.gecko.wauh.enchantments.tools.pickaxes.Drill; import org.gecko.wauh.enchantments.tools.pickaxes.Smelt; import org.gecko.wauh.gui.ConfigGUI; import org.gecko.wauh.listeners.*; import java.lang.reflect.Field; import java.util.logging.Level; import java.util.logging.Logger;
10,816
package org.gecko.wauh; public final class Main extends JavaPlugin { ConfigurationManager configManager; FileConfiguration config; private int playerRadiusLimit; private int tntRadiusLimit; private int creeperRadiusLimit; private boolean showRemoval = true; private BucketListener bucketListener; private BarrierListener barrierListener; private BedrockListener bedrockListener; private WaterBucketListener waterBucketListener; private TNTListener tntListener; private CreeperListener creeperListener; private static final Logger logger = Logger.getLogger(Main.class.getName());
package org.gecko.wauh; public final class Main extends JavaPlugin { ConfigurationManager configManager; FileConfiguration config; private int playerRadiusLimit; private int tntRadiusLimit; private int creeperRadiusLimit; private boolean showRemoval = true; private BucketListener bucketListener; private BarrierListener barrierListener; private BedrockListener bedrockListener; private WaterBucketListener waterBucketListener; private TNTListener tntListener; private CreeperListener creeperListener; private static final Logger logger = Logger.getLogger(Main.class.getName());
private final EnchantmentHandler enchantmentHandler = new EnchantmentHandler();
5
2023-10-28 11:26:45+00:00
16k
sinch/sinch-sdk-java
openapi-contracts/src/main/com/sinch/sdk/domains/numbers/adapters/api/v1/ActiveNumberApi.java
[ { "identifier": "ApiException", "path": "core/src/main/com/sinch/sdk/core/exceptions/ApiException.java", "snippet": "public class ApiException extends RuntimeException {\n\n private static final long serialVersionUID = -1L;\n private int code = 0;\n\n public ApiException() {}\n\n public ApiException...
import com.fasterxml.jackson.core.type.TypeReference; import com.sinch.sdk.core.exceptions.ApiException; import com.sinch.sdk.core.exceptions.ApiExceptionBuilder; import com.sinch.sdk.core.http.AuthManager; import com.sinch.sdk.core.http.HttpClient; import com.sinch.sdk.core.http.HttpMapper; import com.sinch.sdk.core.http.HttpMethod; import com.sinch.sdk.core.http.HttpRequest; import com.sinch.sdk.core.http.HttpResponse; import com.sinch.sdk.core.http.HttpStatus; import com.sinch.sdk.core.http.URLParameter; import com.sinch.sdk.core.http.URLPathUtils; import com.sinch.sdk.core.models.ServerConfiguration; import com.sinch.sdk.domains.numbers.models.dto.v1.ActiveNumberDto; import com.sinch.sdk.domains.numbers.models.dto.v1.ActiveNumberRequestDto; import com.sinch.sdk.domains.numbers.models.dto.v1.ActiveNumbersResponseDto; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger;
10,859
/* * Numbers | Sinch * An API service for getting, listing and managing Sinch virtual numbers. * * The version of the OpenAPI document: 1.0.2 * Contact: Support@sinch.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sinch.sdk.domains.numbers.adapters.api.v1; public class ActiveNumberApi { private static final Logger LOGGER = Logger.getLogger(ActiveNumberApi.class.getName()); private HttpClient httpClient; private ServerConfiguration serverConfiguration; private Map<String, AuthManager> authManagersByOasSecuritySchemes; private HttpMapper mapper; public ActiveNumberApi( HttpClient httpClient, ServerConfiguration serverConfiguration, Map<String, AuthManager> authManagersByOasSecuritySchemes, HttpMapper mapper) { this.httpClient = httpClient; this.serverConfiguration = serverConfiguration; this.authManagersByOasSecuritySchemes = authManagersByOasSecuritySchemes; this.mapper = mapper; } /** * Get active Number Get a virtual number * * @param projectId Found on your &lt;a * href&#x3D;\&quot;https://dashboard.sinch.com/settings/project-management\&quot; * target&#x3D;\&quot;_blank\&quot;&gt;Sinch Customer Dashboard&lt;/a&gt;. (required) * @param phoneNumber Output only. The phone number in &lt;a * href&#x3D;\&quot;https://community.sinch.com/t5/Glossary/E-164/ta-p/7537\&quot; * target&#x3D;\&quot;_blank\&quot;&gt;E.164&lt;/a&gt; format with leading &#x60;+&#x60;. * (required) * @return ActiveNumberDto * @throws ApiException if fails to make API call */ public ActiveNumberDto numberServiceGetActiveNumber(String projectId, String phoneNumber)
/* * Numbers | Sinch * An API service for getting, listing and managing Sinch virtual numbers. * * The version of the OpenAPI document: 1.0.2 * Contact: Support@sinch.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.sinch.sdk.domains.numbers.adapters.api.v1; public class ActiveNumberApi { private static final Logger LOGGER = Logger.getLogger(ActiveNumberApi.class.getName()); private HttpClient httpClient; private ServerConfiguration serverConfiguration; private Map<String, AuthManager> authManagersByOasSecuritySchemes; private HttpMapper mapper; public ActiveNumberApi( HttpClient httpClient, ServerConfiguration serverConfiguration, Map<String, AuthManager> authManagersByOasSecuritySchemes, HttpMapper mapper) { this.httpClient = httpClient; this.serverConfiguration = serverConfiguration; this.authManagersByOasSecuritySchemes = authManagersByOasSecuritySchemes; this.mapper = mapper; } /** * Get active Number Get a virtual number * * @param projectId Found on your &lt;a * href&#x3D;\&quot;https://dashboard.sinch.com/settings/project-management\&quot; * target&#x3D;\&quot;_blank\&quot;&gt;Sinch Customer Dashboard&lt;/a&gt;. (required) * @param phoneNumber Output only. The phone number in &lt;a * href&#x3D;\&quot;https://community.sinch.com/t5/Glossary/E-164/ta-p/7537\&quot; * target&#x3D;\&quot;_blank\&quot;&gt;E.164&lt;/a&gt; format with leading &#x60;+&#x60;. * (required) * @return ActiveNumberDto * @throws ApiException if fails to make API call */ public ActiveNumberDto numberServiceGetActiveNumber(String projectId, String phoneNumber)
throws ApiException {
0
2023-10-31 08:32:59+00:00
16k
SpCoGov/SpCoBot
src/main/java/top/spco/service/command/commands/DataCommand.java
[ { "identifier": "SpCoBot", "path": "src/main/java/top/spco/SpCoBot.java", "snippet": "public class SpCoBot {\n private static SpCoBot instance;\n public static Logger logger;\n public static File dataFolder;\n public static File configFolder;\n public long botId;\n public long botOwner...
import top.spco.SpCoBot; import top.spco.api.Bot; import top.spco.api.Interactive; import top.spco.api.User; import top.spco.api.message.Message; import top.spco.service.command.AbstractCommand; import top.spco.service.command.CommandMeta; import top.spco.service.command.CommandParam; import top.spco.service.command.CommandUsage; import top.spco.user.BotUser; import top.spco.user.UserPermission; import java.sql.SQLException; import java.util.List;
10,824
/* * Copyright 2023 SpCo * * 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 top.spco.service.command.commands; /** * @author SpCo * @version 1.2.3 * @since 0.1.0 */ public final class DataCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"data"}; } @Override public String getDescriptions() { return "操作数据"; } @Override public List<CommandUsage> getUsages() { return List.of( new CommandUsage("data", "查询记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "get"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待查询的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)), new CommandUsage("data", "编辑记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "set"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待修改的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("新值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public UserPermission needPermission() { return UserPermission.OWNER; } /** * <pre> * 0 1 2 3 4 5 * /data set <表名> <字段名> <记录值> <待修改的字段名> <新值> * /data get <表名> <字段名> <记录值> <待查询的字段名> * </pre> */ @Override public void onCommand(Bot bot, Interactive from, User sender, BotUser user, Message message, int time, String command, String label, String[] args, CommandMeta meta, String usageName) { switch (usageName) { case "查询记录" -> { String table = args[1]; String columns = args[4]; String whereClause = args[2]; String whereValues = args[3]; try {
/* * Copyright 2023 SpCo * * 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 top.spco.service.command.commands; /** * @author SpCo * @version 1.2.3 * @since 0.1.0 */ public final class DataCommand extends AbstractCommand { @Override public String[] getLabels() { return new String[]{"data"}; } @Override public String getDescriptions() { return "操作数据"; } @Override public List<CommandUsage> getUsages() { return List.of( new CommandUsage("data", "查询记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "get"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待查询的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT)), new CommandUsage("data", "编辑记录", new CommandParam("操作类型", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.SELECTION, "set"), new CommandParam("表名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("记录值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("待修改的字段名", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT), new CommandParam("新值", CommandParam.ParamType.REQUIRED, CommandParam.ParamContent.TEXT))); } @Override public UserPermission needPermission() { return UserPermission.OWNER; } /** * <pre> * 0 1 2 3 4 5 * /data set <表名> <字段名> <记录值> <待修改的字段名> <新值> * /data get <表名> <字段名> <记录值> <待查询的字段名> * </pre> */ @Override public void onCommand(Bot bot, Interactive from, User sender, BotUser user, Message message, int time, String command, String label, String[] args, CommandMeta meta, String usageName) { switch (usageName) { case "查询记录" -> { String table = args[1]; String columns = args[4]; String whereClause = args[2]; String whereValues = args[3]; try {
String value = SpCoBot.getInstance().getDataBase().selectString(table, columns, whereClause, whereValues);
0
2023-10-26 10:27:47+00:00
16k
zxzf1234/jimmer-ruoyivuepro
backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/service/infra/codegen/inner/CodegenEngine.java
[ { "identifier": "ServiceExceptionUtil", "path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/exception/util/ServiceExceptionUtil.java", "snippet": "@Slf4j\npublic class ServiceExceptionUtil {\n\n /**\n * 错误码提示模板\n */\n private static final Concurren...
import cn.hutool.core.convert.Convert; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.engine.velocity.VelocityEngine; import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil; import cn.iocoder.yudao.framework.common.pojo.CommonResult; import cn.iocoder.yudao.framework.common.pojo.PageParam; import cn.iocoder.yudao.framework.common.pojo.PageResult; import cn.iocoder.yudao.framework.common.util.date.DateUtils; import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils; import cn.iocoder.yudao.framework.common.util.object.ObjectUtils; import cn.iocoder.yudao.framework.excel.core.annotations.DictFormat; import cn.iocoder.yudao.framework.excel.core.convert.DictConvert; import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils; import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO; import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX; import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog; import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum; import cn.iocoder.yudao.service.convert.infra.codegen.CodegenConvert; import cn.iocoder.yudao.service.enums.codegen.CodegenSceneEnum; import cn.iocoder.yudao.service.framework.codegen.config.CodegenProperties; import cn.iocoder.yudao.service.framework.codegen.config.SchemaHistory; import cn.iocoder.yudao.service.model.infra.codegen.*; import cn.iocoder.yudao.service.repository.infra.codegen.*; import cn.iocoder.yudao.service.vo.infra.codegen.database.DatabaseUpdateReq; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.File; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.*; import static cn.hutool.core.map.MapUtil.getStr; import static cn.hutool.core.text.CharSequenceUtil.*;
12,142
package cn.iocoder.yudao.service.service.infra.codegen.inner; /** * 代码生成的引擎,用于具体生成代码 * 目前基于 {@link org.apache.velocity.app.Velocity} 模板引擎实现 * * 考虑到 Java 模板引擎的框架非常多,Freemarker、Velocity、Thymeleaf 等等,所以我们采用 hutool 封装的 {@link cn.hutool.extra.template.Template} 抽象 * * @author 芋道源码 */ @Component public class CodegenEngine { /** * 后端的模板配置 * * key:模板在 resources 的地址 * value:生成的路径 */ private static final Map<String, String> TABLE_INSERT_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("repository/repository"), javaTableFilePath("repository","${classNameHump}Repository")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> TABLE_UPDATE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> MODULE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controller"), javaControllerFilePath()) .put(javaTemplatePath("convert/convert"), javaModuleFilePath("convert", "${nameHumpUp}Convert")) .put(javaTemplatePath("service/serviceImpl"), javaModuleFilePath("service", "${nameHumpUp}ServiceImpl")) .put(javaTemplatePath("service/service"), javaModuleFilePath("service", "${nameHumpUp}Service")) .build(); private static final Map<String, String> INTERFACE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controllerInterface"), javaFilePath("controller/${sceneEnum.basePackage}/${modulePath}/${moduleNameHump}Controller")+ ".java") .put(javaTemplatePath("convert/convertInterface"), javaModuleFilePath("convert", "${moduleNameHump}Convert")) .put(javaTemplatePath("service/serviceImplInterface"), javaModuleFilePath("service", "${moduleNameHump}ServiceImpl")) .put(javaTemplatePath("service/serviceInterface"), javaModuleFilePath("service", "${moduleNameHump}Service")) .put(javaTemplatePath("vo/VOInput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Input")) .put(javaTemplatePath("vo/VOOutput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Output")) .build(); /* private static final Table<Integer, String, String> FRONT_TEMPLATES = ImmutableTable.<Integer, String, String>builder() // Vue2 标准模版 .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/index.vue"), vueFilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("api/api.js"), vueFilePath("api/${table.moduleName}/${classNameVar}.js")) // Vue3 标准模版 .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 Schema 模版 .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 vben 模版 .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Modal.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) .build();*/ @Resource private CodegenProperties codegenProperties; @Resource private InfraDatabaseTableRepository infraDatabaseTableRepository; @Resource private InfraInterfaceModuleRepository infraInterfaceModuleRepository; @Resource private InfraInterfaceRepository infraInterfaceRepository; @Resource private InfraInterfaceVoClassRepository infraInterfaceVoClassRepository; @Resource private InfraInterfaceSubclassRepository infraInterfaceSubclassRepository; @Resource private SchemaHistory schemaHistory; /** * 模板引擎,由 hutool 实现 */ private final TemplateEngine templateEngine; /** * 全局通用变量映射 */ private final Map<String, Object> globalBindingMap = new HashMap<>(); public CodegenEngine() { // 初始化 TemplateEngine 属性 TemplateConfig config = new TemplateConfig(); config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH); this.templateEngine = new VelocityEngine(config); } @PostConstruct private void initGlobalBindingMap() { // 全局配置 globalBindingMap.put("basePackage", codegenProperties.getBasePackage()); globalBindingMap.put("baseFrameworkPackage", codegenProperties.getBasePackage() + '.' + "framework"); // 用于后续获取测试类的 package 地址 // 全局 Java Bean globalBindingMap.put("CommonResultClassName", CommonResult.class.getName()); globalBindingMap.put("PageResultClassName", PageResult.class.getName()); // VO 类,独有字段 globalBindingMap.put("PageParamClassName", PageParam.class.getName()); globalBindingMap.put("DictFormatClassName", DictFormat.class.getName()); // DO 类,独有字段 globalBindingMap.put("BaseDOClassName", BaseDO.class.getName()); globalBindingMap.put("QueryWrapperClassName", LambdaQueryWrapperX.class.getName()); globalBindingMap.put("BaseMapperClassName", BaseMapperX.class.getName()); // Util 工具类 globalBindingMap.put("ServiceExceptionUtilClassName", ServiceExceptionUtil.class.getName()); globalBindingMap.put("DateUtilsClassName", DateUtils.class.getName()); globalBindingMap.put("ExcelUtilsClassName", ExcelUtils.class.getName()); globalBindingMap.put("LocalDateTimeUtilsClassName", LocalDateTimeUtils.class.getName());
package cn.iocoder.yudao.service.service.infra.codegen.inner; /** * 代码生成的引擎,用于具体生成代码 * 目前基于 {@link org.apache.velocity.app.Velocity} 模板引擎实现 * * 考虑到 Java 模板引擎的框架非常多,Freemarker、Velocity、Thymeleaf 等等,所以我们采用 hutool 封装的 {@link cn.hutool.extra.template.Template} 抽象 * * @author 芋道源码 */ @Component public class CodegenEngine { /** * 后端的模板配置 * * key:模板在 resources 的地址 * value:生成的路径 */ private static final Map<String, String> TABLE_INSERT_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("repository/repository"), javaTableFilePath("repository","${classNameHump}Repository")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> TABLE_UPDATE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 // Java module-biz Main .put(javaTemplatePath("vo/baseVO"), javaBaseVOFilePath("Base")) .put(javaTemplatePath("model/model"), javaTableFilePath("model","${classNameHump}")) .build(); private static final Map<String, String> MODULE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controller"), javaControllerFilePath()) .put(javaTemplatePath("convert/convert"), javaModuleFilePath("convert", "${nameHumpUp}Convert")) .put(javaTemplatePath("service/serviceImpl"), javaModuleFilePath("service", "${nameHumpUp}ServiceImpl")) .put(javaTemplatePath("service/service"), javaModuleFilePath("service", "${nameHumpUp}Service")) .build(); private static final Map<String, String> INTERFACE_TEMPLATES = MapUtil.<String, String>builder(new LinkedHashMap<>()) // 有序 .put(javaTemplatePath("controller/controllerInterface"), javaFilePath("controller/${sceneEnum.basePackage}/${modulePath}/${moduleNameHump}Controller")+ ".java") .put(javaTemplatePath("convert/convertInterface"), javaModuleFilePath("convert", "${moduleNameHump}Convert")) .put(javaTemplatePath("service/serviceImplInterface"), javaModuleFilePath("service", "${moduleNameHump}ServiceImpl")) .put(javaTemplatePath("service/serviceInterface"), javaModuleFilePath("service", "${moduleNameHump}Service")) .put(javaTemplatePath("vo/VOInput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Input")) .put(javaTemplatePath("vo/VOOutput"), javaModuleFilePath("vo", "${moduleNameHump}/${moduleNameHumpUp}${interfaceNameHumpUp}Output")) .build(); /* private static final Table<Integer, String, String> FRONT_TEMPLATES = ImmutableTable.<Integer, String, String>builder() // Vue2 标准模版 .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("views/index.vue"), vueFilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE2.getType(), vueTemplatePath("api/api.js"), vueFilePath("api/${table.moduleName}/${classNameVar}.js")) // Vue3 标准模版 .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3.getType(), vue3TemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 Schema 模版 .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Form.vue")) .put(CodegenFrontTypeEnum.VUE3_SCHEMA.getType(), vue3SchemaTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) // Vue3 vben 模版 .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/data.ts"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${classNameVar}.data.ts")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/index.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/index.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("views/form.vue"), vue3FilePath("views/${table.moduleName}/${classNameVar}/${simpleClassName}Modal.vue")) .put(CodegenFrontTypeEnum.VUE3_VBEN.getType(), vue3VbenTemplatePath("api/api.ts"), vue3FilePath("api/${table.moduleName}/${classNameVar}/index.ts")) .build();*/ @Resource private CodegenProperties codegenProperties; @Resource private InfraDatabaseTableRepository infraDatabaseTableRepository; @Resource private InfraInterfaceModuleRepository infraInterfaceModuleRepository; @Resource private InfraInterfaceRepository infraInterfaceRepository; @Resource private InfraInterfaceVoClassRepository infraInterfaceVoClassRepository; @Resource private InfraInterfaceSubclassRepository infraInterfaceSubclassRepository; @Resource private SchemaHistory schemaHistory; /** * 模板引擎,由 hutool 实现 */ private final TemplateEngine templateEngine; /** * 全局通用变量映射 */ private final Map<String, Object> globalBindingMap = new HashMap<>(); public CodegenEngine() { // 初始化 TemplateEngine 属性 TemplateConfig config = new TemplateConfig(); config.setResourceMode(TemplateConfig.ResourceMode.CLASSPATH); this.templateEngine = new VelocityEngine(config); } @PostConstruct private void initGlobalBindingMap() { // 全局配置 globalBindingMap.put("basePackage", codegenProperties.getBasePackage()); globalBindingMap.put("baseFrameworkPackage", codegenProperties.getBasePackage() + '.' + "framework"); // 用于后续获取测试类的 package 地址 // 全局 Java Bean globalBindingMap.put("CommonResultClassName", CommonResult.class.getName()); globalBindingMap.put("PageResultClassName", PageResult.class.getName()); // VO 类,独有字段 globalBindingMap.put("PageParamClassName", PageParam.class.getName()); globalBindingMap.put("DictFormatClassName", DictFormat.class.getName()); // DO 类,独有字段 globalBindingMap.put("BaseDOClassName", BaseDO.class.getName()); globalBindingMap.put("QueryWrapperClassName", LambdaQueryWrapperX.class.getName()); globalBindingMap.put("BaseMapperClassName", BaseMapperX.class.getName()); // Util 工具类 globalBindingMap.put("ServiceExceptionUtilClassName", ServiceExceptionUtil.class.getName()); globalBindingMap.put("DateUtilsClassName", DateUtils.class.getName()); globalBindingMap.put("ExcelUtilsClassName", ExcelUtils.class.getName()); globalBindingMap.put("LocalDateTimeUtilsClassName", LocalDateTimeUtils.class.getName());
globalBindingMap.put("ObjectUtilsClassName", ObjectUtils.class.getName());
6
2023-10-27 06:35:24+00:00
16k
frc7787/FTC-Centerstage
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/SampleTankDrive.java
[ { "identifier": "TrajectorySequence", "path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/trajectorysequence/TrajectorySequence.java", "snippet": "public class TrajectorySequence {\n private final List<SequenceSegment> sequenceList;\n\n public TrajectorySequence(List<Sequence...
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.TankDrive; 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.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;
10,860
package org.firstinspires.ftc.teamcode.RoadRunner.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(DriveConstants.MAX_VEL, DriveConstants.MAX_ANG_VEL, DriveConstants.TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(DriveConstants.MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(DriveConstants.kV, DriveConstants.kA, DriveConstants.kStatic, DriveConstants.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 (DriveConstants.RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (DriveConstants.RUN_USING_ENCODER && DriveConstants.MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, DriveConstants.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); }
package org.firstinspires.ftc.teamcode.RoadRunner.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(DriveConstants.MAX_VEL, DriveConstants.MAX_ANG_VEL, DriveConstants.TRACK_WIDTH); private static final TrajectoryAccelerationConstraint accelConstraint = getAccelerationConstraint(DriveConstants.MAX_ACCEL); private TrajectoryFollower follower; private List<DcMotorEx> motors, leftMotors, rightMotors; private IMU imu; private VoltageSensor batteryVoltageSensor; public SampleTankDrive(HardwareMap hardwareMap) { super(DriveConstants.kV, DriveConstants.kA, DriveConstants.kStatic, DriveConstants.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 (DriveConstants.RUN_USING_ENCODER) { setMode(DcMotor.RunMode.RUN_USING_ENCODER); } setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); if (DriveConstants.RUN_USING_ENCODER && DriveConstants.MOTOR_VELO_PID != null) { setPIDFCoefficients(DcMotor.RunMode.RUN_USING_ENCODER, DriveConstants.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) {
1
2023-10-31 16:06:46+00:00
16k
slatepowered/slate
slate-cluster/src/main/java/slatepowered/slate/cluster/ClusterInstance.java
[ { "identifier": "CommunicationKey", "path": "slate-common/src/main/java/slatepowered/slate/communication/CommunicationKey.java", "snippet": "public class CommunicationKey {\r\n\r\n public static class ClusterDeclareCommunicationKey extends CommunicationKey {\r\n @Override\r\n public int...
import slatepowered.slate.allocation.*; import slatepowered.slate.communication.CommunicationKey; import slatepowered.slate.communication.CommunicationStrategy; import slatepowered.slate.logging.Logger; import slatepowered.slate.logging.Logging; import slatepowered.slate.model.ClusterManagedNode; import slatepowered.slate.model.ClusterNetwork; import slatepowered.slate.model.Node; import slatepowered.slate.model.NodeComponent; import slatepowered.slate.action.NodeAllocationAdapter; import slatepowered.slate.network.NetworkInfoService; import slatepowered.slate.packages.PackageAttachment; import slatepowered.slate.packages.PackageManager; import slatepowered.slate.packages.Packages; import slatepowered.slate.packages.service.LateAttachmentService; import slatepowered.slate.plugin.SlatePluginManager; import slatepowered.veru.collection.Sequence; import slatepowered.veru.misc.Throwables; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture;
11,599
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true;
package slatepowered.slate.cluster; /** * An instance of this cluster for a specific network. */ public abstract class ClusterInstance extends ClusterNetwork { protected static final Logger LOGGER = Logging.getLogger("ClusterInstance"); /** * The cluster. */ protected final Cluster<?> cluster; /** * The directory for this cluster instance. */ protected final Path directory; /** * Whether this instance is enabled. */ private boolean enabled = true;
public ClusterInstance(Cluster<?> cluster, CommunicationKey communicationKey, CommunicationStrategy communicationStrategy) {
0
2023-10-30 08:58:02+00:00
16k
Melledy/LunarCore
src/main/java/emu/lunarcore/game/rogue/RogueBuffSelectMenu.java
[ { "identifier": "GameDepot", "path": "src/main/java/emu/lunarcore/data/GameDepot.java", "snippet": "public class GameDepot {\n // Exp\n @Getter private static List<AvatarExpItemExcel> avatarExpExcels = new ArrayList<>();\n @Getter private static List<EquipmentExpItemExcel> equipmentExpExcels = ...
import java.util.ArrayList; import java.util.List; import emu.lunarcore.data.GameDepot; import emu.lunarcore.data.excel.RogueBuffExcel; import emu.lunarcore.proto.RogueBuffSelectInfoOuterClass.RogueBuffSelectInfo; import emu.lunarcore.util.WeightedList; import lombok.Getter;
12,828
package emu.lunarcore.game.rogue; @Getter public class RogueBuffSelectMenu { private transient RogueInstance rogue; private int maxBuffs; private int rerolls; private int maxRerolls; private int hint; private List<RogueBuffData> buffs; // Cache private transient WeightedList<RogueBuffExcel> randomBuffs; @Deprecated // Morphia only! public RogueBuffSelectMenu() {} public RogueBuffSelectMenu(RogueInstance rogue) { this(rogue, false); } public RogueBuffSelectMenu(RogueInstance rogue, boolean generateAeonBuffs) { this.rogue = rogue; this.maxBuffs = 3; this.maxRerolls = rogue.getBaseRerolls(); this.buffs = new ArrayList<>(); if (generateAeonBuffs) { this.generateAeonBuffs(); } else { this.generateRandomBuffs(); } } public void setMaxRerolls(int i) { this.maxBuffs = i; } public void reroll() { this.generateRandomBuffs(); this.rerolls++; } public boolean hasRerolls() { return this.maxRerolls > this.rerolls; } private void generateRandomBuffs() { if (this.randomBuffs == null) { this.randomBuffs = new WeightedList<>(); for (var excel : GameDepot.getRogueRandomBuffList()) { if (rogue.getBuffs().containsKey(excel.getMazeBuffID())) { continue; } // Calculate buff weights double weight = 10.0 / excel.getRogueBuffRarity(); if (getRogue().getAeonBuffType() == excel.getRogueBuffType()) { weight *= 2; } this.randomBuffs.add(weight, excel); }; } this.getBuffs().clear(); while (this.getBuffs().size() < this.getMaxBuffs()) { var excel = this.randomBuffs.next(); this.getBuffs().add(new RogueBuffData(excel.getMazeBuffID(), 1)); } } private void generateAeonBuffs() { this.getBuffs().clear(); var aeonBuffExcel = GameDepot.getRogueAeonBuffs().get(getRogue().getAeonId()); if (aeonBuffExcel == null) return; // Select buff menu hint this.hint = (getRogue().getAeonId() * 100) + 1; // Check for rogue aeon buffs if (!this.getRogue().getBuffs().containsKey(aeonBuffExcel.getMazeBuffID())) { // We dont have the first aeon buff yet this.getBuffs().add(new RogueBuffData(aeonBuffExcel.getMazeBuffID(), 1)); } else { // Add hint this.hint += 1; // Add path resonances that we currently dont have for (var aeonEnhanceExcel : GameDepot.getRogueAeonEnhanceBuffs().get(getRogue().getAeonId())) { if (!this.getRogue().getBuffs().containsKey(aeonEnhanceExcel.getMazeBuffID())) { this.getBuffs().add(new RogueBuffData(aeonEnhanceExcel.getMazeBuffID(), 1)); } else { this.hint += 1; } } } } protected void onLoad(RogueInstance rogue) { this.rogue = rogue; }
package emu.lunarcore.game.rogue; @Getter public class RogueBuffSelectMenu { private transient RogueInstance rogue; private int maxBuffs; private int rerolls; private int maxRerolls; private int hint; private List<RogueBuffData> buffs; // Cache private transient WeightedList<RogueBuffExcel> randomBuffs; @Deprecated // Morphia only! public RogueBuffSelectMenu() {} public RogueBuffSelectMenu(RogueInstance rogue) { this(rogue, false); } public RogueBuffSelectMenu(RogueInstance rogue, boolean generateAeonBuffs) { this.rogue = rogue; this.maxBuffs = 3; this.maxRerolls = rogue.getBaseRerolls(); this.buffs = new ArrayList<>(); if (generateAeonBuffs) { this.generateAeonBuffs(); } else { this.generateRandomBuffs(); } } public void setMaxRerolls(int i) { this.maxBuffs = i; } public void reroll() { this.generateRandomBuffs(); this.rerolls++; } public boolean hasRerolls() { return this.maxRerolls > this.rerolls; } private void generateRandomBuffs() { if (this.randomBuffs == null) { this.randomBuffs = new WeightedList<>(); for (var excel : GameDepot.getRogueRandomBuffList()) { if (rogue.getBuffs().containsKey(excel.getMazeBuffID())) { continue; } // Calculate buff weights double weight = 10.0 / excel.getRogueBuffRarity(); if (getRogue().getAeonBuffType() == excel.getRogueBuffType()) { weight *= 2; } this.randomBuffs.add(weight, excel); }; } this.getBuffs().clear(); while (this.getBuffs().size() < this.getMaxBuffs()) { var excel = this.randomBuffs.next(); this.getBuffs().add(new RogueBuffData(excel.getMazeBuffID(), 1)); } } private void generateAeonBuffs() { this.getBuffs().clear(); var aeonBuffExcel = GameDepot.getRogueAeonBuffs().get(getRogue().getAeonId()); if (aeonBuffExcel == null) return; // Select buff menu hint this.hint = (getRogue().getAeonId() * 100) + 1; // Check for rogue aeon buffs if (!this.getRogue().getBuffs().containsKey(aeonBuffExcel.getMazeBuffID())) { // We dont have the first aeon buff yet this.getBuffs().add(new RogueBuffData(aeonBuffExcel.getMazeBuffID(), 1)); } else { // Add hint this.hint += 1; // Add path resonances that we currently dont have for (var aeonEnhanceExcel : GameDepot.getRogueAeonEnhanceBuffs().get(getRogue().getAeonId())) { if (!this.getRogue().getBuffs().containsKey(aeonEnhanceExcel.getMazeBuffID())) { this.getBuffs().add(new RogueBuffData(aeonEnhanceExcel.getMazeBuffID(), 1)); } else { this.hint += 1; } } } } protected void onLoad(RogueInstance rogue) { this.rogue = rogue; }
public RogueBuffSelectInfo toProto() {
2
2023-10-10 12:57:35+00:00
16k
lunasaw/gb28181-proxy
sip-common/src/main/java/io/github/lunasaw/sip/common/transmit/SipSender.java
[ { "identifier": "Constant", "path": "sip-common/src/main/java/io/github/lunasaw/sip/common/constant/Constant.java", "snippet": "public class Constant {\n\n public static final String TCP = \"TCP\";\n\n public static final String UDP = \"UDP\";\n\n public static final String AGENT = \"LunaSaw-GB...
import java.util.Objects; import javax.sip.ServerTransaction; import javax.sip.SipException; import javax.sip.address.SipURI; import javax.sip.header.CallIdHeader; import javax.sip.header.UserAgentHeader; import javax.sip.header.ViaHeader; import javax.sip.message.Message; import javax.sip.message.Request; import javax.sip.message.Response; import gov.nist.javax.sip.SipProviderImpl; import gov.nist.javax.sip.SipStackImpl; import gov.nist.javax.sip.message.SIPRequest; import gov.nist.javax.sip.message.SIPResponse; import gov.nist.javax.sip.stack.SIPServerTransaction; import io.github.lunasaw.sip.common.constant.Constant; import io.github.lunasaw.sip.common.entity.FromDevice; import io.github.lunasaw.sip.common.entity.ToDevice; import io.github.lunasaw.sip.common.layer.SipLayer; import io.github.lunasaw.sip.common.subscribe.SubscribeInfo; import io.github.lunasaw.sip.common.transmit.event.Event; import io.github.lunasaw.sip.common.transmit.event.SipSubscribe; import io.github.lunasaw.sip.common.transmit.request.SipRequestProvider; import io.github.lunasaw.sip.common.utils.SipRequestUtils; import lombok.Data; import lombok.extern.slf4j.Slf4j;
13,106
package io.github.lunasaw.sip.common.transmit; /** * 发送SIP消息 * * @author lin */ @Slf4j @Data public class SipSender { public static String doSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo) { return doSubscribeRequest(fromDevice, toDevice, content, subscribeInfo, null, null); } public static String doMessageRequest(FromDevice fromDevice, ToDevice toDevice, String contend) { return doMessageRequest(fromDevice, toDevice, contend, null, null); } public static String doNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo) { return doNotifyRequest(fromDevice, toDevice, content, subscribeInfo, null, null); } public static String doInviteRequest(FromDevice fromDevice, ToDevice toDevice, String contend, String subject) { return doInviteRequest(fromDevice, toDevice, contend, subject, null, null); } public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String contend) { String callId = SipRequestUtils.getNewCallId(); return doInfoRequest(fromDevice, toDevice, contend, callId, null, null); } public static String doInviteRequest(FromDevice fromDevice, ToDevice toDevice, String contend, String subject, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createInviteRequest(fromDevice, toDevice, contend, subject, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String contend, SubscribeInfo subscribeInfo, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createSubscribeRequest(fromDevice, toDevice, contend, subscribeInfo, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String contend, SubscribeInfo subscribeInfo, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createNotifyRequest(fromDevice, toDevice, contend, subscribeInfo, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doMessageRequest(FromDevice fromDevice, ToDevice toDevice, String contend, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createMessageRequest(fromDevice, toDevice, contend, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doByeRequest(FromDevice fromDevice, ToDevice toDevice) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createByeRequest(fromDevice, toDevice, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return callId; } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice) { String callId = SipRequestUtils.getNewCallId(); return doAckRequest(fromDevice, toDevice, callId); } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { Request messageRequest = SipRequestProvider.createAckRequest(fromDevice, toDevice, content, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return callId; } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires) { return doRegisterRequest(fromDevice, toDevice, expires, SipRequestUtils.getNewCallId(), null, null); } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, Event event) { return doRegisterRequest(fromDevice, toDevice, expires, SipRequestUtils.getNewCallId(), event, null); } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, String callId, Event errorEvent, Event okEvent) { Request registerRequest = SipRequestProvider.createRegisterRequest(fromDevice, toDevice, expires, callId); SipSender.transmitRequest(fromDevice.getIp(), registerRequest, errorEvent, okEvent); return callId; } public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { return doInfoRequest(fromDevice, toDevice, content, callId, null, null); } public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId, Event errorEvent, Event okEvent) { Request messageRequest = SipRequestProvider.createInfoRequest(fromDevice, toDevice, content, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { Request messageRequest = SipRequestProvider.createAckRequest(fromDevice, toDevice, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return callId; } public static String doAckRequest(FromDevice fromDevice, SipURI sipURI, SIPResponse sipResponse) { Request messageRequest = SipRequestProvider.createAckRequest(fromDevice, sipURI, sipResponse); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return sipResponse.getCallIdHeader().getCallId(); } public static void transmitRequest(String ip, Message message) { transmitRequest(ip, message, null, null); } public static void transmitRequest(String ip, Message message, Event errorEvent) { transmitRequest(ip, message, errorEvent, null); } public static void transmitRequestSuccess(String ip, Message message, Event okEvent) { transmitRequest(ip, message, null, okEvent); } public static void transmitRequest(String ip, Message message, Event errorEvent, Event okEvent) { ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME); String transport = "UDP"; if (viaHeader == null) { log.warn("[消息头缺失]: ViaHeader, 使用默认的UDP方式处理数据"); } else { transport = viaHeader.getTransport(); } if (message.getHeader(UserAgentHeader.NAME) == null) { message.addHeader(SipRequestUtils.createUserAgentHeader(Constant.AGENT)); } CallIdHeader callIdHeader = (CallIdHeader) message.getHeader(CallIdHeader.NAME); // 添加错误订阅 if (errorEvent != null) {
package io.github.lunasaw.sip.common.transmit; /** * 发送SIP消息 * * @author lin */ @Slf4j @Data public class SipSender { public static String doSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo) { return doSubscribeRequest(fromDevice, toDevice, content, subscribeInfo, null, null); } public static String doMessageRequest(FromDevice fromDevice, ToDevice toDevice, String contend) { return doMessageRequest(fromDevice, toDevice, contend, null, null); } public static String doNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String content, SubscribeInfo subscribeInfo) { return doNotifyRequest(fromDevice, toDevice, content, subscribeInfo, null, null); } public static String doInviteRequest(FromDevice fromDevice, ToDevice toDevice, String contend, String subject) { return doInviteRequest(fromDevice, toDevice, contend, subject, null, null); } public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String contend) { String callId = SipRequestUtils.getNewCallId(); return doInfoRequest(fromDevice, toDevice, contend, callId, null, null); } public static String doInviteRequest(FromDevice fromDevice, ToDevice toDevice, String contend, String subject, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createInviteRequest(fromDevice, toDevice, contend, subject, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doSubscribeRequest(FromDevice fromDevice, ToDevice toDevice, String contend, SubscribeInfo subscribeInfo, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createSubscribeRequest(fromDevice, toDevice, contend, subscribeInfo, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doNotifyRequest(FromDevice fromDevice, ToDevice toDevice, String contend, SubscribeInfo subscribeInfo, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createNotifyRequest(fromDevice, toDevice, contend, subscribeInfo, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doMessageRequest(FromDevice fromDevice, ToDevice toDevice, String contend, Event errorEvent, Event okEvent) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createMessageRequest(fromDevice, toDevice, contend, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doByeRequest(FromDevice fromDevice, ToDevice toDevice) { String callId = SipRequestUtils.getNewCallId(); Request messageRequest = SipRequestProvider.createByeRequest(fromDevice, toDevice, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return callId; } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice) { String callId = SipRequestUtils.getNewCallId(); return doAckRequest(fromDevice, toDevice, callId); } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { Request messageRequest = SipRequestProvider.createAckRequest(fromDevice, toDevice, content, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return callId; } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires) { return doRegisterRequest(fromDevice, toDevice, expires, SipRequestUtils.getNewCallId(), null, null); } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, Event event) { return doRegisterRequest(fromDevice, toDevice, expires, SipRequestUtils.getNewCallId(), event, null); } public static String doRegisterRequest(FromDevice fromDevice, ToDevice toDevice, Integer expires, String callId, Event errorEvent, Event okEvent) { Request registerRequest = SipRequestProvider.createRegisterRequest(fromDevice, toDevice, expires, callId); SipSender.transmitRequest(fromDevice.getIp(), registerRequest, errorEvent, okEvent); return callId; } public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId) { return doInfoRequest(fromDevice, toDevice, content, callId, null, null); } public static String doInfoRequest(FromDevice fromDevice, ToDevice toDevice, String content, String callId, Event errorEvent, Event okEvent) { Request messageRequest = SipRequestProvider.createInfoRequest(fromDevice, toDevice, content, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest, errorEvent, okEvent); return callId; } public static String doAckRequest(FromDevice fromDevice, ToDevice toDevice, String callId) { Request messageRequest = SipRequestProvider.createAckRequest(fromDevice, toDevice, callId); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return callId; } public static String doAckRequest(FromDevice fromDevice, SipURI sipURI, SIPResponse sipResponse) { Request messageRequest = SipRequestProvider.createAckRequest(fromDevice, sipURI, sipResponse); SipSender.transmitRequest(fromDevice.getIp(), messageRequest); return sipResponse.getCallIdHeader().getCallId(); } public static void transmitRequest(String ip, Message message) { transmitRequest(ip, message, null, null); } public static void transmitRequest(String ip, Message message, Event errorEvent) { transmitRequest(ip, message, errorEvent, null); } public static void transmitRequestSuccess(String ip, Message message, Event okEvent) { transmitRequest(ip, message, null, okEvent); } public static void transmitRequest(String ip, Message message, Event errorEvent, Event okEvent) { ViaHeader viaHeader = (ViaHeader) message.getHeader(ViaHeader.NAME); String transport = "UDP"; if (viaHeader == null) { log.warn("[消息头缺失]: ViaHeader, 使用默认的UDP方式处理数据"); } else { transport = viaHeader.getTransport(); } if (message.getHeader(UserAgentHeader.NAME) == null) { message.addHeader(SipRequestUtils.createUserAgentHeader(Constant.AGENT)); } CallIdHeader callIdHeader = (CallIdHeader) message.getHeader(CallIdHeader.NAME); // 添加错误订阅 if (errorEvent != null) {
SipSubscribe.addErrorSubscribe(callIdHeader.getCallId(), (eventResult -> {
6
2023-10-11 06:56:28+00:00
16k
Swofty-Developments/Continued-Slime-World-Manager
swoftyworldmanager-plugin/src/main/java/net/swofty/swm/plugin/loader/LoaderUtils.java
[ { "identifier": "CorruptedWorldException", "path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/CorruptedWorldException.java", "snippet": "public class CorruptedWorldException extends SlimeException {\n\n public CorruptedWorldException(String world) {\n this(world, null)...
import com.flowpowered.nbt.CompoundMap; import com.flowpowered.nbt.CompoundTag; import com.flowpowered.nbt.DoubleTag; import com.flowpowered.nbt.IntArrayTag; import com.flowpowered.nbt.IntTag; import com.flowpowered.nbt.ListTag; import com.flowpowered.nbt.stream.NBTInputStream; import com.github.luben.zstd.Zstd; import net.swofty.swm.api.exceptions.CorruptedWorldException; import net.swofty.swm.api.exceptions.NewerFormatException; import net.swofty.swm.api.loaders.SlimeLoader; import net.swofty.swm.api.utils.NibbleArray; import net.swofty.swm.api.utils.SlimeFormat; import net.swofty.swm.api.world.SlimeChunk; import net.swofty.swm.api.world.SlimeChunkSection; import net.swofty.swm.api.world.properties.SlimePropertyMap; import net.swofty.swm.nms.craft.CraftSlimeChunk; import net.swofty.swm.nms.craft.CraftSlimeChunkSection; import net.swofty.swm.nms.craft.CraftSlimeWorld; import net.swofty.swm.plugin.config.ConfigManager; import net.swofty.swm.plugin.config.DatasourcesConfig; import net.swofty.swm.plugin.loader.loaders.FileLoader; import net.swofty.swm.plugin.loader.loaders.MongoLoader; import net.swofty.swm.plugin.loader.loaders.MysqlLoader; import net.swofty.swm.plugin.log.Logging; import com.mongodb.MongoException; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.sql.SQLException; import java.util.*;
13,920
package net.swofty.swm.plugin.loader; public class LoaderUtils { public static final long MAX_LOCK_TIME = 300000L; // Max time difference between current time millis and world lock public static final long LOCK_INTERVAL = 60000L; private static Map<String, SlimeLoader> loaderMap = new HashMap<>(); public static void registerLoaders() { DatasourcesConfig config = ConfigManager.getDatasourcesConfig(); // File loader DatasourcesConfig.FileConfig fileConfig = config.getFileConfig(); registerLoader("file", new FileLoader(new File(fileConfig.getPath()))); // Mysql loader DatasourcesConfig.MysqlConfig mysqlConfig = config.getMysqlConfig(); if (mysqlConfig.isEnabled()) { try { registerLoader("mysql", new MysqlLoader(mysqlConfig)); } catch (SQLException ex) { Logging.error("Failed to establish connection to the MySQL server:"); ex.printStackTrace(); } } // MongoDB loader DatasourcesConfig.MongoDBConfig mongoConfig = config.getMongoDbConfig(); if (mongoConfig.isEnabled()) { try { registerLoader("mongodb", new MongoLoader(mongoConfig)); } catch (MongoException ex) { Logging.error("Failed to establish connection to the MongoDB server:"); ex.printStackTrace(); } } } public static List<String> getAvailableLoadersNames() { return new LinkedList<>(loaderMap.keySet()); } public static SlimeLoader getLoader(String dataSource) { return loaderMap.get(dataSource); } public static void registerLoader(String dataSource, SlimeLoader loader) { if (loaderMap.containsKey(dataSource)) { throw new IllegalArgumentException("Data source " + dataSource + " already has a declared loader!"); } if (loader instanceof UpdatableLoader) { try { ((UpdatableLoader) loader).update(); } catch (UpdatableLoader.NewerDatabaseException e) { Logging.error("Data source " + dataSource + " version is " + e.getDatabaseVersion() + ", while" + " this SWM version only supports up to version " + e.getCurrentVersion() + "."); return; } catch (IOException ex) { Logging.error("Failed to check if data source " + dataSource + " is updated:"); ex.printStackTrace(); return; } } loaderMap.put(dataSource, loader); }
package net.swofty.swm.plugin.loader; public class LoaderUtils { public static final long MAX_LOCK_TIME = 300000L; // Max time difference between current time millis and world lock public static final long LOCK_INTERVAL = 60000L; private static Map<String, SlimeLoader> loaderMap = new HashMap<>(); public static void registerLoaders() { DatasourcesConfig config = ConfigManager.getDatasourcesConfig(); // File loader DatasourcesConfig.FileConfig fileConfig = config.getFileConfig(); registerLoader("file", new FileLoader(new File(fileConfig.getPath()))); // Mysql loader DatasourcesConfig.MysqlConfig mysqlConfig = config.getMysqlConfig(); if (mysqlConfig.isEnabled()) { try { registerLoader("mysql", new MysqlLoader(mysqlConfig)); } catch (SQLException ex) { Logging.error("Failed to establish connection to the MySQL server:"); ex.printStackTrace(); } } // MongoDB loader DatasourcesConfig.MongoDBConfig mongoConfig = config.getMongoDbConfig(); if (mongoConfig.isEnabled()) { try { registerLoader("mongodb", new MongoLoader(mongoConfig)); } catch (MongoException ex) { Logging.error("Failed to establish connection to the MongoDB server:"); ex.printStackTrace(); } } } public static List<String> getAvailableLoadersNames() { return new LinkedList<>(loaderMap.keySet()); } public static SlimeLoader getLoader(String dataSource) { return loaderMap.get(dataSource); } public static void registerLoader(String dataSource, SlimeLoader loader) { if (loaderMap.containsKey(dataSource)) { throw new IllegalArgumentException("Data source " + dataSource + " already has a declared loader!"); } if (loader instanceof UpdatableLoader) { try { ((UpdatableLoader) loader).update(); } catch (UpdatableLoader.NewerDatabaseException e) { Logging.error("Data source " + dataSource + " version is " + e.getDatabaseVersion() + ", while" + " this SWM version only supports up to version " + e.getCurrentVersion() + "."); return; } catch (IOException ex) { Logging.error("Failed to check if data source " + dataSource + " is updated:"); ex.printStackTrace(); return; } } loaderMap.put(dataSource, loader); }
public static CraftSlimeWorld deserializeWorld(SlimeLoader loader, String worldName, byte[] serializedWorld, SlimePropertyMap propertyMap, boolean readOnly)
7
2023-10-08 10:54:28+00:00
16k
ZJU-ACES-ISE/chatunitest-core
src/main/java/zju/cst/aces/api/impl/RepairImpl.java
[ { "identifier": "Repair", "path": "src/main/java/zju/cst/aces/api/Repair.java", "snippet": "public interface Repair {\n\n String ruleBasedRepair(String code);\n String LLMBasedRepair(String code);\n String LLMBasedRepair(String code, int rounds);\n\n}" }, { "identifier": "Validator", ...
import lombok.Data; import okhttp3.Response; import zju.cst.aces.api.Repair; import zju.cst.aces.api.Validator; import zju.cst.aces.api.config.Config; import zju.cst.aces.dto.PromptInfo; import zju.cst.aces.runner.MethodRunner; import java.io.IOException; import static zju.cst.aces.runner.AbstractRunner.*; import static zju.cst.aces.api.impl.ChatGenerator.*;
12,823
package zju.cst.aces.api.impl; @Data public class RepairImpl implements Repair {
package zju.cst.aces.api.impl; @Data public class RepairImpl implements Repair {
Config config;
2
2023-10-14 07:15:10+00:00
16k
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom
src/gamestates/Playing.java
[ { "identifier": "LevelManager", "path": "src/Level/LevelManager.java", "snippet": "public class LevelManager {\n\n\tprivate Game game;\n\tprivate BufferedImage[] levelSprite;\n\tprivate ArrayList<levels> Levels;\n\tprivate int lvlIndex = 0;\n\n\tpublic LevelManager(Game game) {\n\t\tthis.game = game;\n\...
import Level.LevelManager; import UI.GameOverOverlay; import UI.LevelCompleted; import UI.PauseOverlay; import entities.EnemyManager; import entities.Player; import main.Game; import utilz.LoadSave; import objects.ObjectManager; import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.Random; import static utilz.Constants.Environment.*;
11,878
package gamestates; public class Playing extends State implements Statemethods { private Player player; private LevelManager levelManager; private EnemyManager enemyManager; private PauseOverlay pauseOverlay; private GameOverOverlay gameOverOverlay; private LevelCompleted levelCompleted; private ObjectManager objectManager; private boolean paused = false ; private int xLvlOffset;
package gamestates; public class Playing extends State implements Statemethods { private Player player; private LevelManager levelManager; private EnemyManager enemyManager; private PauseOverlay pauseOverlay; private GameOverOverlay gameOverOverlay; private LevelCompleted levelCompleted; private ObjectManager objectManager; private boolean paused = false ; private int xLvlOffset;
private int leftBorder = (int) (0.2 * Game.GAME_WIDTH);
6
2023-10-07 12:07:45+00:00
16k
yc-huang/bsdb
src/main/java/tech/bsdb/read/AsyncReader.java
[ { "identifier": "Native", "path": "src/main/java/tech/bsdb/io/Native.java", "snippet": "public class Native {\n static Logger logger = LoggerFactory.getLogger(Native.class);\n\n static {\n NativeUtils.loadLibraryFromJar(System.mapLibraryName(\"bsdbjni\"));\n }\n public static clas...
import org.apache.commons.configuration2.Configuration; import tech.bsdb.io.Native; import tech.bsdb.read.index.AsyncDirectIndexReader; import tech.bsdb.read.index.AsyncIndexReader; import tech.bsdb.read.index.AsyncLBufferIndexReader; import tech.bsdb.read.kv.BlockedKVReader; import tech.bsdb.read.kv.CompactKVReader; import tech.bsdb.read.kv.CompressedKVReader; import tech.bsdb.read.kv.KVReader; import tech.bsdb.serde.Field; import tech.bsdb.util.Common; import it.unimi.dsi.fastutil.io.BinIO; import it.unimi.dsi.sux4j.mph.GOVMinimalPerfectHashFunction; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.ex.ConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.nio.channels.CompletionHandler; import java.nio.file.Files;
10,820
package tech.bsdb.read; public class AsyncReader extends Reader { private KVReader kvReader; private final AsyncIndexReader idxReader; Logger logger = LoggerFactory.getLogger(AsyncReader.class); public AsyncReader(File basePath, boolean approximate, boolean indexReadDirect, boolean kvReadDirect) throws IOException, ClassNotFoundException { super(basePath, approximate); boolean useUring = Common.isUringEnabled(); int submitThreads = Common.getPropertyAsInt("bsdb.reader.index.submit.threads", Math.max(Common.CPUS / 2, 2)); //int callbackThreads = Common.getPropertyAsInt("bsdb.reader.index.callback.threads", 1); this.idxReader = indexReadDirect ? new AsyncDirectIndexReader(idxFile, submitThreads, useUring) : new AsyncLBufferIndexReader(idxFile); this.idxCapacity = idxReader.size(); logger.info("idx capacity:{}", idxCapacity); if (!approximate) { Configuration config = getConfig(); this.kvReader = isCompressed() ? new CompressedKVReader(kvFile, config, true, kvReadDirect)
package tech.bsdb.read; public class AsyncReader extends Reader { private KVReader kvReader; private final AsyncIndexReader idxReader; Logger logger = LoggerFactory.getLogger(AsyncReader.class); public AsyncReader(File basePath, boolean approximate, boolean indexReadDirect, boolean kvReadDirect) throws IOException, ClassNotFoundException { super(basePath, approximate); boolean useUring = Common.isUringEnabled(); int submitThreads = Common.getPropertyAsInt("bsdb.reader.index.submit.threads", Math.max(Common.CPUS / 2, 2)); //int callbackThreads = Common.getPropertyAsInt("bsdb.reader.index.callback.threads", 1); this.idxReader = indexReadDirect ? new AsyncDirectIndexReader(idxFile, submitThreads, useUring) : new AsyncLBufferIndexReader(idxFile); this.idxCapacity = idxReader.size(); logger.info("idx capacity:{}", idxCapacity); if (!approximate) { Configuration config = getConfig(); this.kvReader = isCompressed() ? new CompressedKVReader(kvFile, config, true, kvReadDirect)
: isCompact() ? new CompactKVReader(kvFile, config, true, kvReadDirect) : new BlockedKVReader(kvFile, config, true, kvReadDirect);
4
2023-10-07 03:32:27+00:00
16k
wise-old-man/wiseoldman-runelite-plugin
src/main/java/net/wiseoldman/ui/CompetitionInfobox.java
[ { "identifier": "WomUtilsPlugin", "path": "src/main/java/net/wiseoldman/WomUtilsPlugin.java", "snippet": "@Slf4j\n@PluginDependency(XpUpdaterPlugin.class)\n@PluginDescriptor(\n\tname = \"Wise Old Man\",\n\ttags = {\"wom\", \"utils\", \"group\", \"xp\"},\n\tdescription = \"Helps you manage your wiseoldma...
import net.wiseoldman.WomUtilsPlugin; import net.wiseoldman.beans.Competition; import net.wiseoldman.beans.CompetitionProgress; import net.wiseoldman.beans.Metric; import net.wiseoldman.beans.ParticipantWithStanding; import net.wiseoldman.util.Utils; import java.awt.Color; import java.text.DecimalFormat; import java.time.Duration; import net.runelite.api.MenuAction; import net.runelite.client.hiscore.HiscoreSkillType; import net.runelite.client.ui.overlay.OverlayMenuEntry; import net.runelite.client.ui.overlay.infobox.InfoBox; import net.runelite.client.util.ColorUtil; import org.apache.commons.lang3.time.DurationFormatUtils;
13,744
package net.wiseoldman.ui; public class CompetitionInfobox extends InfoBox { final Competition competition; final WomUtilsPlugin plugin; final int rank; final CompetitionProgress progress; private static final Color ACTIVE_COLOR = new Color(0x51f542); public CompetitionInfobox(Competition competition, WomUtilsPlugin plugin) { super(competition.getMetric().loadImage(), plugin); this.competition = competition; this.rank = -1; this.progress = null; this.plugin = plugin; this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.SHOW_ALL_COMPETITIONS, "Wise Old Man")); this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.HIDE_COMPETITION_INFOBOX, competition.getTitle())); } public CompetitionInfobox(ParticipantWithStanding pws, WomUtilsPlugin plugin) { super(pws.getCompetition().getMetric().loadImage(), plugin); this.competition = pws.getCompetition(); this.rank = pws.getRank(); this.progress = pws.getProgress(); this.plugin = plugin; this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.SHOW_ALL_COMPETITIONS, "Wise Old Man")); this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.HIDE_COMPETITION_INFOBOX, competition.getTitle())); } @Override public String getTooltip() { Metric metric = competition.getMetric(); StringBuilder sb = new StringBuilder(); sb.append(competition.getTitle()).append("</br>") .append("Metric: ").append(metric.getName()).append("</br>") .append(competition.getTimeStatus()); if (progress != null) { sb.append("</br>"); double gained = progress.getGained(); if (gained > 0) {
package net.wiseoldman.ui; public class CompetitionInfobox extends InfoBox { final Competition competition; final WomUtilsPlugin plugin; final int rank; final CompetitionProgress progress; private static final Color ACTIVE_COLOR = new Color(0x51f542); public CompetitionInfobox(Competition competition, WomUtilsPlugin plugin) { super(competition.getMetric().loadImage(), plugin); this.competition = competition; this.rank = -1; this.progress = null; this.plugin = plugin; this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.SHOW_ALL_COMPETITIONS, "Wise Old Man")); this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.HIDE_COMPETITION_INFOBOX, competition.getTitle())); } public CompetitionInfobox(ParticipantWithStanding pws, WomUtilsPlugin plugin) { super(pws.getCompetition().getMetric().loadImage(), plugin); this.competition = pws.getCompetition(); this.rank = pws.getRank(); this.progress = pws.getProgress(); this.plugin = plugin; this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.SHOW_ALL_COMPETITIONS, "Wise Old Man")); this.getMenuEntries().add(new OverlayMenuEntry(MenuAction.RUNELITE_INFOBOX, WomUtilsPlugin.HIDE_COMPETITION_INFOBOX, competition.getTitle())); } @Override public String getTooltip() { Metric metric = competition.getMetric(); StringBuilder sb = new StringBuilder(); sb.append(competition.getTitle()).append("</br>") .append("Metric: ").append(metric.getName()).append("</br>") .append(competition.getTimeStatus()); if (progress != null) { sb.append("</br>"); double gained = progress.getGained(); if (gained > 0) {
String coloredRank = ColorUtil.wrapWithColorTag(Utils.ordinalOf(rank), Color.GREEN);
5
2023-10-09 14:23:06+00:00
16k
PeytonPlayz595/c0.0.23a_01
src/main/java/com/mojang/minecraft/level/tile/Bush.java
[ { "identifier": "Level", "path": "src/main/java/com/mojang/minecraft/level/Level.java", "snippet": "public class Level implements Serializable {\n\tpublic static final long serialVersionUID = 0L;\n\tpublic int width;\n\tpublic int height;\n\tpublic int depth;\n\tpublic byte[] blocks;\n\tpublic String na...
import com.mojang.minecraft.level.Level; import com.mojang.minecraft.phys.AABB; import com.mojang.minecraft.renderer.Tesselator; import java.util.Random;
12,972
package com.mojang.minecraft.level.tile; public final class Bush extends Tile { protected Bush(int var1, int var2) { super(var1); this.tex = var2; this.setTicking(true); } public final void tick(Level var1, int var2, int var3, int var4, Random var5) { int var6 = var1.getTile(var2, var3 - 1, var4); if(!var1.isLit(var2, var3, var4) || var6 != Tile.dirt.id && var6 != Tile.grass.id) { var1.setTile(var2, var3, var4, 0); } }
package com.mojang.minecraft.level.tile; public final class Bush extends Tile { protected Bush(int var1, int var2) { super(var1); this.tex = var2; this.setTicking(true); } public final void tick(Level var1, int var2, int var3, int var4, Random var5) { int var6 = var1.getTile(var2, var3 - 1, var4); if(!var1.isLit(var2, var3, var4) || var6 != Tile.dirt.id && var6 != Tile.grass.id) { var1.setTile(var2, var3, var4, 0); } }
public final boolean render(Tesselator var1, Level var2, int var3, int var4, int var5, int var6) {
2
2023-10-10 17:10:45+00:00
16k
ProfessorFichte/More-RPG-Classes
src/main/java/net/more_rpg_classes/MRPGCMod.java
[ { "identifier": "MoreParticles", "path": "src/main/java/net/more_rpg_classes/client/particle/MoreParticles.java", "snippet": "public class MoreParticles {\n public static final DefaultParticleType IGNI_SIGN = FabricParticleTypes.simple();\n public static final DefaultParticleType AARD_SIGN = Fabri...
import net.fabricmc.api.ModInitializer; import net.more_rpg_classes.client.particle.MoreParticles; import net.more_rpg_classes.custom.custom_spells.CustomSpells; import net.more_rpg_classes.effect.MRPGCEffects; import net.more_rpg_classes.entity.attribute.MRPGCEntityAttributes; import net.more_rpg_classes.item.MRPGCBooks; import net.more_rpg_classes.item.MRPGCGroup; import net.more_rpg_classes.item.MRPGCItems; import net.more_rpg_classes.sounds.ModSounds; import net.more_rpg_classes.util.MRPGCLootTableChestModifiers; import net.more_rpg_classes.util.MRPGCLootTableEntityModifiers; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
11,461
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() { MRPGCItems.registerModItems(); MRPGCGroup.registerItemGroups(); MRPGCLootTableEntityModifiers.modifyLootEntityTables(); MRPGCLootTableChestModifiers.modifyChestLootTables(); MRPGCEffects.register();
package net.more_rpg_classes; public class MRPGCMod implements ModInitializer { public static final String MOD_ID = "more_rpg_classes"; public static final Logger LOGGER = LoggerFactory.getLogger("more_rpg_classes"); @Override public void onInitialize() { MRPGCItems.registerModItems(); MRPGCGroup.registerItemGroups(); MRPGCLootTableEntityModifiers.modifyLootEntityTables(); MRPGCLootTableChestModifiers.modifyChestLootTables(); MRPGCEffects.register();
MRPGCBooks.register();
4
2023-10-14 12:44:07+00:00
16k
5152Alotobots/2024_Crescendo_Preseason
src/main/java/frc/robot/chargedup/commands/auto/doubleelement/Auto_middleredconeleftescape_Cmd.java
[ { "identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj", "path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java", "snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_Dr...
import edu.wpi.first.wpilibj.DriverStation.Alliance; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.ParallelCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj; import frc.robot.chargedup.subsystems.arm.SubSys_Arm; import frc.robot.chargedup.subsystems.arm.commands.Cmd_SubSys_Arm_RotateAndExtend; import frc.robot.chargedup.subsystems.hand.SubSys_Hand; import frc.robot.library.drivetrains.SubSys_DriveTrain; import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro;
13,368
// 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. /* _____ _ / ____| /\ | | | (___ ___ __ _ _ __ / \ _ __ _ __ _ __ _____ _____ __| | \___ \ / _ \/ _` | '_ \ / /\ \ | '_ \| '_ \| '__/ _ \ \ / / _ \/ _` | ____) | __/ (_| | | | | / ____ \| |_) | |_) | | | (_) \ V / __/ (_| | |_____/ \___|\__,_|_| |_| /_/ \_\ .__/| .__/|_| \___/ \_/ \___|\__,_| | | | | |_| |_| */ package frc.robot.chargedup.commands.auto.doubleelement; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_middleredconeleftescape_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain;
// 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. /* _____ _ / ____| /\ | | | (___ ___ __ _ _ __ / \ _ __ _ __ _ __ _____ _____ __| | \___ \ / _ \/ _` | '_ \ / /\ \ | '_ \| '_ \| '__/ _ \ \ / / _ \/ _` | ____) | __/ (_| | | | | / ____ \| |_) | |_) | | | (_) \ V / __/ (_| | |_____/ \___|\__,_|_| |_| /_/ \_\ .__/| .__/|_| \___/ \_/ \___|\__,_| | | | | |_| |_| */ package frc.robot.chargedup.commands.auto.doubleelement; /** * *Link For PathPlaner * * https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e65ac68f1d_0_48 */ public class Auto_middleredconeleftescape_Cmd extends SequentialCommandGroup { private final SubSys_DriveTrain m_DriveTrain;
private final SubSys_PigeonGyro m_pigeonGyro;
5
2023-10-09 00:27:11+00:00
16k
nexus3a/monitor-remote-agent
src/main/java/com/monitor/agent/server/handler/AckHandler.java
[ { "identifier": "FileState", "path": "src/main/java/com/monitor/agent/server/FileState.java", "snippet": "public class FileState {\n\n @JsonIgnore\n private File file;\n private String directory;\n private String fileName;\n @JsonIgnore\n private long lastModified;\n @JsonIgnore\n ...
import com.monitor.agent.server.FileState; import com.monitor.agent.server.FileWatcher; import com.monitor.agent.server.Registrar; import com.monitor.agent.server.Section; import com.monitor.agent.server.Server; import fi.iki.elonen.NanoHTTPD; import fi.iki.elonen.router.RouterNanoHTTPD; import java.util.Collection; import java.util.Map;
11,763
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class AckHandler extends DefaultResponder { @Override @SuppressWarnings("UseSpecificCatch") public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидания снятия сервера с паузы try { RequestParameters parameters = getParameters(); // получаем секцию, в пределах которой нужно подтввердить получение данных // String sectionName = (String) parameters.get("section", null); Section section = Section.byName(sectionName); Object sectionLock = section == null ? server : section; synchronized (sectionLock) { Collection<FileWatcher> watchers = server.getWatchers(Section.byName(sectionName)); // подтверждаем факт успешного приёма предыдущей порции данных: // переустанавливаем указатели файлов в рабочее положение // for (FileWatcher watcher : watchers) { synchronized (watcher) {
package com.monitor.agent.server.handler; /* * Copyright 2022 Aleksei Andreev * * 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. * */ public class AckHandler extends DefaultResponder { @Override @SuppressWarnings("UseSpecificCatch") public NanoHTTPD.Response get( RouterNanoHTTPD.UriResource uriResource, Map<String, String> urlParams, NanoHTTPD.IHTTPSession session) { super.get(uriResource, urlParams, session); Server server = uriResource.initParameter(Server.class); server.waitForUnpause(); // ожидания снятия сервера с паузы try { RequestParameters parameters = getParameters(); // получаем секцию, в пределах которой нужно подтввердить получение данных // String sectionName = (String) parameters.get("section", null); Section section = Section.byName(sectionName); Object sectionLock = section == null ? server : section; synchronized (sectionLock) { Collection<FileWatcher> watchers = server.getWatchers(Section.byName(sectionName)); // подтверждаем факт успешного приёма предыдущей порции данных: // переустанавливаем указатели файлов в рабочее положение // for (FileWatcher watcher : watchers) { synchronized (watcher) {
Collection<FileState> states = watcher.getWatched();
0
2023-10-11 20:25:12+00:00
16k
mhaupt/basicode
src/main/java/de/haupz/basicode/ast/GosubNode.java
[ { "identifier": "InterpreterState", "path": "src/main/java/de/haupz/basicode/interpreter/InterpreterState.java", "snippet": "public class InterpreterState {\n\n /**\n * The root node of the program whose state this instance represents.\n */\n private final ProgramNode program;\n\n /**\n...
import de.haupz.basicode.interpreter.InterpreterState; import de.haupz.basicode.subroutines.Subroutines;
12,596
package de.haupz.basicode.ast; /** * <p>{@code GOSUB}. The implementation pushes the {@linkplain InterpreterState#getStatementIndex() statement index} of * the return address and performs a {@linkplain InterpreterState#requestLineJump() jump} to the * {@linkplain InterpreterState#setLineJumpTarget(int)} target line.</p> * * <p>In case the target line number is less than 1000, a call to a {@linkplain Subroutines subroutine} is executed * instead of the normal {@code GOSUB}.</p> */ public class GosubNode extends StatementNode { /** * The target line number. */ private int target; public GosubNode(int target) { this.target = target; } @Override
package de.haupz.basicode.ast; /** * <p>{@code GOSUB}. The implementation pushes the {@linkplain InterpreterState#getStatementIndex() statement index} of * the return address and performs a {@linkplain InterpreterState#requestLineJump() jump} to the * {@linkplain InterpreterState#setLineJumpTarget(int)} target line.</p> * * <p>In case the target line number is less than 1000, a call to a {@linkplain Subroutines subroutine} is executed * instead of the normal {@code GOSUB}.</p> */ public class GosubNode extends StatementNode { /** * The target line number. */ private int target; public GosubNode(int target) { this.target = target; } @Override
public void run(InterpreterState state) {
0
2023-10-14 12:20:59+00:00
16k