text
stringlengths
184
4.48M
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.function.DoubleSupplier; import com.pathplanner.lib.PathPlanner; import com.pathplanner.lib.PathPlannerTrajectory; import com.pathplanner.lib.auto.PIDConstants; import com.pathplanner.lib.auto.SwerveAutoBuilder; import edu.wpi.first.cameraserver.CameraServer; import edu.wpi.first.cscore.CameraServerCvJNI; import edu.wpi.first.cscore.UsbCamera; import edu.wpi.first.wpilibj.Compressor; import edu.wpi.first.wpilibj.PneumaticsModuleType; import edu.wpi.first.wpilibj.XboxController; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Commands; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.button.CommandXboxController; import edu.wpi.first.wpilibj2.command.button.Trigger; import frc.robot.commands.autonomous.YawTest; import frc.robot.commands.autonomous.arm.AutoOutputPiece; import frc.robot.commands.autonomous.drive.ConeNodeAlign; import frc.robot.commands.autonomous.drive.MoveX; import frc.robot.commands.autonomous.groups.ForwardDock; import frc.robot.commands.autonomous.groups.MoveConeAlignedPlaceHigh; import frc.robot.commands.autonomous.groups.PlaceAndDock; import frc.robot.commands.autonomous.groups.PlaceConeHigh; import frc.robot.commands.autonomous.groups.PlaceConeOut; import frc.robot.commands.autonomous.groups.PlaceCubeOut; import frc.robot.commands.autonomous.groups.PlaceCubeHigh; import frc.robot.commands.autonomous.groups.PlaceMobilityDock; import frc.robot.commands.autonomous.groups.PlacePieceLow; import frc.robot.commands.intake.arm.MoveArm; import frc.robot.commands.intake.arm.MoveWrist; import frc.robot.commands.intake.arm.positions.CollapseArm; import frc.robot.commands.intake.arm.positions.pickup.PickupChute; import frc.robot.commands.intake.arm.positions.pickup.PickupShelf; import frc.robot.commands.intake.arm.positions.pickup.PickupTipped; import frc.robot.commands.intake.arm.positions.placing.PlaceHigh; import frc.robot.commands.intake.arm.positions.placing.PlaceLow; import frc.robot.commands.intake.arm.positions.placing.PlaceMed; import frc.robot.commands.intake.grip.CloseGrip; import frc.robot.commands.intake.grip.IntakePiece; import frc.robot.commands.intake.grip.OpenGrip; import frc.robot.commands.intake.grip.OutputPiece; import frc.robot.commands.swerve.AbsoluteDrive3Axis; import frc.robot.commands.swerve.RecenterRotation; import frc.robot.commands.swerve.SnapRotation; import frc.robot.commands.swerve.SwerveAutobalance; import frc.robot.commands.swerve.SwerveBrake; // import frc.robot.commands.swerve.TeleopDrive; import frc.robot.settings.Constants; import frc.robot.settings.Constants.Drivetrains.Swerve.Paths; import frc.robot.settings.DashboardConfig; import frc.robot.subsystems.EdgeDetector; import frc.robot.subsystems.Lights; import frc.robot.subsystems.Limelight; import frc.robot.subsystems.drivetrains.SwerveContainer; import frc.robot.subsystems.intake.Arm; import frc.robot.subsystems.intake.Grip; public class RobotContainer { private final DashboardConfig config; // Declare subsystems private final SwerveContainer swerveDrive; private final Arm arm; private final Grip grip; final Lights lights = new Lights(); private EdgeDetector edgeDetector; private Limelight limelight; private final Compressor airCompressor = new Compressor(Constants.Intake.Ports.COMPRESSOR, PneumaticsModuleType.CTREPCM); private final UsbCamera camera = CameraServer.startAutomaticCapture(); private SendableChooser<Command> autonomousDropDown; // Declare controllers // private Joystick driverStick = new Joystick(Constants.Controllers.DRIVER_JOYSTICK_PORT); // private Joystick driverWheel = new Joystick(Constants.Controllers.DRIVER_WHEEL_PORT); private CommandXboxController driverController = new CommandXboxController(0); private CommandXboxController codriverController = new CommandXboxController(1); // Globally loaded path planner stuff private SwerveAutoBuilder pathBuilder; private HashMap<String, Command> commandMap; public RobotContainer() { config = new DashboardConfig(); camera.setResolution(640, 480); swerveDrive = new SwerveContainer(); arm = new Arm(); grip = new Grip(); limelight = new Limelight(); edgeDetector = new EdgeDetector(); configureBindings(); configureCommands(); // Set default commands } private DoubleSupplier axisDeadband(CommandXboxController controller, int axis, double deadband, boolean inverted, double multiplier) { double invertedMultiplier = inverted ? -multiplier : multiplier; return () -> ( Math.abs(controller.getRawAxis(axis)) > deadband ) ? controller.getRawAxis(axis) * invertedMultiplier : 0; } private void configureBindings() { // DRIVER CONTROLS // Driving the robot: left stick for movement, right stick for turning, LB to quarter speed swerveDrive.setDefaultCommand(new AbsoluteDrive3Axis( swerveDrive, axisDeadband(driverController, XboxController.Axis.kLeftY.value, Constants.Controllers.joystickDeadband, true, 1.0), axisDeadband(driverController, XboxController.Axis.kLeftX.value, Constants.Controllers.joystickDeadband, true, 1.0), axisDeadband(driverController, XboxController.Axis.kRightX.value, Constants.Controllers.wheelDeadband, false, 1.0) )); driverController.rightBumper().whileTrue(new AbsoluteDrive3Axis( swerveDrive, axisDeadband(driverController, XboxController.Axis.kLeftY.value, Constants.Controllers.joystickDeadband, true, 0.5), axisDeadband(driverController, XboxController.Axis.kLeftX.value, Constants.Controllers.joystickDeadband, true, 0.5), axisDeadband(driverController, XboxController.Axis.kRightX.value, Constants.Controllers.wheelDeadband, false, 0.5) )); // swerveDrive.setDefaultCommand(new TeleopDrive( // swerveDrive, // axisDeadband( // driverController, // XboxController.Axis.kLeftY.value, // Constants.Controllers.joystickDeadband, // true, // 1.0 // ), // axisDeadband( // driverController, // XboxController.Axis.kLeftX.value, // Constants.Controllers.joystickDeadband, // true, // 1.0 // ), // axisDeadband( // driverController, // XboxController.Axis.kRightX.value, // Constants.Controllers.wheelDeadband, // false, // 1.0 // ), // () -> true, // Constants.Drivetrains.Swerve.OPEN_LOOP, // true // )); // Manipulating the claw: A to open, B to close; // RT to drive forward, LT to drive backward // driverController.a().onTrue(new OpenGrip(grip)); // driverController.b().onTrue(new CloseGrip(grip)); driverController.x().onTrue(new MoveConeAlignedPlaceHigh( new AbsoluteDrive3Axis( swerveDrive, axisDeadband(driverController, XboxController.Axis.kLeftY.value, Constants.Controllers.joystickDeadband, true, 0.5), axisDeadband(driverController, XboxController.Axis.kLeftX.value, Constants.Controllers.joystickDeadband, true, 0.5), axisDeadband(driverController, XboxController.Axis.kRightX.value, Constants.Controllers.wheelDeadband, false, 0.5) ), limelight, arm, grip )); driverController.y().onTrue(new RecenterRotation(swerveDrive)); driverController.leftBumper().onTrue(new OpenGrip(grip)); driverController.leftBumper().onFalse(new CloseGrip(grip)); // driverController.rightBumper().whileTrue(new SwerveBrake(swerveDrive)); driverController.rightTrigger().whileTrue(new IntakePiece(grip)); driverController.leftTrigger().whileTrue(new OutputPiece(grip)); driverController.povUp().onTrue(new SnapRotation(swerveDrive, 0)); driverController.povRight().onTrue(new SnapRotation(swerveDrive, (0.5 * Math.PI))); driverController.povDown().onTrue(new SnapRotation(swerveDrive, (1 * Math.PI))); driverController.povLeft().onTrue(new SnapRotation(swerveDrive, (1.5 * Math.PI))); // CODRIVER CONTROLS // Triggers if any dpad position is hit, except for middle (untouched dpad) Trigger hitPov = codriverController.povUp() .or(codriverController.povUpRight()) .or(codriverController.povRight()) .or(codriverController.povDownRight()) .or(codriverController.povDown()) .or(codriverController.povDownLeft()) .or(codriverController.povLeft()) .or(codriverController.povUpLeft()); // Auto moving the arm: DPad to collapse it, A/X/Y to move the arm Low/Med/High hitPov.onTrue(new CollapseArm(arm, lights)); codriverController.a().onTrue(new PlaceLow(arm, lights)); codriverController.x().onTrue(new PlaceMed(arm, lights)); codriverController.y().onTrue(new PlaceHigh(arm, lights)); // Pickup Moves: B to tip the arm down, LB to pick up from the shelf, // RB to pick up from the chute codriverController.b().onTrue(new PickupTipped(arm, lights)); codriverController.leftBumper().onTrue(new PickupChute(arm, lights)); codriverController.rightBumper().onTrue(new PickupShelf(arm, lights)); // Manually moving the arm: Left Stick Y for moving the arm, Right Stick Y // for moving the wrist codriverController.rightTrigger().whileTrue(new MoveArm( arm, axisDeadband( codriverController, XboxController.Axis.kLeftY.value, 0.1, false, 1.0 ) )); codriverController.leftTrigger().whileTrue(new MoveWrist( arm, axisDeadband( codriverController, XboxController.Axis.kRightY.value, 0.1, false, 1.0 ) )); } private void configureCommands() { // commandMap = new HashMap<>(); // // Connect markers in the path file to our auton commands // commandMap.put("collapseArm", new AutoCollapseArmLong(arm, lights)); // commandMap.put("placeLow", new AutoPlaceLow(arm, lights)); // commandMap.put("outputPiece", new AutoOutputPiece(grip)); // commandMap.put("autobalance", new SwerveAutobalance(swerveDrive)); // commandMap.put("lazyAutobalance", new ForwardDock(swerveDrive)); // commandMap.put("backAutobalance", new BackwardDock(swerveDrive)); // pathBuilder = new SwerveAutoBuilder( // swerveDrive::getPose, // swerveDrive::resetPose, // new PIDConstants(0.1, 0, 0), // new PIDConstants(0.02, 0, 0.0005), // swerveDrive::setChassisSpeeds, // commandMap, // true, // swerveDrive // ); // PathPlannerTrajectory pio = PathPlanner.loadPath(Paths.PIO, 1, 1); // PathPlannerTrajectory wio = PathPlanner.loadPath(Paths.WIO, 1, 1); // PathPlannerTrajectory cioda = PathPlanner.loadPath(Paths.CIODA, 1, 1); // PathPlannerTrajectory ciodn = PathPlanner.loadPath(Paths.CIODN, 1, 1); // PathPlannerTrajectory out = PathPlanner.loadPath("[Either Side] Out", 1, 1); // PathPlannerTrajectory blueCenterDock = PathPlanner.loadPath("[Center] Dock", 1, 1); // List<PathPlannerTrajectory> brokenL = new ArrayList<PathPlannerTrajectory>(); // brokenL.add(PathPlanner.loadPath("Move Right", 1, 1)); // brokenL.add(PathPlanner.loadPath("Move Out Far", 1, 1)); // PathPlannerTrajectory bpio = PathPlanner.loadPath("[Blue Pickup Side] In, Out", 1, 1); // PathPlannerTrajectory bwio = PathPlanner.loadPath("[Blue Wire Side] In, Out", 1, 1); autonomousDropDown = new SendableChooser<>(); // autonomousDropDown.setDefaultOption(Paths.PIO, pathBuilder.fullAuto(pio)); // autonomousDropDown.addOption(Paths.WIO, pathBuilder.fullAuto(wio)); // autonomousDropDown.addOption(Paths.CIODA, pathBuilder.fullAuto(cioda)); // autonomousDropDown.addOption(Paths.CIODN, pathBuilder.fullAuto(ciodn)); // autonomousDropDown.addOption("[Blue Pickup Side] In, Out", pathBuilder.fullAuto(bpio)); // autonomousDropDown.addOption("[Blue Wire Side] In, Out", pathBuilder.fullAuto(bwio)); // autonomousDropDown.addOption("Broken L Right", pathBuilder.fullAuto(brokenL)); // autonomousDropDown.addOption("[Center] Dock", pathBuilder.followPath(blueCenterDock)); // autonomousDropDown.addOption("[Either Side] Out", pathBuilder.fullAuto(out)); // autonomousDropDown.addOption("Place Piece Low", new PlacePieceLow(arm, grip, lights)); autonomousDropDown.addOption("Place Cube High", new PlaceCubeHigh(arm, grip, lights)); // autonomousDropDown.addOption("Place Cone High", new PlaceConeHigh(arm, grip, lights)); // autonomousDropDown.addOption("Dock", new ForwardDock(swerveDrive, lights)); autonomousDropDown.addOption("Place Cube, Mobility", new PlaceCubeOut(swerveDrive, arm, grip, lights)); autonomousDropDown.addOption("Place Cone, Mobility", new PlaceConeOut(swerveDrive, arm, grip, lights)); autonomousDropDown.addOption("Place Cube High and Dock", new PlaceAndDock(arm, grip, swerveDrive, lights)); autonomousDropDown.addOption("Place Cube, Mobility, Dock", new PlaceMobilityDock(swerveDrive, arm, grip, lights)); // autonomousDropDown.addOption("Yaw Test", new YawTest(swerveDrive)); // autonomousDropDown.addOption("Move Test", new SequentialCommandGroup(new PlaceCubeHigh(arm, grip, lights), new MoveX(swerveDrive, 4))); autonomousDropDown.addOption("Retroreflect Test", new ConeNodeAlign(swerveDrive, limelight)); SmartDashboard.putData("Auton Routine", autonomousDropDown); } public Command getAutonomousCommand() { Command command = autonomousDropDown.getSelected(); if(command == null) { return Commands.print("No autonomous command selected."); } return command; } public void unbrake() { swerveDrive.setBrakes(false); } }
----------------------------------------------------------------------------- -- Syed Fahimuddin Alavi -- AES Encryption -- https://www.github.com/fahimalavi ----------------------------------------------------------------------------- -- -- unit name: aes_encryption.vhdl -- -- description: -- -- This unit implements the encryption of the AES algorithm, it's pre-req is -- the key expansion present in the same directory. ----------------------------------------------------------------------------- -- Copyright (c) 2023 Syed Fahimuddin Alavi ----------------------------------------------------------------------------- -- MIT License ----------------------------------------------------------------------------- -- 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. ----------------------------------------------------------------------------- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; ENTITY AES_ENCRYPTION is PORT( CLK :in std_logic; RESET :in std_logic; CONFIG :in std_logic_vector(1 downto 0); ENCRYPT_ENABLE :in std_logic; EXP_KEYS_PRESENT :in std_logic; INITIAL_KEY :in std_logic_vector(127 downto 0); PLAIN_TEXT :in std_logic_vector(127 downto 0); KEYS_EXP :in std_logic_vector(1279 downto 0); CIPHER :out std_logic_vector(127 downto 0); ENCRYPTION_STATUS :out std_logic ); END AES_ENCRYPTION; Architecture RTL of AES_ENCRYPTION is ----------------------------------------------------------------------------- -- Type definitions ----------------------------------------------------------------------------- type ByteArray is array (0 to 255) of std_logic_vector(7 downto 0); type RowArray is array (0 to 3) of std_logic_vector(7 downto 0); ----------------------------------------------------------------------------- -- Constants ----------------------------------------------------------------------------- constant SBOX : ByteArray := ( x"63", x"7c", x"77", x"7b", x"f2", x"6b", x"6f", x"c5", x"30", x"01", x"67", x"2b", x"fe", x"d7", x"ab", x"76", x"ca", x"82", x"c9", x"7d", x"fa", x"59", x"47", x"f0", x"ad", x"d4", x"a2", x"af", x"9c", x"a4", x"72", x"c0", x"b7", x"fd", x"93", x"26", x"36", x"3f", x"f7", x"cc", x"34", x"a5", x"e5", x"f1", x"71", x"d8", x"31", x"15", x"04", x"c7", x"23", x"c3", x"18", x"96", x"05", x"9a", x"07", x"12", x"80", x"e2", x"eb", x"27", x"b2", x"75", x"09", x"83", x"2c", x"1a", x"1b", x"6e", x"5a", x"a0", x"52", x"3b", x"d6", x"b3", x"29", x"e3", x"2f", x"84", x"53", x"d1", x"00", x"ed", x"20", x"fc", x"b1", x"5b", x"6a", x"cb", x"be", x"39", x"4a", x"4c", x"58", x"cf", x"d0", x"ef", x"aa", x"fb", x"43", x"4d", x"33", x"85", x"45", x"f9", x"02", x"7f", x"50", x"3c", x"9f", x"a8", x"51", x"a3", x"40", x"8f", x"92", x"9d", x"38", x"f5", x"bc", x"b6", x"da", x"21", x"10", x"ff", x"f3", x"d2", x"cd", x"0c", x"13", x"ec", x"5f", x"97", x"44", x"17", x"c4", x"a7", x"7e", x"3d", x"64", x"5d", x"19", x"73", x"60", x"81", x"4f", x"dc", x"22", x"2a", x"90", x"88", x"46", x"ee", x"b8", x"14", x"de", x"5e", x"0b", x"db", x"e0", x"32", x"3a", x"0a", x"49", x"06", x"24", x"5c", x"c2", x"d3", x"ac", x"62", x"91", x"95", x"e4", x"79", x"e7", x"c8", x"37", x"6d", x"8d", x"d5", x"4e", x"a9", x"6c", x"56", x"f4", x"ea", x"65", x"7a", x"ae", x"08", x"ba", x"78", x"25", x"2e", x"1c", x"a6", x"b4", x"c6", x"e8", x"dd", x"74", x"1f", x"4b", x"bd", x"8b", x"8a", x"70", x"3e", x"b5", x"66", x"48", x"03", x"f6", x"0e", x"61", x"35", x"57", x"b9", x"86", x"c1", x"1d", x"9e", x"e1", x"f8", x"98", x"11", x"69", x"d9", x"8e", x"94", x"9b", x"1e", x"87", x"e9", x"ce", x"55", x"28", x"df", x"8c", x"a1", x"89", x"0d", x"bf", x"e6", x"42", x"68", x"41", x"99", x"2d", x"0f", x"b0", x"54", x"bb", x"16"); constant IRREDUCIBLE_POLY : std_logic_vector(7 downto 0) := x"1B"; -- X^4 + X^3 + X + 1 constant ROUNDS_COUNT : natural := 10; TYPE Tstate IS (STATE_INIT, STATE_INIT_KEY, STATE_SBOX, STATE_MIXROWS, STATE_MIXCOLOUMN, STATE_ADD_ROUNDKEY, STATE_COMPLETE); SIGNAL FSM_STATE: Tstate := STATE_INIT; SIGNAL current_round_data: std_logic_vector(127 downto 0) := (others => '0'); begin PROCESS (CLK, RESET) VARIABLE round: natural range 0 to 10 := 0; BEGIN IF CLK'event and rising_edge(CLK) THEN IF RESET='0' THEN FSM_STATE <=STATE_INIT; else CASE FSM_STATE IS WHEN STATE_INIT => round := 0; CIPHER <= x"00000000000000000000000000000000"; ENCRYPTION_STATUS <= '0'; if(ENCRYPT_ENABLE='1' and EXP_KEYS_PRESENT='1') then current_round_data <= INITIAL_KEY xor PLAIN_TEXT; FSM_STATE <= STATE_SBOX; else current_round_data <= (others => '1'); FSM_STATE <= STATE_INIT; end if; WHEN STATE_SBOX => round := round + 1; CIPHER <= current_round_data; ENCRYPTION_STATUS <= '0'; current_round_data(127 downto 120) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(127 downto 120))))); current_round_data(119 downto 112) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(119 downto 112))))); current_round_data(111 downto 104) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(111 downto 104))))); current_round_data(103 downto 96) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(103 downto 96))))); current_round_data(95 downto 88) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(95 downto 88))))); current_round_data(87 downto 80) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(87 downto 80))))); current_round_data(79 downto 72) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(79 downto 72))))); current_round_data(71 downto 64) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(71 downto 64))))); current_round_data(63 downto 56) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(63 downto 56))))); current_round_data(55 downto 48) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(55 downto 48))))); current_round_data(47 downto 40) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(47 downto 40))))); current_round_data(39 downto 32) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(39 downto 32))))); current_round_data(31 downto 24) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(31 downto 24))))); current_round_data(23 downto 16) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(23 downto 16))))); current_round_data(15 downto 8) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(15 downto 8))))); current_round_data(7 downto 0) <= std_logic_vector(SBOX(to_integer(unsigned(current_round_data(7 downto 0))))); FSM_STATE <= STATE_MIXROWS; WHEN STATE_MIXROWS => CIPHER <= current_round_data; ENCRYPTION_STATUS <= '0'; -- ShiftRows() cyclically shifts the last three rows in the State. -- R0 -- R1 current_round_data(119 downto 112) <= current_round_data(87 downto 80); current_round_data(87 downto 80) <= current_round_data(55 downto 48); current_round_data(55 downto 48) <= current_round_data(23 downto 16); current_round_data(23 downto 16) <= current_round_data(119 downto 112); -- R2 current_round_data(111 downto 104) <= current_round_data(47 downto 40); current_round_data(79 downto 72) <= current_round_data(15 downto 8); current_round_data(47 downto 40) <= current_round_data(111 downto 104); current_round_data(15 downto 8) <= current_round_data(79 downto 72); -- R3 current_round_data(103 downto 96) <= current_round_data(7 downto 0); current_round_data(71 downto 64) <= current_round_data(103 downto 96); current_round_data(39 downto 32) <= current_round_data(71 downto 64); current_round_data(7 downto 0) <= current_round_data(39 downto 32); if(round = 10) then FSM_STATE <= STATE_ADD_ROUNDKEY; else FSM_STATE <= STATE_MIXCOLOUMN; end if; WHEN STATE_MIXCOLOUMN => CIPHER <= current_round_data; ENCRYPTION_STATUS <= '0'; for i in 3 downto 0 loop -- constant MIX_C_MATRIX_R1 : RowArray := (x"02",x"03",x"01",x"01"); if(current_round_data((i*32)+31)='0') then if (current_round_data((i*32)+23) = '0') then current_round_data((i*32)+31 downto (i*32)+24) <= std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor current_round_data((i*32)+23 downto (i*32)+16)) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+7 downto (i*32)); else current_round_data((i*32)+31 downto (i*32)+24) <= std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor current_round_data((i*32)+23 downto (i*32)+16) xor IRREDUCIBLE_POLY) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+7 downto (i*32)); end if; else if (current_round_data((i*32)+23) = '0') then current_round_data((i*32)+31 downto (i*32)+24) <= (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor IRREDUCIBLE_POLY) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor current_round_data((i*32)+23 downto (i*32)+16)) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+7 downto (i*32)); else current_round_data((i*32)+31 downto (i*32)+24) <= (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor IRREDUCIBLE_POLY) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor current_round_data((i*32)+23 downto (i*32)+16) xor IRREDUCIBLE_POLY) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+7 downto (i*32)); end if; end if; -- constant MIX_C_MATRIX_R2 : RowArray := (x"01",x"02",x"03",x"01"); if(current_round_data((i*32)+23)='0') then if (current_round_data((i*32)+15) = '0') then current_round_data((i*32)+23 downto (i*32)+16) <= current_round_data((i*32)+31 downto (i*32)+24) xor std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1)) xor current_round_data((i*32)+15 downto (i*32)+8)) xor current_round_data((i*32)+7 downto (i*32)); else current_round_data((i*32)+23 downto (i*32)+16) <= current_round_data((i*32)+31 downto (i*32)+24) xor std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1)) xor current_round_data((i*32)+15 downto (i*32)+8) xor IRREDUCIBLE_POLY) xor current_round_data((i*32)+7 downto (i*32)); end if; else if (current_round_data((i*32)+15) = '0') then current_round_data((i*32)+23 downto (i*32)+16) <= current_round_data((i*32)+31 downto (i*32)+24) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor IRREDUCIBLE_POLY) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1)) xor current_round_data((i*32)+15 downto (i*32)+8)) xor current_round_data((i*32)+7 downto (i*32)); else current_round_data((i*32)+23 downto (i*32)+16) <= current_round_data((i*32)+31 downto (i*32)+24) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+23 downto (i*32)+16)),1)) xor IRREDUCIBLE_POLY) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1)) xor current_round_data((i*32)+15 downto (i*32)+8) xor IRREDUCIBLE_POLY) xor current_round_data((i*32)+7 downto (i*32)); end if; end if; -- constant MIX_C_MATRIX_R3 : RowArray := (x"01",x"01",x"02",x"03"); if(current_round_data((i*32)+15)='0') then if (current_round_data((i*32)+7) = '0') then current_round_data((i*32)+15 downto (i*32)+8) <= current_round_data((i*32)+31 downto (i*32)+24) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1))) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1)) xor current_round_data((i*32)+7 downto (i*32))); else current_round_data((i*32)+15 downto (i*32)+8) <= current_round_data((i*32)+31 downto (i*32)+24) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1))) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1)) xor current_round_data((i*32)+7 downto (i*32)) xor IRREDUCIBLE_POLY); end if; else if (current_round_data((i*32)+7) = '0') then current_round_data((i*32)+15 downto (i*32)+8) <= current_round_data((i*32)+31 downto (i*32)+24) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1)) xor IRREDUCIBLE_POLY) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1)) xor current_round_data((i*32)+7 downto (i*32))); else current_round_data((i*32)+15 downto (i*32)+8) <= current_round_data((i*32)+31 downto (i*32)+24) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+15 downto (i*32)+8)),1)) xor IRREDUCIBLE_POLY) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1)) xor current_round_data((i*32)+7 downto (i*32)) xor IRREDUCIBLE_POLY); end if; end if; -- constant MIX_C_MATRIX_R4 : RowArray := (x"03",x"01",x"01",x"02"); if(current_round_data((i*32)+7)='0') then if (current_round_data((i*32)+31) = '0') then current_round_data((i*32)+7 downto (i*32)) <= (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor current_round_data((i*32)+31 downto (i*32)+24)) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1))); else current_round_data((i*32)+7 downto (i*32)) <= (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor current_round_data((i*32)+31 downto (i*32)+24) xor IRREDUCIBLE_POLY) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1))); end if; else if (current_round_data((i*32)+31) = '0') then current_round_data((i*32)+7 downto (i*32)) <= (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor current_round_data((i*32)+31 downto (i*32)+24)) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1)) xor IRREDUCIBLE_POLY); else current_round_data((i*32)+7 downto (i*32)) <= (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+31 downto (i*32)+24)),1)) xor current_round_data((i*32)+31 downto (i*32)+24) xor IRREDUCIBLE_POLY) xor current_round_data((i*32)+15 downto (i*32)+8) xor current_round_data((i*32)+23 downto (i*32)+16) xor (std_logic_vector(shift_left(unsigned(current_round_data((i*32)+7 downto (i*32))),1)) xor IRREDUCIBLE_POLY); end if; end if; end loop; -- i FSM_STATE <= STATE_ADD_ROUNDKEY; WHEN STATE_ADD_ROUNDKEY => CIPHER <= current_round_data; ENCRYPTION_STATUS <= '0'; current_round_data <= current_round_data xor KEYS_EXP((128*round)-1 downto (128*(round-1))); if(round = ROUNDS_COUNT) then FSM_STATE <= STATE_COMPLETE; else FSM_STATE <= STATE_SBOX; end if; WHEN STATE_COMPLETE => CIPHER <= current_round_data; ENCRYPTION_STATUS <= '1'; FSM_STATE <= STATE_COMPLETE; if(ENCRYPT_ENABLE='0') then FSM_STATE <= STATE_INIT; end if; WHEN OTHERS => CIPHER <= current_round_data; ENCRYPTION_STATUS <= '0'; FSM_STATE <= STATE_INIT; END CASE; END IF; END IF; END PROCESS; end RTL;
import { RecipeSchema } from "./RecipeSchema.js"; export class ReplacementParser { protected data: any; private window?: Window; protected host: string; constructor(host: string) { this.host = host.toLowerCase(); } parse(window: Window, orig: RecipeSchema) { this.window = window; this.data = Object.assign({}, orig); } getOrig() { return this.data; } before_parse() {} get() { this.before_parse(); return <RecipeSchema>{ host: this.host, author: this.author(), title: this.title(), category: this.category(), total_time: this.total_time(), yields: this.yields(), image: this.image(), ingredients: this.ingredients(), instructions: this.instructions(), ratings: this.ratings(), cuisine: this.cuisine(), description: this.description(), }; } getWindow() { return this.window; } querySelector(query: string, text?: string) { if (this.window) { if (text) { const results = Array.from( this.window.document.querySelectorAll(query) ); const result = results.filter( (result) => result.textContent && result.textContent.indexOf(text) !== -1 )[0]; return result || null; } else { return this.window.document.querySelector(query); } } return null; } querySelectorAll(query: string, text?: string): Element[] { if (this.window) { const results = Array.from( this.window?.document.querySelectorAll(query) ); if (text) { return results.filter( (ele) => ele.textContent && ele.textContent.indexOf(text) !== -1 ); } else { return results; } } return []; } hasHost(host: string) { return host.toLowerCase().indexOf(this.host) !== -1; } raw(): any { return this.data._raw; } author(): string { return this.data.author; } title(): string { return this.data.title; } category(): string { return this.data.category; } prep_time(): string { return this.data.prepTime; } cook_time(): string { return this.data.cookTime; } calc_total_time(): string { // TODO Parse time from string and reconstruct properly, lib for this? this.data.total_time = this.prep_time() + " + " + this.cook_time(); return this.data.total_time; } total_time(): string { return this.data.total_time; } yields(): string { return this.data.yields; } image(): string { return this.data.image; } ingredients(): string | string[] { return this.data.ingredients; } instructions(): string | string[] { return this.data.instructions; } ratings(): string { return this.data.ratings; } cuisine(): string { return this.data.cuisine; } description(): string { return this.data.description; } }
#ifndef clox_chunk_h #define clox_chunk_h #include "common.h" #include "value.h" #include <stddef.h> #include <stdint.h> /* * We define all operation for our bytecode format */ typedef enum { OP_RETURN, // Means return from current function, /* * Aimed at producing a constants * It has an operand. An the operand is the index of the constant to produce * It is a 2byte instruction of the format * <opcode> <constant_index> e.g 0009 23, produces the constant stored at index 23 from the list of constants in the array */ OP_CONSTANT, OP_NEGATE, // Unary negation OP_PRINT, OP_JUMP_IF_FALSE, OP_LOOP, OP_ADD, // To emit a result or value from the stack OP_POP, OP_GET_LOCAL, OP_SET_LOCAL, OP_NIL, OP_TRUE, OP_FALSE, OP_EQUAL, OP_GREATER, OP_LESS, OP_JUMP, OP_SUBTRACT, OP_DIVIDE, OP_NOT, OP_MULTIPLY, OP_DEFINE_GLOBAL, OP_GET_GLOBAL, OP_SET_GLOBAL, } OpCode; #define STACK_MAX 256 /* * Bytecode is a series of instructions or bytes and a group of them is stored * in a chunk This is just a Dynamic arraylist structure to store all * instructions or bytes. * * @count is the actual number of elements allocated * @capacity is the number of elements which can be allocated * @code is a list of bytes or instructions * @consants Are the values produced at runtime like numbers, strings etc, they * are stored in a dynamic array */ typedef struct { int count; int capacity; uint8_t *code; ValueArray consants; int *lines; } Chunk; void initChunk(Chunk *chunk); /* * Adds a byte to the chunk */ void writeChunk(Chunk *chunk, uint8_t byte, int line); /* * Appends the constant to the list of constants */ int addConstant(Chunk *chunk, Value value); /* * Deletes all bytes from the chunk */ void freeChunk(Chunk *chunk); #endif // !clox_chunk_h
namespace Spoon.Demo.Application.V1.Administrator.CustomerTypes.Get.V1.Command; using Domain.Entities; using Domain.Repositories; /// <summary> /// Class ProductCreateQueryHandler. This class cannot be inherited. /// </summary> public sealed class CustomerTypeGetCommandV1Handler : IRequestHandler<CustomerTypeGetCommandV1, Either<CustomerTypeGetCommandV1Result>> { private readonly ICustomerTypeRepository _repository; /// <summary> /// </summary> /// <param name="repository"></param> public CustomerTypeGetCommandV1Handler(IApplicationRepository repository) { this._repository = repository.CustomerTypes; } /// <summary> /// Handles the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="cancellationToken"> /// The cancellation token that can be used by other objects or threads to receive notice /// of cancellation. /// </param> /// <returns>Task&lt;Either&lt;ProductCreateQueryResult&gt;&gt;.</returns> public async Task<Either<CustomerTypeGetCommandV1Result>> Handle( CustomerTypeGetCommandV1 request, CancellationToken cancellationToken) { var getSpecification = new DefaultGetSpecification<CustomerType>(request.CustomerTypeId); var existing = await this._repository.GetAsync(getSpecification, cancellationToken); if (existing == null) return EitherHelper<CustomerTypeGetCommandV1Result>.EntityNotFound(typeof(CustomerTypeGetCommandV1)); await this._repository.SaveChangesAsync(cancellationToken); var result = new CustomerTypeGetCommandV1Result { CategoryId = existing.CustomerTypeId, Name = existing.Name, Description = existing.Description, CreatedAt = existing.CreatedAt, ModifiedAt = existing.ModifiedAt, DeletedAt = existing.DeletedAt, }; return new Either<CustomerTypeGetCommandV1Result>(result); } }
import 'package:desgram_ui/ui/app_widgets/image_user_avatar.dart'; import 'package:desgram_ui/ui/roots/main_page/main_page_navigator.dart'; import 'package:desgram_ui/ui/roots/main_page/subpages/search_suggestions/search_suggestions_view_model.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class SearchSuggestionsWidget extends StatelessWidget { const SearchSuggestionsWidget({super.key}); @override Widget build(BuildContext context) { var viewModel = context.watch<SearchSuggestionsViewModel>(); return Scaffold( appBar: AppBar( bottom: const PreferredSize( preferredSize: Size.fromHeight(0.6), child: Divider(color: Colors.grey, height: 0.6, thickness: 0.6), ), elevation: 0, backgroundColor: Colors.white, foregroundColor: Colors.black, flexibleSpace: Padding( padding: const EdgeInsets.only(top: 7, bottom: 7, left: 50, right: 20), child: TextField( controller: viewModel.searchController, textInputAction: TextInputAction.search, onChanged: viewModel.onChangedSearchString, onSubmitted: viewModel.toSearchResult, autofocus: true, decoration: const InputDecoration( prefixIcon: Icon(Icons.search), fillColor: Color.fromARGB(255, 235, 230, 230), filled: true, contentPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 6), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(10)), ), hintText: "Поиск", hintStyle: TextStyle( fontSize: 19, color: Color.fromARGB(255, 120, 119, 119))), ), ), ), body: CustomScrollView( slivers: [ SliverList( delegate: SliverChildBuilderDelegate((context, index) { var user = viewModel.state.suggestionsUsers[index]; return Column( mainAxisSize: MainAxisSize.min, children: [ TextButton.icon( style: TextButton.styleFrom( foregroundColor: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 25), alignment: Alignment.centerLeft, minimumSize: const Size.fromHeight(55), textStyle: const TextStyle(fontSize: 20), ), onPressed: () => viewModel.mainPageNavigator .toAnotherAccountContent(userId: user.id), icon: ImageUserAvatar.fromImageModel( imageModel: user.avatar, size: 40, ), label: Text( user.name, )), ], ); }, childCount: viewModel.state.suggestionsUsers.length)), SliverList( delegate: SliverChildBuilderDelegate((context, index) { var hashtag = viewModel.state.suggestionsHashtags[index]; return Column( mainAxisSize: MainAxisSize.min, children: [ TextButton.icon( style: TextButton.styleFrom( foregroundColor: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 25), alignment: Alignment.centerLeft, minimumSize: const Size.fromHeight(55), textStyle: const TextStyle(fontSize: 20), ), onPressed: () { viewModel.mainPageNavigator .toFeedHashtag(hashtag: hashtag.hashtag); }, icon: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(width: 1, color: Colors.black)), alignment: Alignment.center, child: const Text( "#", style: TextStyle(fontSize: 30), ), ), label: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( hashtag.hashtag, ), Text( "Кол. постов: ${hashtag.amountPosts}", style: const TextStyle( fontSize: 18, color: Colors.grey), ) ], )), ], ); }, childCount: viewModel.state.suggestionsHashtags.length)), SliverList( delegate: SliverChildBuilderDelegate( (context, index) => TextButton.icon( style: TextButton.styleFrom( foregroundColor: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 25), alignment: Alignment.centerLeft, minimumSize: const Size.fromHeight(55), textStyle: const TextStyle(fontSize: 22), ), onPressed: () => viewModel.toSearchResult( viewModel.state.suggestionsSearchString[index]), icon: const Icon( Icons.search, size: 35, ), label: Text( viewModel.state.suggestionsSearchString[index], )), childCount: viewModel.state.suggestionsSearchString.length)), if (viewModel.state.searchString.isNotEmpty) SliverToBoxAdapter( child: TextButton.icon( style: TextButton.styleFrom( foregroundColor: Colors.black, padding: const EdgeInsets.symmetric(horizontal: 25), alignment: Alignment.centerLeft, minimumSize: const Size.fromHeight(55), textStyle: const TextStyle(fontSize: 22), ), onPressed: () => viewModel.toSearchResult(viewModel.state.searchString), icon: const Icon( Icons.search, size: 35, ), label: Text( viewModel.state.searchString, )), ) ], )); } static Widget create(MainPageNavigator mainPageNavigator) { return ChangeNotifierProvider( create: (context) => SearchSuggestionsViewModel( context: context, mainPageNavigator: mainPageNavigator), child: const SearchSuggestionsWidget(), ); } }
// SPDX-License-Identifier: Apache-2.0 // Copyright 2023 The Falco 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 fields import ( "k8s.io/apimachinery/pkg/types" ) // Reference used to reference objects to which a resource is related. type Reference struct { Name types.NamespacedName UID types.UID } // References custom type for a resource's references. // Key is the kind of the resource and the values is a slice containing all the references for objects // of the same kind as the key. type References map[string][]Reference // ToFlatMap return the references in a map where the key is the kind of the object for which the references // are saved. The value is slice containing all the types.UID for objects of the same kind as the key. func (r *References) ToFlatMap() map[string][]string { flatMap := make(map[string][]string) for key, val := range *r { refs := make([]string, len(val)) for i := range val { refs[i] = string(val[i].UID) } flatMap[key] = refs } return flatMap } // Subscribers custom type for subscribers to which a given event need to be sent. // The key is the subscriber's UID. type Subscribers map[string]struct{} // Add adds a subscriber. func (s Subscribers) Add(sub string) { s[sub] = struct{}{} } // Delete deletes a subscriber. func (s Subscribers) Delete(sub string) { delete(s, sub) } // Has returns true if a subcriber is present. func (s Subscribers) Has(sub string) bool { _, ok := s[sub] return ok } // Intersect returns the intersection with the given set. func (s Subscribers) Intersect(subs Subscribers) Subscribers { intersection := make(Subscribers) s1, s2 := s, subs if len(s1) > len(s2) { s1, s2 = s2, s1 } for sub := range s1 { if _, ok := s2[sub]; ok { intersection[sub] = struct{}{} } } return intersection } // Difference returns the difference ( all the members of the initial set that are not members of the given set). func (s Subscribers) Difference(subs Subscribers) Subscribers { setDifference := make(Subscribers) for sub := range s { if _, ok := subs[sub]; !ok { setDifference[sub] = struct{}{} } } return setDifference }
package leetcode.slidewindow; import java.util.HashMap; import java.util.Map; //给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 "" 。 // // // // 注意: // // // 对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。 // 如果 s 中存在这样的子串,我们保证它是唯一的答案。 // // // // // 示例 1: // // //输入:s = "ADOBECODEBANC", t = "ABC" //输出:"BANC" // // // 示例 2: // // //输入:s = "a", t = "a" //输出:"a" // // // 示例 3: // // //输入: s = "a", t = "aa" //输出: "" //解释: t 中两个字符 'a' 均应包含在 s 的子串中, //因此没有符合条件的子字符串,返回空字符串。 // // // // 提示: // // // 1 <= s.length, t.length <= 10⁵ // s 和 t 由英文字母组成 // // // //进阶:你能设计一个在 o(n) 时间内解决此问题的算法吗? Related Topics 哈希表 字符串 滑动窗口 👍 1953 👎 0 /** * 字节 */ public class _76_最小覆盖子串{ class Solution{ /** * init window * @param s * @param t * @return */ public String minWindow(String s, String t) { // window 是活动窗口,need 是目标串对应字母字典 char[] schars = s.toCharArray(); char[] tchars = t.toCharArray(); Map<Character, Integer> window = new HashMap<>(schars.length); Map<Character, Integer> need = new HashMap<>(tchars.length); for (char c : tchars) { need.put(c, need.getOrDefault(c, 0) + 1); } int left = 0, right = 0, start = 0, len = Integer.MAX_VALUE, valid = 0; while (right < schars.length) { //c是将要加入窗口的字符 char c = schars[right]; right++; //下面处理滑动窗口内数据的一系列更新 if (need.keySet().contains(c)) { window.put(c, window.getOrDefault(c, 0) + 1); if (window.get(c).equals(need.get(c))) { valid++; } } //判断左侧是否需要收缩 while (valid == need.size()) { // 在这里更新最小子串 if (right - left < len) { start = left; len = right - left; } //需要收缩的字符 char d = schars[left]; left++; //进行窗口内数据的一些列更新 if (need.keySet().contains(d)) { if (window.get(d).equals(need.get(d))) { valid--; } window.put(d, window.getOrDefault(d, 0) - 1); } } } return len == Integer.MAX_VALUE ? "" :s.substring(start, start + len); } } class Solution2{ public String minWindow(String s, String t) { int ns = s.length(), nt = t.length(); if (ns < nt) { return ""; } int[] hash = new int[58]; // A~Z: 65~90, a~z: 97~122 int diff = 0; for (int i = 0; i < nt; i++) { hash[t.charAt(i) - 'A']++; hash[s.charAt(i) - 'A']--; } for (int val : hash) { // 只关心未抵消的字符 if (val > 0) { diff++; } } if (diff == 0) { return s.substring(0, nt); // 第一个窗为最小覆盖子串时 } int l = 0, r = nt, lmin = 0, rmin = ns; for (; r < ns; r++) { // 只要当前窗还未覆盖,向右侧扩窗 int in = s.charAt(r) - 'A'; hash[in]--; if (hash[in] == 0) { diff--; // in入窗后使得窗内该字符个数与t中相同 } if (diff != 0) { continue; // diff不为0则继续扩窗 } for (; diff == 0; l++) { // 从左侧缩窗 int out = s.charAt(l) - 'A'; hash[out]++; if (hash[out] == 1) { diff++; } } if (r - l + 1 < rmin - lmin) { // 缩窗后得到一个合格窗,若窗宽更小,更新窗界 lmin = l - 1; rmin = r; } } return rmin == ns ? "" :s.substring(lmin, rmin + 1); // 根据窗界是否有过更新来返回相应的结果 } } }
## Code and requirements ```bash git clone https://github.com/D-Roberts/smarter.git cd smarter conda create --name smarter python=3.10 conda activate smarter pip install -r requirements.txt ``` To install conda if necessary, can do [miniconda](https://docs.anaconda.com/free/miniconda/). ## Small Runs To be able to run a small experiment without the need to download the full dataset, a math puzzle is committed to the repo. See the *SMART101 Data* section of the README to see how to download the full dataset to run full final models train and eval. To run training and eval of smaller models on the small subset of the dataset which is committed to this repo for initial insights into the deep learning training of vision-language reasoners, from the repo root: ```bash unzip small-data.zip python main_reasoner.py \ --model_name fused_dinov2_siglip \ --log \ --word_embed siglip \ --save_root small-runs \ --data_root small-data/SMART101-Data \ --lr 0.0001 \ --wd 0.2 \ --batch_size 4 \ --num_heads 2 \ --repr_size 128 \ --qf_layer \ --eps 1e-8 \ --beta2 0.98 \ --pdrop 0.2 \ --ln_eps 1e-6 \ --h_sz 64 \ --seed 0 \ --num_workers 1 \ --data_tot 128 \ --train_diff easy \ --num_epochs 2 \ --puzzles 58 rm -rf small-data rm -rf small-runs ``` The small dataset has one puzzle, 58, illustrated in the article, from the math skill with multiple choice answer. Note that the skill-based accuracies will not be calculated since at least 3 puzzles are necessary. Args are described in *main_reasoner.py*. ## Machine learning experiment tracking with CometML Experiments are tracked in CometML. A public account is made available for trying out the code, and experiment panels (loss and accuracy curves) can be seen here [https://www.comet.com/ai-daor/smarter/view/new/panels](https://www.comet.com/ai-daor/smarter/view/new/panels). To be able to create personal experiments, a Comet API Key must be created and placed in the smarter/.comet_token file and a Comet account username must be written to smarter/.comet_workspace (from your [CometML](https://www.comet.com) account), replacing the public one. ## SMART101 Data To download the full SMART101 dataset (from [merl](https://github.com/merlresearch/SMART)), please execute the `get_SMART_data.sh` script in the repository. Depending on the internet connection, it can take 1-5hrs to download. ## Final Models To run training and eval of final models, from the repo root (need at least 40GB mem, at least 16 cores, and a V100 GPU (or A100 or H100)): ```bash python main_reasoner.py \ --model_name fused_dinov2_siglip \ --log \ --word_embed siglip \ --save_root final-runs \ --data_root data/smart-data/SMART101-release-v1/SMART101-Data \ --lr 0.0003 \ --wd 0.2 \ --batch_size 128 \ --num_heads 2 \ --repr_size 128 \ --qf_layer \ --eps 1e-8 \ --beta2 0.98 \ --pdrop 0.2 \ --ln_eps 1e-6 \ --h_sz 256 \ --seed 0 \ --num_workers 16 \ --data_tot 1000 \ --train_diff easy \ --num_epochs 3 \ --puzzles all ``` Tested on Ubuntu20.04 LTS, Mac (x86_64 and M1) CPU-only, V100, A100, H100.
import java.util.*; public class ShipBots { ShipGenerator shipGenerator; //shipGenerator object is an instance of our ShipGenerator class private int[][] moves = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; //this defines up, right, left, down movements private int[][] ship; //our generated ship we will run the simulations on private int[] botPosition, buttonPosition, firePosition; //initial positions of the bot, button, fire private int rows, cols; //stores the dimensions of our generated ship private final int maxIterations = 20000; //maxIterations is a constant used to prevent some methods for looping continously and running out of heap space and memory private double q; //'q' parameter between 0 and 1 that we will pass in private Queue<int[]> firePositionQueue; //Queue to store all the coordinates of the positions of the fire that it will spread to //ShipBots constructor that takes in an instance of the ShipGenerator class and a q value public ShipBots(ShipGenerator shipGenerator, double q) { //retrieves all necessary info, including an instance of the ShipGenerator class, the ship, dimensions, and initial positions this.shipGenerator = shipGenerator; this.ship = shipGenerator.getShip(); this.rows = shipGenerator.getRows(); this.cols = shipGenerator.getCols(); this.botPosition = shipGenerator.getKeyPosition(ship, 2); this.buttonPosition = shipGenerator.getKeyPosition(ship, 3); this.firePosition = shipGenerator.getKeyPosition(ship, 4); this.q = q; this.firePositionQueue = new LinkedList<>(); firePositionQueue.add(firePosition); //add the initial fire position to the queue } private static class Path { //private class 'Path' within ShipBots class to help represent our path for Uniform Cost Search (used in Bot 2 and Bot 3) private List<int[]> path; //list of array coordinates to represent our path private int cost; //represents the cost associated with each path movement private int[] position; //represents the current position in the path public Path(List<int[]> path, int cost, int[] position) { //the three attributes are passed in the 'Path' constructor this.path = path; this.cost = cost; this.position = position; } public List<int[]> getPath() { //getter method to retrieve the path list return path; } public int getCost() { //getter method to retrieve the cost return cost; } public int[] getPosition() { //getter method to retrieve the current position return position; } } private static class PathComparator implements Comparator<Path> { //the Comparator interface is implemeted so we can objects (paths) by their costs in the priority queue @Override public int compare(Path path1, Path path2) { //method compares two 'Path' objects based on their individual 'cost' values return Integer.compare(path1.getCost(), path2.getCost()); //this means that 'Path' objects added to a priority queue are ordered on ascending order (lower the cost = more in front in the priority queue) } } private List<int[]> getAllNeighbors(int[] position) { //returns a list of neighboring cell positions/coordinates around the passed in position List<int[]> neighbors = new ArrayList<>(); //'neighbors' will store all neighboring positions for (int[] move : moves) { //loop through the neighbors (up/right/left/down) int currRow = position[0] + move[0]; //obtain row coordinate of curr neighbor int curCol = position[1] + move[1]; //obtain col coordinate of curr neighbor if (shipGenerator.inShip(currRow, curCol)) { //if this neighbor is in the ship, add it to our 'neighbors' list neighbors.add(new int[]{currRow, curCol}); } } return neighbors; //return the neighbors list } private boolean isAdjacentToFire(int[] cell, Queue<int[]> firePositionQueue) { //this method helps determine whether the passed in 'cell' position is adjacent to a fire cell for (int[] fireCell : firePositionQueue) { //firePositionQueue holds all fire positions, loop through each position //if both the row coordinate and column coordinate of 'cell' is within 1 absolute unit in any direction (u/r/l/d) of a fireCell (a position we know is on fire), then it is adjacent to a fire cell if (Math.abs(cell[0] - fireCell[0]) <= 1 && Math.abs(cell[1] - fireCell[1]) <= 1) { return true; //returns true if the position is adjacent to a fire cell } } return false; //return false if no positions are found to be adjacent to a fire cell } private int getK(int row, int col) { //method returns the number of cells neighboring the (row,col) position that are on fire int count = 0; for (int[] move : moves) { //loop through all moves (up, left, right, down) int currRow = row + move[0]; //obtain current row coordinate of neighbor int curCol = col + move[1]; //obtain current column coordinate of neighbor //checks if the coordinates are 1. In the ship 2. Equal to 4 (a fire cell) 3. Not equal to 1 (A blocked cell) if (shipGenerator.inShip(currRow, curCol) && ship[currRow][curCol] == 4 && ship[currRow][curCol] != 1) { count++; //add to count if conditions are met } } return count; //return count (num of neighboring cells on fire) } private boolean containsFireOrBlockedCells(List<int[]> path) { //method checks whether any positions in the 'path' list are fire cells are blocked cells for (int[] step : path) { //loop through each 'step' in the path if (ship[step[0]][step[1]] == 1 || ship[step[0]][step[1]] == 4) { //checks if path contains fire/blocked cells return true; //return true if it does } } return false; // return false if the path is 'clean' (containing no fire/blocked cells) } private List<int[]> planPathToButton(int[] start, int[] goal, boolean[][] visited) {//method plans a path from the start to goal position that avoids current fire cells //priority queue to prioritize paths with the lowest cost PriorityQueue<Path> allPathsQueues = new PriorityQueue<>(new PathComparator()); //initialize starting position with a cost of 0 and add it to the 'allPathsQueues' Path initialPath = new Path(new ArrayList<>(), 0, start); allPathsQueues.add(initialPath); //while loop continues until either allPathsQueues is empty or iterations exceed our constant 'maxIterations' //as mentioned before, maxIterations is set as 20,000 to prevent heap/memory issues int iterations = 0; while (!allPathsQueues.isEmpty() && iterations < maxIterations) { Path currentPath = allPathsQueues.poll(); //retrieve the 'Path' with the lowest cost int[] currentCell = currentPath.getPosition(); //set our currentCell equal to the current position in the 'currentPath' if (Arrays.equals(currentCell, goal)) { //if our currentCell is equal to the goal, this means a path to the goal has been found return currentPath.getPath(); // return the path that leads to the goal } //if its not the goal, we explore the neighbors of 'currentCell' List<int[]> neighbors = getAllNeighbors(currentCell); //this retrieves the neighbors of 'currentCell' and stores it in the 'neighbors' list for (int[] neighbor : neighbors) { //loop through all the neighbors in the 'neighbors' list if (!visited[neighbor[0]][neighbor[1]] && ship[neighbor[0]][neighbor[1]] != 1) { //check if the neighbor is unvisited and not a blocked/wall cell List<int[]> newPath = new ArrayList<>(currentPath.getPath()); //create a new path starting from the 'currentPath' position and onwards newPath.add(neighbor); // Add the neighbor of 'currentPath' to the new path 'newPath' int newCost = currentPath.getCost() + 1; //update the cost by 1 additional value //Add the new path 'newPath' with the updated cost to the priority queue allPathsQueues.add(new Path(newPath, newCost, neighbor)); } } iterations++; } return null; //return null if there was no valid path that could be found from the bot to the button (start to goal) } private List<int[]> planPathToButtonWithFireAvoidance(int[] start, int[] goal, boolean[][] visited, Queue<int[]> firePositionQueue) { //method returns a path from bot to button (start to goal) that avoids cells adjacent to fire cells /* THIS METHOD IS JUST LIKE THE 'planPathToButton' METHOD, HOWEVER THIS ALSO AVOIDS CELLS THAT ARE ADJACENT TO FIRE CELLS */ PriorityQueue<Path> allPathsQueues = new PriorityQueue<>(new PathComparator()); Path initialPath = new Path(new ArrayList<>(), 0, start); allPathsQueues.add(initialPath); int iterations = 0; while (!allPathsQueues.isEmpty() && iterations < maxIterations) { Path currentPath = allPathsQueues.poll(); int[] currentCell = currentPath.getPosition(); if (Arrays.equals(currentCell, goal)) { return currentPath.getPath(); } List<int[]> neighbors = getAllNeighbors(currentCell); for (int[] neighbor : neighbors) { if (!visited[neighbor[0]][neighbor[1]] && ship[neighbor[0]][neighbor[1]] != 1) { List<int[]> newPath = new ArrayList<>(currentPath.getPath()); newPath.add(neighbor); int newCost = currentPath.getCost() + 1; if (!isAdjacentToFire(neighbor, firePositionQueue)) { allPathsQueues.add(new Path(newPath, newCost, neighbor)); } } } iterations++; } return null; } private int heuristic(int[] start, int[] goal) { //this will be the heuristic value used for the A star algorithm, which is the distance, or "Manhattan" distance from the start position to goal position return Math.abs(start[0] - goal[0]) + Math.abs(start[1] - goal[1]); } private List<int[]> pathPlanAStar(int[] start, int[] goal, boolean[][] visited, Queue<int[]> fireQueue) { /* THIS METHOD IS JUST LIKE THE 'planPathToButton' and 'planPathToButtonWithFireAvoidance' METHOD, HOWEVER THE ONLY DIFFERENCE IS THE COST IS CALCULATED USING THE HEURISTIC DISTANCE VALUE INSTEAD OF JUST INCREMENTING IT BY +1*/ PriorityQueue<Path> allPathsQueues = new PriorityQueue<>(new PathComparator()); Path initialPath = new Path(new ArrayList<>(), 0, start); allPathsQueues.add(initialPath); int iterations = 0; while (!allPathsQueues.isEmpty() && iterations < maxIterations) { Path currentPath = allPathsQueues.poll(); int[] currentCell = currentPath.getPosition(); if (Arrays.equals(currentCell, goal)) { return currentPath.getPath(); //if the current path leads to the goal, just return it } List<int[]> neighbors = getAllNeighbors(currentCell); for (int[] neighbor : neighbors) { if (!visited[neighbor[0]][neighbor[1]] && ship[neighbor[0]][neighbor[1]] != 1) { List<int[]> newPath = new ArrayList<>(currentPath.getPath()); newPath.add(neighbor); int newCost = currentPath.getCost() + 1; //calculate the heuristic (the current distance left to get to the goal) int heuristicCost = heuristic(neighbor, goal); //calculate the total 'cost' as the sum of the new cost plus the distance that the 'heuristic' function returns int cost = newCost + heuristicCost; if (!isAdjacentToFire(neighbor, fireQueue)) { //add the new path with the right 'cost' value to the priority queue allPathsQueues.add(new Path(newPath, cost, neighbor)); } } } iterations++; } return null; // Return null if there was no valid path to the button } private void spreadFire(Queue<int[]> firePositionQueue) { //this method simulates the spreading of the fire, takes in the firePositionQueue (which currently stores the initial fire position) //only included this so that I could make sure that the K value for the first iteration was set to 1 boolean isFirstIteration = true; Queue<int[]> newfirePositionQueue = new LinkedList<>(); //create a new firePositionQueue to store the cells that are to be ignited in this current iteration //iterate through each cell in the firePositionQueue (each cell here should be on fire already) for (int i = 0; i < firePositionQueue.size(); i++) { int[] currentFire = firePositionQueue.poll(); //retrieve the the current fire cells position //iterate through the neighboring cells of the current fire cell for (int[] move : moves) { int currRow = currentFire[0] + move[0]; //retrieve the row coordinate int curCol = currentFire[1] + move[1]; //retrieve the neighbor column coordinate if (shipGenerator.inShip(currRow, curCol)) { //check if this coordinate is within our ship bounds //check if the neighboring cell is not already on fire/blocked if (ship[currRow][curCol] != 4 && ship[currRow][curCol] != 1 ) { //Calculate 'K' value based on the number of neighboring cells that are on fire //this just makes sure that if we are in first iteration K = 1, otherwise we can call the 'getK' helper method to retrieve K int K = isFirstIteration ? 1 : getK(currRow, curCol); //calculate the probability of this neighbor cell catching fire double rand = Math.random();//generate a random number between 0 and 1 //if the formula (1-(1-q)^K returns a number greater than the randomly generated number, we can say the cell is now on fire if (rand < (1 - Math.pow((1 - q), K))) { //set the cell value equal to 4 to represent it being on fire and add it to the 'newfirePositionQueue' ship[currRow][curCol] = 4; newfirePositionQueue.add(new int[]{currRow, curCol}); } } } } isFirstIteration = false; //now the 'K' value will be retrieved from the 'getK' method } //add newly ignited cells that were added to 'newfirePositionQueue' to the 'firePositionQueue' for the next iteration firePositionQueue.addAll(newfirePositionQueue); } public void botOneSimulation() { //method simulates BFS exploring of Bot One to find the shortest path to the button, the bot ignores the spread of the fire //create a 'botPositionQueue' and 'firePositionQueue' to store the bot and fire positions Queue<int[]> botPositionQueue = new LinkedList<>(); Queue<int[]> firePositionQueue = new LinkedList<>(); //create 2D boolean array to track the visited positions of the bot (true = visited, and false = non-visited) boolean[][] visited = new boolean[rows][cols]; botPositionQueue.add(botPosition); //add bot's initial position to 'botPositionQueue' visited[botPosition[0]][botPosition[1]] = true; //set the initial position firePositionQueue.add(firePosition); //add fire's initial position to the firePositionQueue //continue iterating until there are no more positions for the bot to explore or if iterations exceed our constant maxIterations int iterations = 0; while (!botPositionQueue.isEmpty() && iterations < maxIterations) { int[] currentBot = botPositionQueue.poll(); //retrieve the earliest cell explored by the bot in the queue //check if the current bot position equals the current button position and is not a fire cell, if so, simulation is successful if (Arrays.equals(currentBot, buttonPosition) && ship[currentBot[0]][currentBot[1]] != 4) { System.out.println("Success! The bot has reached the button and put out the fire in the ship!."); return; } List<int[]> botNeighbors = getAllNeighbors(currentBot); //retrieve all neighbor positions of the current bot position for (int[] botNeighbor : botNeighbors) { //loop through each of the neighbors of the current bot position if (!visited[botNeighbor[0]][botNeighbor[1]] && ship[botNeighbor[0]][botNeighbor[1]] == 1) { //if the neighbor is a wall or if it is already visited, we can continue onwards continue; } botPositionQueue.add(botNeighbor); //add the neighbor position to the queue if it is not a wall or already visited visited[botNeighbor[0]][botNeighbor[1]] = true; //set that position to true to represent it being a visited cell in 'visited' } //call the spreadFire() method, passing in the firePositionQueue that stores the current fire positions, to simulate the spreading of the fire spreadFire(firePositionQueue); //check if the current bot's position is on fire, if so, simulate is a failure if (ship[currentBot[0]][currentBot[1]] == 4) { System.out.println("Failure! The bot has caught on fire!"); return; } iterations++; } } public void botTwoSimulation() { //method simulates the bot re-planning (Using uniform cost search) the shortest path from itself to the button at each iteration whilst avoiding current fire cells //create a 'botPositionQueue' and 'firePositionQueue' to store the bot and fire positions Queue<int[]> botPositionQueue = new LinkedList<>(); Queue<int[]> firePositionQueue = new LinkedList<>(); //create a 2D boolean array 'visited' to store true for visited and false for unvisited boolean[][] visited = new boolean[rows][cols]; botPositionQueue.add(botPosition); //add the initial bot position to the 'botPositionQueue' visited[botPosition[0]][botPosition[1]] = true; //mark this position as visited firePositionQueue.add(firePosition); //add the initial fire position to the 'firePositionQueue' int iterations = 0; List<int[]> currentPath = null; //create and set our 'currentPath' list to null/empty, which will store the current generated path the bot is exploring //continue the while loop until the 'botPositionQueue' is empty meaning no more paths/positions to explore or if the maxIterations constant is exceeded while (!botPositionQueue.isEmpty() && iterations < maxIterations) { //set currentPath equal to a new re-planned path that is generated from the 'planPathToButton' method which takes in the botPosition and buttonPosotion as the start/gpal values respectively //this re-planned path should avoid blocked/fire cells currentPath = planPathToButton(botPosition, buttonPosition, visited); //checks if there exists a valid/clean path from the current position to the button, if so, the simulation is succesful since we know the bot can take this path with no issues if (currentPath != null && !containsFireOrBlockedCells(currentPath)) { System.out.println("Success! The bot has reached the button and put out the fire in the ship!"); return; } //iterate through the current re-planned path as long as its not empty if (currentPath != null) { for (int[] step : currentPath) { //loop through each step/position in this pth if (visited[step[0]][step[1]]) { //if the cell is visited already, just continue continue; } visited[step[0]][step[1]] = true; //set the position to visited and add that step to the 'botPositionQueue' botPositionQueue.add(step); } } //call the spreadFire() method to simualte the spreading at each iteration spreadFire(firePositionQueue); //check if the bot's current position is on fire (equal to 4), if so, simulation is a failure if (ship[botPosition[0]][botPosition[1]] == 4) { System.out.println("Failure! The bot has caught on fire!"); return; } botPosition = botPositionQueue.poll(); //update the bot's position to be the least-recent added element in the queue iterations++; } } public void botThreeSimulation() { //method simulates the bot re-planning (Using uniform cost search) the shortest path from itself to the button at each iteration whilst avoiding cells adjacent to fire cells /*SAME PROCESS AS 'botTwoSimulation', THE ONLY DIFFERENCE IS WE SET 'currentPath' VALUE USING THE 'planPathToButtonWithFireAvoidance' method instead of the 'planPathToButton' method */ Queue<int[]> botPositionQueue = new LinkedList<>(); Queue<int[]> firePositionQueue = new LinkedList<>(); boolean[][] visited = new boolean[rows][cols]; botPositionQueue.add(botPosition); visited[botPosition[0]][botPosition[1]] = true; firePositionQueue.add(firePosition); int iterations = 0; List<int[]> currentPath = null; while (!botPositionQueue.isEmpty() && iterations < maxIterations) { currentPath = planPathToButtonWithFireAvoidance(botPosition, buttonPosition, visited, firePositionQueue); if (currentPath != null && !containsFireOrBlockedCells(currentPath)) { System.out.println("Success! The bot has reached the button and put out the fire in the ship!"); return; } currentPath = planPathToButton(botPosition, buttonPosition, visited); if (currentPath != null && !containsFireOrBlockedCells(currentPath)) { System.out.println("Success! The bot has reached the button and put out the fire in the ship!"); return; } List<int[]> botNeighbors = getAllNeighbors(botPosition); for (int[] botNeighbor : botNeighbors) { if (!visited[botNeighbor[0]][botNeighbor[1]] && ship[botNeighbor[0]][botNeighbor[1]] != 1) { botPositionQueue.add(botNeighbor); visited[botNeighbor[0]][botNeighbor[1]] = true; } } spreadFire(firePositionQueue); if (ship[botPosition[0]][botPosition[1]] == 4) { System.out.println("Failure! The bot has caught on fire!"); return; } botPosition = botPositionQueue.poll(); iterations++; } } public void botFourSimulation() { //method simulates the bot re-planning the shortest path from itself to the button using A star algorithm /*SAME PROCESS AS 'botTwoSimulation' and 'botThreeSimulation', THE ONLY DIFFERENCE IS WE SET 'currentPath' VALUE USING THE 'pathPlanAStar' method instead of the 'planPathToButton' or 'planPathToButtonWIthFireAvoidance' method */ Queue<int[]> botPositionQueue = new LinkedList<>(); Queue<int[]> firePositionQueue = new LinkedList<>(); boolean[][] visited = new boolean[rows][cols]; botPositionQueue.add(botPosition); visited[botPosition[0]][botPosition[1]] = true; firePositionQueue.add(firePosition); int iterations = 0; List<int[]> currentPath = null; while (!botPositionQueue.isEmpty() && iterations < maxIterations) { currentPath = pathPlanAStar(botPosition, buttonPosition, visited, firePositionQueue); if (currentPath != null && !containsFireOrBlockedCells(currentPath)) { System.out.println("Success! The bot has reached the button and put out the fire in the ship!"); return; } if (currentPath != null) { for (int[] step : currentPath) { if (visited[step[0]][step[1]]) { continue; } visited[step[0]][step[1]] = true; botPositionQueue.add(step); } } spreadFire(firePositionQueue); if (ship[botPosition[0]][botPosition[1]] == 4) { System.out.println("Failure! The bot has caught on fire!"); return; } botPosition = botPositionQueue.poll(); iterations++; } } public static void main(String[] args) { //run 250 simulations for botOne, botTwo, botThree, and botFour //can adjust the q values myself /* DISCLAIMER: THE NUMBER OF OUTPUTS MIGHT NOT BE EQUAL TO 500 FOR SOME BOT SIMULATIONS.... * THIS IS BECAUSE IN SOME SIMULATIONS, THE WHILE LOOPS CONTINUE INDEFINITELY. TO WORK AROUND THIS, * I JUST RAN THE LOOP MULTIPLE TIMES UNTIL THE 500 "Success"/"Failure" STATEMENTS WERE DISPLAYED */ /* BOT ONE SIMULATIONS */ // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.7).botOneSimulation(); // } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.55).botOneSimulation(); // } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.85).botOneSimulation(); // } /* BOT TWO SIMULATIONS */ for(int i = 0; i < 500; i++){ new ShipBots(new ShipGenerator(100, 100),0.20).botTwoSimulation(); } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.55).botTwoSimulation(); // } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.85).botTwoSimulation(); // } /* BOT THREE SIMULATIONS */ // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.20).botThreeSimulation(); // } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.55).botThreeSimulation(); // } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.85).botThreeSimulation(); // } /* BOT FOUR SIMULATIONS */ // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.20).botFourSimulation(); // } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.55).botFourSimulation(); // } // for(int i = 0; i < 500; i++){ // new ShipBots(new ShipGenerator(100, 100),0.85).botFourSimulation(); // } } }
package dzh.com.DesignPattern.DesignPattern.structuralPatterns.decorator.decorator1; /** * Decorator(抽象装饰类):它也是抽象构件类的子类,用于给具体构件增加职责,但是具体职责在其子类中实现。 * 它维护一个指向抽象构件对象的引用,通过该引用可以调用装饰之前 构件对象的方法,并通过其子类扩展该方法,以达到装饰的目的。 */ public class Decorator implements Component { private Component component; //维持一个对抽象构件对象的引用 public Decorator(Component component) //注入一个抽象构件类型的对象 { this.component = component; } @Override public void operation() { component.operation(); //调用原有业务方法 } }
############################################################################### # OpenVAS Vulnerability Test # # obby Service Detection # # Authors: # Christian Fischer <[email protected]> # # Copyright: # Copyright (C) 2015 SCHUTZWERK GmbH # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 # (or any later version), as published by the Free Software Foundation. # # 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, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. ############################################################################### if(description) { script_oid("1.3.6.1.4.1.25623.1.0.111045"); script_version("2020-11-12T10:09:08+0000"); script_tag(name:"last_modification", value:"2020-11-12 10:09:08 +0000 (Thu, 12 Nov 2020)"); script_tag(name:"creation_date", value:"2015-11-05 09:00:00 +0100 (Thu, 05 Nov 2015)"); script_tag(name:"cvss_base", value:"0.0"); script_tag(name:"cvss_base_vector", value:"AV:N/AC:L/Au:N/C:N/I:N/A:N"); script_name("obby Service Detection"); script_copyright("Copyright (C) 2015 SCHUTZWERK GmbH"); script_category(ACT_GATHER_INFO); script_family("Service detection"); script_dependencies("find_service1.nasl"); script_require_ports("Services/obby", 6522); script_tag(name:"summary", value:"The script checks the presence of an obby service."); script_tag(name:"qod_type", value:"remote_banner"); exit(0); } include("host_details.inc"); include("port_service_func.inc"); port = service_get_port( default:6522, proto:"obby" ); soc = open_sock_tcp( port ); if( soc ) { send( socket: soc, data: "TEST\r\n\r\n" ); buf = recv( socket:soc, length:64 ); close( soc ); if( banner = egrep( string:buf, pattern:"obby_welcome" ) ) { version = "unknown"; service_register( port:port, proto:"obby" ); set_kb_item( name:"obby/" + port + "/version", value:version ); set_kb_item( name:"obby/" + port + "/installed", value:TRUE ); cpe = "cpe:/a:ubuntu_developers:obby"; register_product( cpe:cpe, location:port + "/tcp", port:port ); log_message( data:build_detection_report( app:"obby", version:version, install:port + "/tcp", cpe:cpe, concluded:banner ), port:port ); } } exit( 0 );
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.io.PrintWriter" %> <%@ page import="board.Board" %> <%@ page import="board.BoardDAO" %> <%@ page import="java.util.ArrayList" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width" , initial-scale="1"> <link rel="stylesheet" href="css/bootstrap.css"> <title>게시판 웹 사이트</title> <style type="text/css"> a,a:hover { color : #000000; text-decoration: none;} </style> </head> <body> <% int pageNum = 1; if(request.getParameter("pageNum") != null) { pageNum = Integer.parseInt(request.getParameter("pageNum")); } %> <nav class="navbar navbar-default"> <div class="navbar-header"> <a class="navbar-brand" href="Board.jsp">JSP 게시판 웹 사이트</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> </ul> </div> </nav> <div class="container"> <div class="row"> <table class="table table-striped" style="text-align: center; border:1px solid #dddddd"> <thead> <tr> <th style="backgroud-color:#eeeeee; text-align: center;"> 번호 </th> <th style="backgroud-color:#eeeeee; text-align: center;"> 제목 </th> <th style="backgroud-color:#eeeeee; text-align: center;"> 작성자 </th> <th style="backgroud-color:#eeeeee; text-align: center;"> 작성일 </th> </tr> </thead> <tbody> <% BoardDAO boardDAO = new BoardDAO(); ArrayList<Board> List = boardDAO.getlist(pageNum); for(int i = 0;i<List.size();i++){ %> <tr> <td><%= List.get(i).getBoard_id() %></td> <td><a href="view.jsp?board_id=<%= List.get(i).getBoard_id() %>"><%= List.get(i).getTitle() %></a></td> <td><%= List.get(i).getWriter() %></td> <td><%= List.get(i).getRegdate().substring(0,11) + List.get(i).getRegdate().substring(11,13) + ":" + List.get(i).getRegdate().substring(14,16)%></td> </tr> <% } %> </tbody> </table> <% //페이지 넘버 보여주는 부분 if(pageNum != 1){ %> <a href="Board.jsp?pageNum=<%=pageNum - 1%>" class="btn btn-success btn-arrow-left">이전</a> <% } if (boardDAO.nextPage(pageNum + 1)) { %> <a href="Board.jsp?pageNum=<%=pageNum + 1%>" class="btn btn-success btn-arrow-right">다음</a> <% } %> <a href="write.jsp" class="btn btn-primary pull-right">글쓰기</a> </div> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="js/bootstrap.js"></script> </body> </html>
package com.nexters.keyme.global.filter; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.nexters.keyme.global.common.dto.internal.UserInfo; import com.nexters.keyme.global.common.dto.internal.RequestLogInfo; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; import org.springframework.http.HttpMethod; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.ContentCachingRequestWrapper; import org.springframework.web.util.ContentCachingResponseWrapper; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; @Slf4j @RequiredArgsConstructor public class LoggingFilter extends OncePerRequestFilter { private final ObjectMapper objectMapper; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { ContentCachingRequestWrapper cachingRequestWrapper = new ContentCachingRequestWrapper(request); ContentCachingResponseWrapper cachingResponseWrapper = new ContentCachingResponseWrapper(response); try { filterChain.doFilter(cachingRequestWrapper, cachingResponseWrapper); printRequestLog(cachingRequestWrapper, cachingResponseWrapper); } catch (JsonProcessingException e) { log.warn("로깅 중 JSON 처리 에러발생"); } catch(UnsupportedEncodingException e) { log.warn("로깅 중 인코딩 에러발생"); } finally { cachingResponseWrapper.copyBodyToResponse(); } } private void printRequestLog(HttpServletRequest request, HttpServletResponse response) throws JsonProcessingException, UnsupportedEncodingException { long executionTime = System.currentTimeMillis() - Long.parseLong(MDC.get("requestStartTime")); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Long memberId = null; if (principal instanceof UserInfo) { memberId = ((UserInfo)principal).getMemberId(); } RequestLogInfo requestLogInfo = RequestLogInfo.builder() .requestMemberId(memberId) .uri(request.getRequestURI()) .method(request.getMethod()) .param(getParamString(request)) .body(getBodyString(request)) .executionTime(executionTime) .build(); String logString = objectMapper.writeValueAsString(requestLogInfo); if (executionTime > 1000) { log.warn("Request too slow! - {}", logString); } else { log.info("Request - {}", logString); } } private String getParamString(HttpServletRequest request) throws JsonProcessingException { return objectMapper.writeValueAsString(request.getParameterMap()); } private String getBodyString(HttpServletRequest request) throws UnsupportedEncodingException { String method = request.getMethod(); if (!(method.equals(HttpMethod.POST.name()) || method.equals(HttpMethod.PUT.name()) || method.equals(HttpMethod.PATCH.name())) ) return ""; if (request instanceof ContentCachingRequestWrapper) { ContentCachingRequestWrapper cachingRequestWrapper = (ContentCachingRequestWrapper) request; byte[] content = cachingRequestWrapper.getContentAsByteArray(); return new String(content, cachingRequestWrapper.getCharacterEncoding()); } return ""; } }
// Initial Data let square = { a1: '', a2: '', a3: '', b1: '', b2: '', b3: '', c1: '', c2: '', c3: '', }; let player = ''; let warning = ''; let playing = false; reset(); //Events /* document.querySelector('.reset').addEventListener('click', reset); document.querySelector('div[data-item=a1]').addEventListener('click', itemClick); document.querySelector('div[data-item=a2]').addEventListener('click', itemClick); document.querySelector('div[data-item=a3]').addEventListener('click', itemClick); document.querySelector('div[data-item=b1]').addEventListener('click', itemClick); document.querySelector('div[data-item=b2]').addEventListener('click', itemClick); document.querySelector('div[data-item=b3]').addEventListener('click', itemClick); document.querySelector('div[data-item=c1]').addEventListener('click', itemClick); document.querySelector('div[data-item=c2]').addEventListener('click', itemClick); document.querySelector('div[data-item=c3]').addEventListener('click', itemClick); */ document.querySelector('.reset').addEventListener('click', reset); document.querySelectorAll('.item').forEach(item => { item.addEventListener('click', itemClick); }); //Functions function itemClick(event) { let item = event.target.getAttribute('data-item'); //console.log(item); if (playing && square[item] === '') { square[item] = player; renderSquare(); togglePlayer(); } }; function reset() { warning = ''; let random = Math.floor(Math.random() * 2); player = (random === 0) ? 'x' : 'o'; //if (random === 0) { // player = 'x'; //} else { // player = 'o'; //} for (let i in square) { square[i] = ''; } playing = true; renderSquare(); renderInfo(); } function renderSquare() { for (let i in square) { //console.log("ITEM ", i); let item = document.querySelector(`div[data-item=${i}]`); item.innerHTML = square[i]; //if (square[i] !== '') { // item.innerHTML = square[i]; //} else { // item.innerHTML = ''; //} } checkGame(); } function renderInfo() { document.querySelector('.vez').innerHTML = player; document.querySelector('.resultado').innerHTML = warning; } function togglePlayer() { if (player == 'x') { player = 'o'; } else { player = 'x'; } renderInfo(); } function checkGame() { if (checkWinnerFor('x')) { warning = 'X - Venceu!'; player = false; } else if (checkWinnerFor('o')) { warning = 'O - Venceu!'; playing = false; } else if (isFull()) { warning = 'Empate!' player = false; } } function checkWinnerFor(player) { let pos = ['a1,a2,a3', 'b1,b2,b3', 'c1,c2,c3', 'a1,b1,c1', 'a2,b2,c2', 'a3,b3,c3', 'a1,b2,c3', 'a3,b2,c1']; for (let w in pos) { //console.log(pos[w]); let pArray = pos[w].split(','); //a1,a2,a3 let hasWon = pArray.every(option => square[option] === player); // pArray.every((option) => { // if (square[option] === player) { // return true; // } else { // return false; // } // }); if (hasWon) { return true; } } return false; } function isFull() { for (let i in square) { if (square[i] === '') { return false; } } return true; }
Common Issues and Solutions Not all models will simulate flawlessly. Some problems may arise upon the initialization of the model, or during the simulation itself. Below, the most common exceptions and/or issues are shown. AssertionError: Can only add BaseBlock (subclass) instances to a CBD -------------------------------------------------------------------- This error is thrown whenever you try adding a block using the :func:`pyCBD.Core.CBD.addBlock` function if that block does **not** inherit from the :class:`pyCBD.Core.BaseBlock` class. NotImplementedError: BaseBlock has nothing to compute ----------------------------------------------------- When invalidly inheriting a :class:`pyCBD.Core.BaseBlock`, this error may occur. It is a consequence of not overwriting the :func:`pyCBD.Core.BaseBlock.compute` method. ValueError: Specified object/influencer/dependent is not member of this graph ----------------------------------------------------------------------------- This issue is indicative of an error in the dependency graph construction. Usually, this is due to an invalid connection between blocks. Make sure to always connect blocks that have been added to the CBD model. I.e. always call :func:`pyCBD.Core.CBD.addBlock` **before** any :func:`pyCBD.Core.CBD.addConnection` that includes the same block. KeyError: 'X' ------------- This exception occurs if :code:`X` cannot be found. Make sure that :code:`X` is actually a block or a port in your model. Cannot solve non-linear algebraic loop. --------------------------------------- The internal solver of the CBD simulator is a simple `Gaussian-Jordan Linear solver <https://en.wikipedia.org/wiki/Gaussian_elimination>`_ (see :class:`pyCBD.solver.GaussianJordanLinearSolver`) that uses row reduction to solve the algebraic loop. However, if this loop represents a non-linear system, the solver cannot handle this. Make use of a :class:`pyCBD.lib.std.DelayBlock` to actively "break" the loop. **Hint:** Internally, the :class:`pyCBD.lib.std.DerivatorBlock` and the :class:`pyCBD.lib.std.IntegratorBlock` make use of a :class:`pyCBD.lib.std.DelayBlock`, hence they can be used to solve the issue. Warning: did not add this block as it has the same name X as an already existing block -------------------------------------------------------------------------------------- A warning that's generated by the :func:`pyCBD.Core.CBD.addBlock` method if it shares the same name as an already existing block. This is meant to ensure uniqueness of names. ImportError: cannot import name 'Clock' from partially initialized module 'pyCBD.lib.std' ----------------------------------------------------------------------------------------- Before importing the standard library, it is important to also import the :mod:`pyCBD.Core` module. This will solve the circular dependency and dissipate the error.
import { randomUUID } from 'node:crypto' import { Org, OrgCreateData, OrgsRepository } from '../orgs-repository' export class InMemoryOrgsRepository implements OrgsRepository { public orgs: Org[] = [] async findById(orgId: string) { const org = this.orgs.find((user) => { return user.id === orgId }) return org || null } async findByEmail(email: string): Promise<Org | null> { const org = this.orgs.find((eachOrg) => { return eachOrg.email === email }) return org || null } async create(data: OrgCreateData): Promise<Org> { const org: Org = { id: randomUUID(), accountable: data.accountable, email: data.email, zip_code: data.zip_code, address: data.address, whatsapp: data.whatsapp, password_hash: data.password_hash, created_at: new Date() } this.orgs.push(org) return org } }
import React from "react"; import { Route, Routes } from "react-router-dom"; import { Protected } from "./components/Protected"; import { Layout } from "./components/Layout"; import { Login } from "./pages/Login"; import { Register } from "./pages/Register"; import { AppDeveloper } from "./pages/AppDeveloper"; import SensorRegistrar from "./pages/SensorRegistrar"; import { PlatformManager } from "./pages/PlatformManager"; import { EndUser } from "./pages/EndUser"; import { NotFound } from "./pages/NotFound"; import { ScheduleForm } from "./pages/ScheduleForm"; import { EndUserNew } from "././pages/EndUserNew"; function App() { return ( <Routes> <Route path="/register" element={<Register />} /> <Route path="/login" element={<Login />} /> <Route element={<Protected redirectTo="/login" />}> <Route element={<Layout />}> <Route path="/" element={<ScheduleForm />} /> <Route path="/app-developer" element={<AppDeveloper />} /> <Route path="/sensor-registrar" element={<SensorRegistrar />} /> <Route path="/platform-manager" element={<PlatformManager />} /> <Route path="/end-user" element={<EndUser />} /> <Route path="/end-user/new" element={<EndUserNew />} /> </Route> </Route> <Route path="*" element={<NotFound />} /> </Routes> ); } export default App;
% example_script % % Build the windtunnel by adding relevant parts and their % information. % See comments in the file for more details. % % Expected output: % wind_tunnel.crosssection_test_section % input % wind_tunnel.velocity_test_section % input % parts{i} % see below % total_pressure_drop % calculated % total_loss_coefficient_ratio % calculated % power_input % calculated % power_fan % calculated % efficiency_motor % calculated % efficiency_fan % calculated % % Output, the information for specific parts: % parts{i} % where i is the part number, input and system calculated % The specific information per part depends on the part type. % See the (part specific) functions for their documentation. % % Date: June 20, 2012 % Version: 1 % Contact: [email protected] % Authors: Rinka van Dommelen % Patrick Hanckmann clear all; clear parts; clear wind_tunnel; %% Create settings settings = make_settings(); %% Start script print_info(['Windtunnel test script (' mfilename() ')'], settings); %% Windtunnel specifications (input) wind_tunnel.crosssection_test_section = 2.3226; wind_tunnel.velocity_test_section = 44.7; %% Build the parts struct % part numbers must be following!! % - Edit the following information: % - change name(first purple part), do NOT change part type (second in % purple!) % - width&hight in and width&hight out % addition info is edited at last parts = []; parts = add_part(wind_tunnel, parts, 'Straight part TS' , 'straight_part' , 1.524, 1.524, 1.524, 1.524, 'length', 1.524); parts = add_part(wind_tunnel, parts, 'Diffuser' , 'diffuser' , 1.524, 1.524, 2, 2, 'cross_section_shape', 'circle','length_center_line', 3.444, 'length_wall', 0); % Only fill in length_center_line OR length_wall, but NOT both! parts = add_part(wind_tunnel, parts, 'Corner small' , 'corner' , 2, 2, 2, 2, 'chord', 1.8); parts = add_part(wind_tunnel, parts, 'Straight part' , 'straight_part' , 2, 2, 2, 2, 'length', 1.585); parts = add_part(wind_tunnel, parts, 'Corner small' , 'corner' , 2, 2, 2, 2, 'chord', 1.8); parts = add_part(wind_tunnel, parts, 'Straight part' , 'straight_part' , 2, 2, 2, 2, 'length', 1.219); parts = add_part(wind_tunnel, parts, 'Large diffuser' , 'diffuser' , 2, 2, 3.048, 3.048, 'cross_section_shape', 'circle', 'length_center_line', 7.4, 'length_wall', 0); % Only fill in length_center_line OR length_wall, but NOT both! parts = add_part(wind_tunnel, parts, 'Corner large' , 'corner' , 3.048, 3.048,3.048, 3.048, 'chord', 2.5); parts = add_part(wind_tunnel, parts, 'Corner large' , 'corner' , 3.048, 3.048,3.048, 3.048, 'chord', 2.5); parts = add_part(wind_tunnel, parts, 'Straight part' , 'straight_part' , 3.048, 3.048,3.048, 3.048, 'length', 0.914); %parts = add_part(wind_tunnel, parts, 'Honeycomb' , 'honeycomb' , .254, .254, .254, .254, 'cell_length', .03, 'cell_diameter', .0017, 'cell_wall_thickness', .0001, 'material_roughness', 7*10^-6); parts = add_part(wind_tunnel, parts, 'Contraction' , 'contraction' , 3.048, 3.048, 1.524, 1.524, 'shape', 'curved', 'center_length', 2.577); % length = length along the center line %parts = add_part(wind_tunnel, parts, 'Screen' , 'screen' , 2, 2.5, 2, 2.5, 'wire_diameter', 0.0006, 'wire_roughness', 1.3, 'cell_diameter', 0.00253747); %parts = add_part(wind_tunnel, parts, 'Safety net' , 'safetynet' , 2, 2.5, .5, .5); % Number of parts parts_count = length(parts); %% Check parts if settings.checks.do check_windtunnel(parts, settings); end %% Calculate the part loss coefficient for i = 1:parts_count parts{i} = part_loss_coefficient(parts{i}, settings); %#ok<SAGROW> end %% Calculate the part|total pressure drop total_pressure_drop = 0; for i = 1:parts_count parts{i} = part_pressure_drop(parts{i}, settings); total_pressure_drop = total_pressure_drop + parts{i}.pressure_drop; end %% Calculate the part|total loss coefficient ratio (and percentage) total_loss_coefficient_ratio = 0; for i = 1:parts_count parts{i} = part_loss_coefficient_ratio(parts{i}, settings); total_loss_coefficient_ratio = total_loss_coefficient_ratio + parts{i}.loss_coefficient_ratio; end % Calculate the part loss percentage for i = 1:parts_count parts{i}.loss_percentage = 100 / total_loss_coefficient_ratio * parts{i}.loss_coefficient_ratio; end %% Set the efficiency values (input) wind_tunnel.efficiency_fan = 0.8; wind_tunnel.efficiency_motor = 0.8; %% Calculate the total power input wind_tunnel.reserve_factor = settings.total_power_input.reserve_factor; wind_tunnel.power_input = wind_tunnel.reserve_factor * total_pressure_drop * wind_tunnel.crosssection_test_section * wind_tunnel.velocity_test_section; %% Calculate the fan power wind_tunnel.power_fan = wind_tunnel.power_input / (wind_tunnel.efficiency_fan * wind_tunnel.efficiency_motor); %% Clear useless information clear i; clear parts_count; clear total_loss_coefficient_ratio total_pressure_drop; %% Pretty printing pretty_print(parts, wind_tunnel)
from transformers import pipeline import numpy as np from PIL import Image import cv2 import torch import torch.nn.functional as F from segment_anything import SamAutomaticMaskGenerator, sam_model_registry image_path = '//Users/kabir/Downloads/SpatialSense/samples/images/img1.jpg' image = Image.open(image_path) original_width, original_height = image.size pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-small-hf") depth = pipe(image)["depth"] depth_tensor = torch.from_numpy(np.array(depth)).unsqueeze(0).unsqueeze(0).float() depth_resized = F.interpolate(depth_tensor, size=(original_height, original_width), mode='bilinear', align_corners=False)[0, 0] depth_normalized = (depth_resized - depth_resized.min()) / (depth_resized.max() - depth_resized.min()) * 255.0 depth_normalized_np = depth_normalized.byte().cpu().numpy() colored_depth = cv2.applyColorMap(depth_normalized_np, cv2.COLORMAP_INFERNO) colored_depth_rgb = cv2.cvtColor(colored_depth, cv2.COLOR_BGR2RGB) colored_depth_image = Image.fromarray(colored_depth_rgb) colored_depth_image_path = '/Users/kabir/Downloads/SpatialSense/samples/images/new3.png' colored_depth_image.save(colored_depth_image_path) sam = sam_model_registry["vit_h"](checkpoint="/Users/kabir/Downloads/SpatialSense/model_checkpoints/sam_vit_h_4b8939.pth") mask_generator = SamAutomaticMaskGenerator(sam) colored_depth_np = np.array(colored_depth_image) masks = mask_generator.generate(colored_depth_np) image_np = np.array(colored_depth_image) image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) for mask in masks: bbox = mask['bbox'] segmentation = mask['segmentation'] seg_color = np.zeros_like(image_np) seg_color[segmentation] = [0, 255, 0] cv2.addWeighted(seg_color, 0.5, image_np, 0.5, 0, image_np) start_point = (bbox[0], bbox[1]) end_point = (bbox[0] + bbox[2], bbox[1] + bbox[3]) cv2.rectangle(image_np, start_point, end_point, (255, 0, 0), 2) image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB) marked_image = Image.fromarray(image_np) marked_image_path = '/Users/kabir/Downloads/SpatialSense/samples/images/new3_SAM.png' marked_image.save(marked_image_path)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fundamentos - Align Content</title> <style> .container { height: 325px; max-width: 300px; display: flex; flex-wrap: wrap; border: 2px solid green; } .item { background-color: orangered; padding: 0 5px; margin: 5px; flex: 1; text-align: center; color: white; } .stretch { align-content: stretch; } .center { align-content: center; } .flex-start { align-content: flex-start; } .flex-end { align-content: flex-end; } .space-around { align-content: space-around; } .space-between { align-content: space-between; } </style> </head> <body> <h1>Align Content</h1> <h2>stretch</h2> <div class="container stretch"> <div class="item">Ali foi indo voltando e indo de volta.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> </div> <h2>center</h2> <div class="container center"> <div class="item">Ali foi indo voltando e indo de volta.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando.</div> </div> <h2>flex-start</h2> <div class="container flex-start"> <div class="item">Ali foi indo voltando e indo de volta.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando.</div> </div> <h2>flex-end</h2> <div class="container flex-end"> <div class="item">Ali foi indo voltando e indo de volta.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando.</div> </div> <h2>space-around</h2> <div class="container space-around"> <div class="item">Ali foi indo voltando e indo de volta.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando.</div> </div> <h2>space-between</h2> <div class="container space-between"> <div class="item">Ali foi indo voltando e indo de volta.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua de baixo.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando e indo de volta na rua de cima com a rua.</div> <div class="item">Ali foi indo voltando.</div> <div class="item">Ali foi indo voltando.</div> </div> </body> </html>
<?php use Carbon\Carbon; use Livewire\Volt\Component; use Livewire\WithPagination; use Livewire\Attributes\Validate; use App\Models\Field; use App\Models\Package; use App\Models\Allotment; use Livewire\Attributes\Url; use App\Livewire\Forms\FilterCustomerHistoryBookingForm; new class extends Component { public FilterCustomerHistoryBookingForm $filterCustomerHistoryBookingForm; #[Url(as: 'q')] public $search = ''; public function mount () { $this->filterCustomerHistoryBookingForm->setFilter(); } public function with(): array { $filters = [ 'search' => $this->search, 'date_from' => $this->filterCustomerHistoryBookingForm->date_from, 'date_until' => $this->filterCustomerHistoryBookingForm->date_until, 'day' => $this->filterCustomerHistoryBookingForm->day, 'field' => $this->filterCustomerHistoryBookingForm->field, 'status' => 'confirmed' ]; $allotments = Allotment::filter($filters) ->where('user_id', auth()->user()->id) ->orderBy('allotments.date') ->orderBy('allotments.start_time') ->get(); $today = Carbon::parse(todayDate()); $showedBookingDateUntil = Carbon::parse($this->filterCustomerHistoryBookingForm->date_until); $fieldAutoCompletes = Field::filter($this->filterCustomerHistoryBookingForm->field)->select('name')->get(); return [ 'fieldAutoCompletes' => $fieldAutoCompletes, 'allotments' => $allotments, 'allotmentsBookedByCurrentUser' => $allotments->filter(function($value) { return $value['user_id'] === auth()->user()->id && $value['status'] === 'hold'; }), 'allotmentsByDate' => $allotments->groupBy('date')->all(), 'totalShowedBookingDays' => Carbon::parse($this->filterCustomerHistoryBookingForm->date_from)->diffInDays(Carbon::parse($showedBookingDateUntil)), ]; } public function searchBookings() { $this->resetPage(); } public function filterHistoryBookings() { $this->filterCustomerHistoryBookingForm->validate(); $this->dispatch('close-modal', 'filter-customer-history-booking'); } public function resetFilter() { $this->filterCustomerHistoryBookingForm->setFilter(); } // public function redirectToPayment() { // $this->redirectRoute('customer-payments'); // } } // ?> <div class="h-full rounded-md mx-auto"> <x-alert name="alert"></x-alert> <div class="mb-6"> {{-- <img class="object-cover w-full h-56 rounded-md" src="{{ asset($field->image) }}" alt="{{ $field->name }}"> --}} <h1 class="text-xl font-bold mt-2">History Bookings</h1> </div> <button @click="$dispatch('open-modal', 'filter-customer-history-booking')" class="flex items-center bg-white mb-2 shadow-sm py-2 px-4 me-4 border border-slate-500 text-slate-500 rounded-md hover:bg-indigo-800 hover:text-gray-200"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6 me-2"> <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 1 1-3 0m3 0a1.5 1.5 0 1 0-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 0 1-3 0m3 0a1.5 1.5 0 0 0-3 0m-9.75 0h9.75" /> </svg> <span>Filter</span> </button> <x-forms.booking.customer.filter-history-booking :fieldAutoCompletes="$fieldAutoCompletes"/> {{-- list --}} <div id="draggable-zone" class="w-full overflow-x-auto whitespace-nowrap"> <div id="draggable-content" class="inline-block whitespace-nowrap cursor-grab"> @for($day = 0; $day <= $totalShowedBookingDays; $day++) @php $rowCarbonDate = Carbon::parse($filterCustomerHistoryBookingForm->date_from)->addDays($day); $rowDate = $rowCarbonDate->format('d M'); $rowDay = $rowCarbonDate->format('l'); $allotmentsPerDate = $allotmentsByDate[$rowCarbonDate->format('Y-m-d')] ?? []; @endphp <div class="flex gap-4 select-none"> <div class="flex flex-col justify-center items-center text-center bg-white rounded-md p-4 mb-2 min-w-36"> <h3 class="font-bold text-lg mb-2">{{ $rowDate }}</h3> <h5 class="text-md text-indigo-600">{{ $rowDay }}</h5> </div> {{-- loop yg group by itu --}} @foreach ($allotmentsPerDate as $allotment) @php $formattedStartTime = Carbon::createFromTimeString($allotment->start_time)->format('H:i'); $formattedEndTime = Carbon::createFromTimeString($allotment->end_time)->format('H:i'); $statusClassStyle = [ 'available' => [ 'bg' => 'bg-white', 'icon' => ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-8 h-8 text-indigo-600"> <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25ZM12.75 9a.75.75 0 0 0-1.5 0v2.25H9a.75.75 0 0 0 0 1.5h2.25V15a.75.75 0 0 0 1.5 0v-2.25H15a.75.75 0 0 0 0-1.5h-2.25V9Z" clip-rule="evenodd" /> </svg>', 'color' => 'text-black', 'statusColor' => 'text-indigo-800' ], 'self-booked-hold' => [ 'bg' => 'bg-indigo-600', 'icon' => ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-8 h-8 text-white"> <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm3 10.5a.75.75 0 0 0 0-1.5H9a.75.75 0 0 0 0 1.5h6Z" clip-rule="evenodd" /> </svg>', 'color' => '!text-white', 'statusColor' => '!text-white' ], 'other-booked' => [ 'bg' => 'bg-gray-600', 'icon' => ' <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="w-8 h-8 text-gray-400"> <path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm3 10.5a.75.75 0 0 0 0-1.5H9a.75.75 0 0 0 0 1.5h6Z" clip-rule="evenodd" /> </svg>', 'color' => '!text-white', 'statusColor' => '!text-white' ], ]; if ($allotment->user_id == auth()->user()->id) { switch ($allotment->status) { case 'hold': $cardLookup = $statusClassStyle['self-booked-hold']; break; case 'verifying': $cardLookup = $statusClassStyle['other-booked']; break; default: $cardLookup = $statusClassStyle['other-booked']; break; } } else { $cardLookup = $allotment->status === 'available' ? $statusClassStyle['available'] : $statusClassStyle['other-booked']; } @endphp <div wire:click="handleBooking('{{ $allotment->id }}')" class="bg-indigo-600 rounded-md mb-2 px-4 py-6 min-w-40 transition-all hover:cursor-pointer"> <div class="text-center {{ $cardLookup['color'] }}"> <h5 class="{{ $cardLookup['statusColor'] }} text-lg mb-2">{{ ucwords($allotment->field_name)}}</h5> <h5 class="text-xl font-bold mb-2">{{ $formattedStartTime . ' - ' . $formattedEndTime}}</h5> <h3 class=" mb-2">{{ formatToRupiah($allotment->price)}}</h3> </div> </div> @endforeach @if (!$allotmentsPerDate) <div class="w-full p-4 bg-white flex items-center mb-2"> <h3 class="text-gray-400">No Booking Available !</h3> </div> @endif </div> @endfor </div> </div> {{-- klu ad allotment yg pnya user --}} <div wire:click="redirectToPayment" class=" bg-white p-4 sticky bottom-0 transition-all {{ count($allotmentsBookedByCurrentUser) ? '' : 'hidden' }}"> <button class="w-full py-4 text-center bg-indigo-600 rounded-md text-white">Continue To Payment</button> </div> @once <script> $(document).ready(function() { $("#draggable-content").draggable({ axis: "x", // Allow dragging only horizontally drag: function(event, ui) { // Update the scrollLeft of the draggable-zone based on the drag movement $("#draggable-zone").scrollLeft($("#draggable-zone").scrollLeft() - ui.position.left + ui.originalPosition.left); ui.position.left = ui.originalPosition.left; // Prevent vertical movement } }); }); </script> @endonce </div>
#!/usr/bin/env python3 # # Copyright 2020 Martin Luelf <[email protected]>. # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This software 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 software; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # # from gnuradio import gr, gr_unittest from gnuradio import blocks import ccsds_swig as ccsds import random import numpy import os import pmt import time class qa_blob_msg_sink (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block() def tearDown (self): self.tb = None def runExperiment(self, num_blobs, blob_len): # generate data blobs = [] data = [] for i in range(num_blobs) : blob = [int(i) for i in numpy.random.randint(0, 256, blob_len)] [data.append(byte) for byte in blob] blobs.append(blob) # blocks self.blob_sink = ccsds.blob_msg_sink_b(blob_len) self.src = blocks.vector_source_b(tuple(data), False) self.dbg = blocks.message_debug() # connections self.tb.connect((self.src, 0), (self.blob_sink, 0)) self.tb.msg_connect(self.blob_sink, "out", self.dbg, "store") # start flowgraph self.tb.start() # timeout = 50 # while(self.dbg.num_messages() < num_blobs+1 and timeout > 0): # time.sleep(0.1) # timeout -= 1 # self.assertTrue(timeout > 0, 'Test timed out') # self.tb.stop() self.tb.wait() self.assertTrue(self.dbg.num_messages() >= num_blobs) # test for EOF # Disabled, because EOF messages tend to get lost in 3.8 TODO: re-enable once this issue has been solved #eof_msg = self.dbg.get_message(self.dbg.num_messages()-1) #self.assertEqual (pmt.is_eof_object(eof_msg), True, 'EOF block no at expected position') # test the blobs for i in range(min(self.dbg.num_messages()-1, num_blobs)): dbg_msg_in = self.dbg.get_message(i) dbg_msg = pmt.cdr(dbg_msg_in) dbg_data = [] [dbg_data.append(pmt.u8vector_ref(dbg_msg, j)) for j in range(pmt.length(dbg_msg))] self.assertEqual (blobs[i], dbg_data, 'BLOB data mismatch in %d byte BLOB no %d/%d' % (blob_len, i+1, num_blobs)) # send 0 BLOBs (just EOF) and return def test_eof(self): self.runExperiment(0, 0) # send one small BLOB def test_one_small(self): self.runExperiment(1, 1) # send 100 BLOBs of 100 byte def test_hundred(self): self.runExperiment(100, 100) # send one huge BLOB def test_one_large(self): self.runExperiment(1, 10000) # send many small BLOB def test_many_small(self): self.runExperiment(10000, 1) if __name__ == '__main__': gr_unittest.run(qa_blob_msg_sink)
--- title: Заголовок запроса slug: Словарь/Request_header tags: - Словарь translation_of: Glossary/Request_header --- <p><strong>Заголовок запроса</strong> - <a href="/en-US/docs/Glossary/header">HTTP header</a> который используется в  HTTP-запросе и который не относиться к содержимому сообщения. Заголовки запроса, такие как <a href="/ru/docs/Web/HTTP/Headers/Accept" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>Accept</code></a>, <a href="/ru/docs/Web/HTTP/Headers/Accept-Language" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>Accept-*</code></a> или <a href="/ru/docs/Web/HTTP/Headers/If-Modified-Since" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>If-*</code></a> позволяют выполнять условные запросы; другие, такие как <a href="/ru/docs/Web/HTTP/Headers/Cookie" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>Cookie</code></a>, <a href="/ru/docs/Web/HTTP/Headers/User-Agent" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>User-Agent</code></a> или <a href="/ru/docs/Web/HTTP/Headers/Referer" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>Referer</code></a> уточняют контекст, чтобы сервер мог адаптировать ответ.</p> <p>Не все заголовки, появляющиеся в запросе, являются <em>заголовками запроса</em>. Например, <a href="/ru/docs/Web/HTTP/Headers/Content-Length" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>Content-Length</code></a>, появляющийся в запросе <a href="/ru/docs/Web/HTTP/Methods/POST" title="HTTP-метод POST предназначен для отправки данных на сервер. Тип тела запроса указывается в заголовке Content-Type."><code>POST</code></a>, на самом деле является <a href="/ru/docs/%D0%A1%D0%BB%D0%BE%D0%B2%D0%B0%D1%80%D1%8C/Entity_header">заголовки сущности</a>, ссылающимся на размер тела сообщения запроса. Однако в таком контексте эти заголовки сущности часто называют заголовками запроса.</p> <p>Кроме того, <a href="/ru/docs/Словарь/CORS">CORS</a> определяет подмножество заголовков запросов как <a href="/ru/docs/%D0%A1%D0%BB%D0%BE%D0%B2%D0%B0%D1%80%D1%8C/%D0%9F%D1%80%D0%BE%D1%81%D1%82%D0%BE%D0%B9_%D0%B7%D0%B0%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%BE%D0%BA">простой заголовок</a>, заголовки запросов, которые всегда считаются авторизованными и не указаны явно в ответах на <a href="/en-US/docs/Glossary/preflight_request">preflight</a> запросов.</p> <p>Несколько заголовков запроса после запроса <a href="/ru/docs/Web/HTTP/Methods/GET" title="HTTP-метод GET запрашивает представление указанного ресурса. GET-запросы должны только получать данные."><code>GET</code></a>:</p> <pre>GET /home.html HTTP/1.1 Host: developer.mozilla.org User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: https://developer.mozilla.org/testpage.html Connection: keep-alive Upgrade-Insecure-Requests: 1 If-Modified-Since: Mon, 18 Jul 2016 02:36:04 GMT If-None-Match: "c561c68d0ba92bbeb8b0fff2a9199f722e3a621a" Cache-Control: max-age=0</pre> <p>Строго говоря, заголовок <a href="/ru/docs/Web/HTTP/Headers/Content-Length" title="Документация об этом ещё не написана; пожалуйста, поспособствуйте её написанию!"><code>Content-Length</code></a> в этом примере является не заголовком запроса, как другие, а представляет <a href="/ru/docs/%D0%A1%D0%BB%D0%BE%D0%B2%D0%B0%D1%80%D1%8C/Entity_header">заголовок сущности</a>:</p> <pre>POST /myform.html HTTP/1.1 Host: developer.mozilla.org User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0 Content-Length: 128 </pre> <h2 id="Узнать_больше">Узнать больше</h2> <h3 id="Технические_знания">Технические знания</h3> <ul> <li><a href="/ru/docs/Web/HTTP/Заголовки">Список всех HTTP заголовков</a></li> </ul>
/** @jsx jsx */ import { Flex, jsx } from 'theme-ui'; import Input from './Input'; import Text from './Text'; interface Props { shadow: boolean; } const SubscribeForm = ({ shadow, ...props }: Props): JSX.Element => { return ( <div {...props}> <Flex sx={{ mb: 3, flexDirection: ['column', 'row'] }}> <Input placeholder="Enter your email" sx={{ ...(shadow && { boxShadow: '0 2px 4px 0 #006ECC', }), mr: [0, 2], mb: ['12px', 0], textAlign: ['center', 'left'], ':focus': { boxShadow: (theme) => `0 0px 0px 4px ${theme.colors.primaryLight}`, }, }} /> <button sx={{ borderRadius: 32, height: 56, bg: 'secondary', ...(shadow && { boxShadow: '0 2px 4px 0 #006ECC', }), outline: 'none', border: 'none', color: 'primary', fontFamily: 'body', fontSize: '1', px: 5, width: ['100%', 'auto'], }} > Subscribe </button> </Flex> <Text variant="detail" sx={{ textAlign: 'center', display: 'block' }}> Unsubscribe at <span sx={{ fontStyle: 'italic' }}>any</span> time </Text> </div> ); }; export default SubscribeForm;
import { connect } from "@/dbConfig/dbConfig"; import User from '@/models/userModel' import bcryptjs from 'bcryptjs' import { NextRequest, NextResponse } from "next/server"; import { sendEmail } from "@/helpers/mailer"; connect(); export async function POST(request:NextRequest){ try { const reqBody = await request.json() const {username, email, password} = reqBody console.log(reqBody) const user = await User.findOne({email}) if(user) { return NextResponse.json({error: "User already exists"}, {status: 400}) } const salt = bcryptjs.genSaltSync(10); const hashedPassword = await bcryptjs.hash(password, salt) const newUser = new User({ username, email, password: hashedPassword }) const savedUser = await newUser.save() console.log("savedUser",savedUser); await sendEmail({email,emailType:"VERIFY", userId: savedUser._id }) return NextResponse.json({ message: "User registered successfully", success: true, savedUser }) } catch (error:any) { return NextResponse.json({error: error.message}, {status: 500}) } }
{% extends 'products/base.html' %} {% block content %} <div class="container my-5"> <div class="card"> <div class="row"> <aside class="col-sm-5 border-right"> <article class="gallery-wrap"> <div class="img-big-wrap"> <div> <a href="#"><img src="/media/{{ object.mainimage }}" style="width: 450px"></a></div> </div> <!-- slider-product.// --> </article> <!-- gallery-wrap .end// --> </aside> <aside class="col-sm-7"> <article class="card-body p-5"> <h3 class="title mb-3">{{ object.name }}</h3> <p class="price-detail-wrap"> <span class="price h3 text-warning"> <span class="currency">US $</span><span class="num">{{ object.price }}</span> </span> </p> <!-- price-detail-wrap .// --> <dl class="item-property"> <dt>Description</dt> <dd><p>{{ object.preview_text }}</p></dd> </dl> <a href="{% url 'mainapp:cart' object.slug %}" class="btn btn-lg btn-outline-primary text-uppercase"> <i class="fas fa-shopping-cart"></i> Add to cart </a> </article> <!-- card-body.// --> </aside> <!-- col.// --> </div> <!-- row.// --> </div> <!-- card.// --> <div class="container-fluid"> <form id="friend-form"> <div class="row"> {% csrf_token %} {% for field in form %} <div class="form-group col-4"> <label class="col-12">{{ field.label }}</label> {{ field }} </div> {% endfor %} <div class = "col text-center"> <input type="submit" class="btn btn-primary" value="Цена" /> </div> </div> <form> </div> <hr /> <div class="container-fluid"> <table class="table table-striped table-sm" id="my_friends"> <thead> <tr> <th>First name</th> <th>Tirazh</th> <th>DOB</th> </tr> </thead> <tbody> {% for friend in friends %} <tr> <td>{{friend.first_name}}</td> <td>{{friend.tirazh}}</td> <td>{{friend.dob | date:"Y-m-d"}}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock %} </div> <!--container.//--> <div class="container-fluid"> <form id="friend-form"> <div class="row"> {% csrf_token %} {% for field in form %} <div class="form-group col-4"> <label class="col-12">{{ field.label }}</label> {{ field }} </div> {% endfor %} <div class = "col text-center"> <input type="submit" class="btn btn-primary" value="Цена" /> </div> </div> <form> </div> <hr /> {% block javascript %} <script> $(document).ready(function () { /* On submiting the form, send the POST ajax request to server and after successfull submission display the object. */ $("#friend-form").submit(function (e) { // preventing from page reload and default actions e.preventDefault(); // serialize the data for sending the form data. var serializedData = $(this).serialize(); // make POST ajax call $.ajax({ type: 'POST', url: "{% url 'post_friend' %}", data: serializedData, success: function (response) { // on successfull creating object // 1. clear the form. $("#friend-form").trigger('reset'); // 2. focus to nickname input $("#id_nick_name").focus(); // display the newly friend to table. var instance = JSON.parse(response["instance"]); var fields = instance[0]["fields"]; $("#my_friends tbody").prepend( `<tr> <td>${fields["nick_name"]||""}</td> <td>${fields["first_name"]||""}</td> <td>${fields["last_name"]||""}</td> <td>${fields["likes"]||""}</td> <td>${fields["dob"]||""}</td> <td>${fields["lives_in"]||""}</td> </tr>` ) }, error: function (response) { // alert the error if any error occured alert(response["responseJSON"]["error"]); } }) }) /* On focus out on input nickname, call AJAX get request to check if the nickName already exists or not. */ $("#id_nick_name").focusout(function (e) { e.preventDefault(); // get the nickname var nick_name = $(this).val(); // GET AJAX request $.ajax({ type: 'GET', url: "{% url 'validate_nickname' %}", data: {"nick_name": nick_name}, success: function (response) { // if not valid user, alert the user if(!response["valid"]){ alert("You cannot create a friend with same nick name"); var nickName = $("#id_nick_name"); nickName.val("") nickName.focus() } }, error: function (response) { console.log(response) } }) }) }) </script> {% endblock javascript %}
export class User { constructor( private id: string, private name: string, private email: string, private password: string ) { } public getId() : string { return this.id } public getName() : string { return this.name } public getEmail() : string { return this.email } public getPassword() : string { return this.password } public setName(newName : string): void { this.name = newName; } public setEmail(newEmail : string): void { this.email = newEmail; } public setPassword(newPassword : string): void { this.password = newPassword; } }
package com.goitgroupsevenbot.service; import com.goitgroupsevenbot.config.BotConstance; import com.goitgroupsevenbot.entity.enums.*; import com.goitgroupsevenbot.entity.domain.User; import com.goitgroupsevenbot.entity.domain.CurrencyBankItem; import com.goitgroupsevenbot.entity.enums.Currency; import com.goitgroupsevenbot.repository.CurrencyBankRepository; import com.goitgroupsevenbot.repository.UserRepository; import lombok.SneakyThrows; import org.joda.time.DateTime; import org.telegram.telegrambots.bots.TelegramLongPollingBot; import org.telegram.telegrambots.meta.api.methods.commands.SetMyCommands; import org.telegram.telegrambots.meta.api.methods.send.SendMessage; import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText; import org.telegram.telegrambots.meta.api.objects.*; import org.telegram.telegrambots.meta.api.objects.commands.BotCommand; import org.telegram.telegrambots.meta.api.objects.commands.scope.BotCommandScopeDefault; import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup; import java.sql.Timestamp; import java.util.*; public class TelegramBot extends TelegramLongPollingBot { private UserRepository userRepository; private UtilMethods util; @SneakyThrows public TelegramBot() { userRepository = new UserRepository(); util = new UtilMethods(userRepository); List<BotCommand> listOfCommands = new ArrayList<>(); listOfCommands.add(new BotCommand("start", "Головне меню")); listOfCommands.add(new BotCommand("info", "Отримати інформацію про курс валют")); listOfCommands.add(new BotCommand("settings", "Налаштування запиту інформації")); listOfCommands.add(new BotCommand("symbols", "Налаштування - Кількість символів після коми")); listOfCommands.add(new BotCommand("banks", "Налаштування - Банк")); listOfCommands.add(new BotCommand("currency", "Налаштування - Валюта")); listOfCommands.add(new BotCommand("notification", "Налаштування - Оповіщення")); this.execute(new SetMyCommands(listOfCommands, new BotCommandScopeDefault(), null)); } @Override public void onUpdateReceived(Update update) { if (update.hasCallbackQuery()) { //If we have update call back (button pressed). handleCallback(update.getCallbackQuery()); } else if (update.hasMessage()) { //If we have update message. handelMessage(update.getMessage()); } } private void handleCallback(CallbackQuery callbackQuery) { Message message = callbackQuery.getMessage(); //We know in what format we gat data (cos we set up it when create the buttons), so we extract data. System.out.println("callbackQuery.getData() = " + callbackQuery.getData()); String[] param = callbackQuery.getData().split(":"); String action = param[0]; System.out.println("action = " + action); switch (action) { case "START" -> { switch (param[1]) { case "settings" -> settingsCommandReceived(message.getChatId()); case "info" -> getRateCommandReceived(message.getChatId()); } } case "NEXT" -> { switch (param[1]) { case "symbol" -> banksCommandReceived(message.getChatId()); case "settings" -> symbolsCommandReceived(message.getChatId()); case "banks" -> currencyCommandReceived(message.getChatId()); case "currency" -> notificationCommandReceived(message.getChatId()); case "notification" -> getRateCommandReceived(message.getChatId()); } } case "BACK" -> { switch (param[1]) { case "symbol" -> settingsCommandReceived(message.getChatId()); case "banks" -> symbolsCommandReceived(message.getChatId()); case "currency" -> banksCommandReceived(message.getChatId()); case "notification" -> currencyCommandReceived(message.getChatId()); } } case "SETTINGS" -> { switch (param[1]) { case "symbols" -> symbolsCommandReceived(message.getChatId()); case "bank" -> banksCommandReceived(message.getChatId()); case "currency" -> currencyCommandReceived(message.getChatId()); case "notification" -> notificationCommandReceived(message.getChatId()); } } case "SYMBOL" -> symbolCallBackReceived(param[1], message); case "BANKS" -> banksCallBackReceived(param[1], message); case "CURRENCY_TARGET" -> currencyCallBackReceived(param[1], message); case "NOTIFICATION" -> notificationCallBackReceived(param[1], message); case "NOTIFICATION_TIME_ZONE" -> notificationTimeZoneCallBackReceived(param[1], message); } } private void handelMessage(Message message) { if (message.hasText() && message.hasEntities()) { //Looking for command. Optional<MessageEntity> commandEntity = message.getEntities().stream().filter(e -> "bot_command".equals(e.getType())).findFirst(); if (commandEntity.isPresent()) { //If command is present extract it. String command = message.getText().substring(commandEntity.get().getOffset(), commandEntity.get().getLength()); //Response on command if it exists. switch (command) { case "/start" -> startCommandReceived(message); case "/info" -> getRateCommandReceived(message.getChatId()); case "/settings" -> settingsCommandReceived(message.getChatId()); case "/symbols" -> symbolsCommandReceived(message.getChatId()); case "/banks" -> banksCommandReceived(message.getChatId()); case "/currency" -> currencyCommandReceived(message.getChatId()); case "/notification" -> notificationCommandReceived(message.getChatId()); } } } } /** * Method for responding to the SYMBOL call back. * * @param param Call back data. * @param message Message from user. */ private void symbolCallBackReceived(String param, Message message) { NumberOfSymbolsAfterComma symbol = NumberOfSymbolsAfterComma.valueOf(param); userRepository.getById(message.getChatId()).setSymbols(symbol); String answer = "Оберіть кількість знаків після коми:"; sendEditMessageWithInlineKeyboard(message.getChatId(), message.getMessageId(), answer, util.symbolsButtons(message.getChatId())); } /** * Method for responding to the BANKS call back. * * @param param Call back data. * @param message Message from user. */ private void banksCallBackReceived(String param, Message message) { Banks bank = Banks.valueOf(param); userRepository.getById(message.getChatId()).setBank(bank); String answer = "Оберіть банк для запиту курсу валют:"; sendEditMessageWithInlineKeyboard(message.getChatId(), message.getMessageId(), answer, util.banksButtons(message.getChatId())); } /** * Method for responding to the CURRENCY call back. * * @param param Call back data. * @param message Message from user. */ private void currencyCallBackReceived(String param, Message message) { Currency currencyTarget = Currency.valueOf(param); if (userRepository.getById(message.getChatId()).getCurrencyTarget().containsKey(currencyTarget)) { userRepository.getById(message.getChatId()).getCurrencyTarget().remove(currencyTarget); String answer = "Оберіть валюти:"; sendEditMessageWithInlineKeyboard(message.getChatId(), message.getMessageId(), answer, util.currencyButtons(message.getChatId())); } else { userRepository.getById(message.getChatId()).getCurrencyTarget().put(currencyTarget, currencyTarget); String answer = "Оберіть валюти:"; sendEditMessageWithInlineKeyboard(message.getChatId(), message.getMessageId(), answer, util.currencyButtons(message.getChatId())); } } /** * Method for responding to the NOTIFICATION call back. * * @param param Call back data. * @param message Message from user. */ private void notificationCallBackReceived(String param, Message message) { NotificationTime notification = NotificationTime.valueOf(param); userRepository.getById(message.getChatId()).setNotificationTime(notification); String answer = "Оберіть час оповіщення:"; sendEditMessageWithInlineKeyboard(message.getChatId(), message.getMessageId(), answer, util.notificationButtons(message.getChatId())); } /** * Method for responding to the NOTIFICATION_TIME_ZONE call back. * * @param param Call back data. * @param message Message from user. */ private void notificationTimeZoneCallBackReceived(String param, Message message) { TimeZones zone = TimeZones.valueOf(param); userRepository.getById(message.getChatId()).setTimeZone(zone); String answer = "Оберіть час оповіщення:"; sendEditMessageWithInlineKeyboard(message.getChatId(), message.getMessageId(), answer, util.notificationButtons(message.getChatId())); } /** * Method for responding to the /notification command. * * @param chatId Chat's ID long. */ private void notificationCommandReceived(Long chatId) { String answer = "Оберіть час оповіщення:"; sendMessageWithInlineKeyboard(chatId, answer, util.notificationButtons(chatId)); } /** * Method for responding to the /banks command. * * @param chatId Chat's ID long. */ private void currencyCommandReceived(Long chatId) { String answer = "Оберіть валюти:"; sendMessageWithInlineKeyboard(chatId, answer, util.currencyButtons(chatId)); } /** * Method for responding to the /banks command. * * @param chatId Chat's ID long. */ private void banksCommandReceived(Long chatId) { String answer = "Оберіть банк для запиту курсу валют:"; sendMessageWithInlineKeyboard(chatId, answer, util.banksButtons(chatId)); } /** * Method for responding to the /symbols command. * * @param chatId Chat's ID long. */ private void symbolsCommandReceived(long chatId) { String answer = "Оберіть кількість знаків після коми:"; sendMessageWithInlineKeyboard(chatId, answer, util.symbolsButtons(chatId)); } /** * Method for responding to the /settings command. * * @param chatId Chat's ID long. */ private void settingsCommandReceived(long chatId) { String answer = "Оберіть налаштування:"; sendMessageWithInlineKeyboard(chatId, answer, util.settingsButtons()); } /** * Util method to register a new user. * * @param message Message form user. */ private void registerUser(Message message) { if (!isUserRegistered(message.getChatId())) { Long chatId = message.getChatId(); Chat chat = message.getChat(); User user = User.builder().chatId(chatId).firstName(chat.getFirstName()).lastName(chat.getLastName()).userName(chat.getUserName()) .symbols(NumberOfSymbolsAfterComma.TWO) .bank(Banks.NABU) .currencyTarget(new HashMap<>(Map.of(Currency.USD, Currency.USD))) .timeZone(TimeZones.KYIV) .notificationTime(NotificationTime.NINE) .registeredAt(new Timestamp(System.currentTimeMillis())) .build(); userRepository.addUser(message.getChatId(), user); System.out.println("userRepository.getAll() = " + userRepository.getAll()); } } /** * Method for responding to the /start command. * * @param message Message fom user. */ private void startCommandReceived(Message message) { registerUser(message); User user = userRepository.getById(message.getChatId()); String answer = "Цей бот відображає курси валют\nНалаштування :\nБанк : " + user.getBank().getName() + "\nВалюта : " + user.currencyToString() + "\nКількість знаків після коми : " + user.getSymbols().getNumber() + "\nЧасовий пояс : " + user.getTimeZone().getName() + "\nЧас оповіщення : " + user.getNotificationTime().getText(); sendMessageWithInlineKeyboard(message.getChatId(), answer, util.startButtons()); } /** * Method for sending notification according to user preference. */ public void sendNotification() { userRepository.getAll().values().forEach(it -> it.setCurrentTime(new DateTime(it.getTimeZone().getTimeZone()).getHourOfDay())); userRepository.getAll().values().stream() .filter(it -> it.getNotificationTime().getTime() == it.getCurrentTime()) .forEach(it -> getRateCommandReceived(it.getChatId())); } /** * Method for responding to the /info command. * * @param chatId Chat ID. */ public void getRateCommandReceived(Long chatId) { User user = userRepository.getById(chatId); if (user.getCurrencyTarget().size() == 0) { String answer = "У вас не обрано жодної валюти. Оберіть валюту"; sendMessageWithInlineKeyboard(user.getChatId(), answer, util.getInfoEmptyCurrencyButtons()); } else { StringBuilder sb = new StringBuilder(); List<CurrencyBankItem> listBanks = CurrencyBankRepository.getList().stream() .filter(it -> it.getBanks().equals(user.getBank())) .filter(it -> it.getCurrency().equals(user.getCurrencyTarget().get(it.getCurrency()))) .toList(); for (CurrencyBankItem listBank : listBanks) { sb.append("Курс ") .append(listBank.getBanks().getName()) .append(" UAH/ ") .append(listBank.getCurrency().getText()) .append("\nКупівля: ") .append(String.format(user.getSymbols().getExpression(), listBank.getRateBuy())) .append("\nПродаж: ") .append(String.format(user.getSymbols().getExpression(), listBank.getRateSell())) .append("\n"); } String answer = "\nКількість знаків після коми : " + user.getSymbols().getNumber() + "\nЧас оповіщення : " + user.getNotificationTime().getText() + "\n" + sb; sendMessageWithInlineKeyboard(user.getChatId(), answer, util.getInfoButtons()); } } /** * Util method to send edit message with inline keyboard. * * @param chatId Chat's ID long. * @param text Text to send. * @param markup Markup with list of buttons. */ private void sendEditMessageWithInlineKeyboard(long chatId, int messageId, String text, InlineKeyboardMarkup markup) { EditMessageText message = EditMessageText.builder() .chatId(chatId).messageId(messageId) .text(text).replyMarkup(markup) .build(); executeEditMessage(message); } /** * Util method to send edit message. * * @param chatId Chat's ID long. * @param text Text to send. */ private void sendEditMessage(long chatId, int messageId, String text) { EditMessageText message = EditMessageText.builder().chatId(chatId).messageId(messageId).text(text).build(); executeEditMessage(message); } /** * Util method to execute sending edit message. * * @param message object of SendMessage. */ @SneakyThrows private void executeEditMessage(EditMessageText message) { execute(message); } /** * Util method to send message. * * @param chatId Chat's ID long. * @param text Text to send. */ private void sendMessage(long chatId, String text) { SendMessage message = SendMessage.builder().chatId(chatId).text(text).build(); executeMessage(message); } /** * Util method to execute sending message. * * @param message object of SendMessage. */ @SneakyThrows private void executeMessage(SendMessage message) { execute(message); } /** * Util method to check if user registered. * * @param chatId Chat id. */ private boolean isUserRegistered(long chatId) { return userRepository.getAll().containsKey(chatId); } /** * Util method to send message with inline keyboard. * * @param chatId Chat's ID long. * @param text Text to send. * @param markup Markup with list of buttons. */ private void sendMessageWithInlineKeyboard(long chatId, String text, InlineKeyboardMarkup markup) { SendMessage message = SendMessage.builder().chatId(chatId).text(text).replyMarkup(markup).build(); executeMessage(message); } @Override public String getBotUsername() { return BotConstance.BOT_NAME; } @Override public String getBotToken() { return BotConstance.BOT_TOKEN; } }
{% extends 'rango/base.html' %} {% load staticfiles %} {% block title_block %} Index {% endblock %} {% block body_block %} <h1>Rango syas...hello world!</h1> <div> <h3>Most Liked Categories</h3> {% if categories %} <ul> {% for category in categories %} <li> <a href="/rango/category/{{ category.slug }}">{{ category.name }}</a> </li> {% endfor %} </ul> {% else %} <strong>There are no categories present.</strong> {% endif %} </div> <div> <h3>Most Liked Pages</h3> {% if pages %} <ul> {% for page in pages %} <li> <a href="{{ page.url }}">{{ page.title }}</a> </li> {% endfor %} </ul> {% else %} <strong>There are no pages present.</strong> {% endif %} </div> <div> <a href="/rango/about/">About</a><br /> <a href="/rango/add_category/">Add a New Category</a><br /> <a href="/rango/register/">Register Here</a><br /> <a href="{% url 'rango:login' %}">Login</a><br /> <img src="{% static "images/background.jpg" %}" alt="Picture of Bk" /> </div> <div> <ul> {% if user.is_authenticated %} <li><a href="{% url 'rango:restricted' %}">Restricted Page</a></li> <li><a href="{% url 'rango:logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'rango:login' %}">Sign In</a></li> <li><a href="{% url 'rango:register' %}">Sign Up</a></li> {% endif %} </ul> </div> <div> <p>visits: {{ visits }}</p> </div> {% endblock %}
function Register-MeidIdentityProvider { <# .SYNOPSIS Register Entra ID identity provider. .DESCRIPTION Register Microsoft Entra ID identity provider. .PARAMETER Name Name(s) of the Entra ID identity provider. .PARAMETER NameProperty Property(s) to search for. E.g.: userPrincipalName .PARAMETER Query Graph endpoint url. E.g.: users .EXAMPLE PS C:\> Register-MeidIdentityProvider -Name "UserUPN" -NameProperty "userPrincipalName" -Query "users" Will register a provider with name "UserUPN", the property to search for "userPrincipalName" with the query "users/{0}". .NOTES General notes #> [CmdletBinding()] param ( [Parameter(Mandatory)] [string[]] $Name, [Parameter(Mandatory)] [string[]] $NameProperty, [Parameter(Mandatory)] [string[]] $Query ) process { $queries = foreach ($item in $Query){ if($item -match "\{0\}"){ $item; continue} $item.TrimEnd("/").Replace("{","{{").Replace("}","}}"), "{0}" -join "/" } foreach ($entry in $Name) { $script:IdentityProvider[$entry] = [PSCustomObject]@{ Name = $entry NameProperty = $NameProperty Query = $queries } } } }
import React, { useMemo, useState, useRef, useCallback } from "react"; import ToDo from "./Todo"; import { uniqueNamesGenerator, Config, starWars } from "unique-names-generator"; import { nanoid } from "nanoid"; import { CirclePicker, SliderPicker } from "react-color"; const customConfig = { dictionaries: [starWars], separator: " ", length: 1 }; const initialList = [ { id: nanoid(), name: "buy stuf", completed: false }, { id: nanoid(), name: "sell stuf", completed: true } ]; const ToDoList = () => { const [todosList, setTodosList] = useState([]); const [color, setColor] = useState("#eeffdd"); const rendersCounter = useRef(0); rendersCounter.current = rendersCounter.current + 1; const handleAddToDo = () => { setTodosList([ ...todosList, { id: nanoid(), name: uniqueNamesGenerator(customConfig), completed: false } ]); }; const handleChange = useCallback( (id) => { const updatedTasks = todosList.map((todo) => { if (todo.id === id) { return { ...todo, completed: !todo.completed }; } return todo; }); setTodosList(updatedTasks); }, [todosList] ); const deleteTodo = useCallback( (id) => { console.log(id); const updatedTasks = todosList.filter((todo) => todo.id !== id); console.log(updatedTasks); setTodosList(updatedTasks); }, [todosList] ); const deleteAll = () => { setTodosList([]); }; const conpleteAll = () => { const updatedTasks = todosList.map((todo) => { return { ...todo, completed: true }; }); setTodosList(updatedTasks); }; const handleChangeComplete = (color) => { setColor(color.hex); }; const MemoTodo = React.memo(ToDo); console.count("render list"); return ( <div> <span className="todo-renders_tag">{rendersCounter.current}</span> <div> <div> <SliderPicker color={color} onChange={handleChangeComplete} /> <button onClick={handleAddToDo}>add</button> <button onClick={deleteAll}>delete all</button> <button onClick={conpleteAll}>complete all</button> </div> <div className="tods-wrapper"> {todosList.map((todo) => ( <MemoTodo color={color} key={todo?.id} todo={todo} setComplete={handleChange} deleteTodo={deleteTodo} /> ))} </div> </div> </div> ); }; export default ToDoList;
from motor.motor_asyncio import AsyncIOMotorClient from fastapi import APIRouter, Depends, HTTPException, status from fastapi.security import OAuth2PasswordBearer,OAuth2PasswordRequestForm from pydantic import BaseModel, Extra from passlib.context import CryptContext from typing import Optional from fastapi import status from jose import JWTError,jwt from datetime import datetime, timedelta from db import get_database # Create an APIRouter instance router = APIRouter( prefix="/auth", tags=["User Authentication"], responses={404: {"description": "Not found"}}, ) oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login") pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") class User(BaseModel): id: Optional[str] = None username: str password: str profilePic : Optional[str] = None fullName : Optional[str] = None class Config: from_attributes = True schema_extra = { "example": { "username": "johndoe", "password": "secret", "profilePic": "https://example.com/profilePic.jpg", "fullName": "John Doe" } } @router.post("/register") async def register(user: User,db=Depends(get_database)): hashed_password = pwd_context.hash(user.password) user_in_db = await db.users.find_one({"username": user.username}) if user_in_db: raise HTTPException(status_code=400, detail="Username already registered") await db.users.insert_one({"username": user.username, "password": hashed_password, "profilePic": user.profilePic, "fullName": user.fullName}) return {"username": user.username, "message": "User registered successfully","fullName": user.fullName} SECRET_KEY = "a very secret key" ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 30 async def authenticate_user(username: str, password: str,db=Depends(get_database)): user = await db.users.find_one({"username": username}) if not user: return False if not pwd_context.verify(password, user["password"]): return False return user @router.post("/login") async def login_user_with_JWT(form_data: OAuth2PasswordRequestForm = Depends(), db=Depends(get_database)): user = await authenticate_user(form_data.username, form_data.password, db) if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect username or password", headers={"WWW-Authenticate": "Bearer"}, ) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) # Assuming user["_id"] or some unique identifier exists user_id = str(user["_id"]) # Convert ObjectId to string if using MongoDB access_token = create_access_token( data={"sub": user["username"]}, user_id=user_id, expires_delta=access_token_expires ) return {"access_token": access_token} def create_access_token(data: dict,user_id: str, expires_delta: timedelta = None): to_encode = data.copy() to_encode.update({"user_id": user_id}) if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(days=30) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt async def get_current_user(token: str = Depends(oauth2_scheme), db=Depends(get_database)) -> User: credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) username: Optional[str] = payload.get("sub") if username is None: raise credentials_exception user_doc = await db.users.find_one({"username": username}) if user_doc is None: raise credentials_exception # Convert the ObjectId to a string and include it in the User instance user_id = str(user_doc["_id"]) user = User(id=user_id, **user_doc) return user except JWTError: raise credentials_exception @router.get("/users/me", response_model=User) async def read_users_me(current_user: User = Depends(get_current_user)): return current_user
import { useEffect, useState } from "react" import { BrowserRouter as Router, Routes, Route, Link, } from 'react-router-dom'; export default function List(props){ const[searchItem,setSearchitem]=useState('') function handleSearch(e){ setSearchitem(e.target.value) } function searching(){ const searchitem= props.todo.filter((items)=>items.title.toLowerCase().includes(searchItem.toLowerCase())||items.description.toLowerCase().includes(searchItem.toLowerCase())) return searchitem } const searcharray=searching() return ( <> <input value={searchItem} onChange={handleSearch} placeholder="search by title or description" style={{position:'relative',left:"85rem",top:"3rem"}}></input> <div className="tabledata"> <table border="2px"> <thead> <tr> <th>Title</th> <th>Description</th> <th>Status</th> <th>Actions</th> </tr> </thead> <tbody>{searcharray.map((items)=><tr key={items._id}> <td>{items.title}</td> <td>{items.description}</td> <td>{<><input type='checkbox' checked={items.isComplete} onChange={()=>props.checker(items._id)}></input><label>completed</label></>}</td> <td> <button style={{position:'relative',left:'1rem'}} onClick={()=>props.delete(items._id)}>Delete</button> <Link to={`/edit/${items._id}`}><button style={{position:'relative',left:'2rem'}} onClick={()=>props.editID(items._id)} >Edit</button></Link></td> </tr>)} </tbody> </table> </div> </> ) }
package org.greencloud.rulescontroller.behaviour.initiate; import static org.greencloud.commons.constants.FactTypeConstants.PROPOSAL_ACCEPT_MESSAGE; import static org.greencloud.commons.constants.FactTypeConstants.PROPOSAL_CREATE_MESSAGE; import static org.greencloud.commons.constants.FactTypeConstants.PROPOSAL_REJECT_MESSAGE; import static org.greencloud.commons.constants.FactTypeConstants.RULE_STEP; import static org.greencloud.commons.constants.FactTypeConstants.RULE_TYPE; import static org.greencloud.commons.enums.rules.RuleStepType.PROPOSAL_CREATE_STEP; import static org.greencloud.commons.enums.rules.RuleStepType.PROPOSAL_HANDLE_ACCEPT_STEP; import static org.greencloud.commons.enums.rules.RuleStepType.PROPOSAL_HANDLE_REJECT_STEP; import org.greencloud.commons.domain.facts.RuleSetFacts; import org.greencloud.commons.mapper.FactsMapper; import org.greencloud.rulescontroller.RulesController; import jade.core.Agent; import jade.lang.acl.ACLMessage; import jade.proto.ProposeInitiator; /** * Abstract behaviour providing template initiating Proposal protocol handled with rules */ public class InitiateProposal extends ProposeInitiator { protected RuleSetFacts facts; protected RulesController<?, ?> controller; protected InitiateProposal(final Agent agent, final RuleSetFacts facts, final RulesController<?, ?> controller) { super(agent, facts.get(PROPOSAL_CREATE_MESSAGE)); this.controller = controller; this.facts = facts; } /** * Method creates behaviour * * @param agent agent executing the behaviour * @param facts facts under which the Proposal message is to be created * @param ruleType type of the rule that handles Proposal execution * @param controller rules controller * @return InitiateProposal */ public static InitiateProposal create(final Agent agent, final RuleSetFacts facts, final String ruleType, final RulesController<?, ?> controller) { final RuleSetFacts methodFacts = FactsMapper.mapToRuleSetFacts(facts); methodFacts.put(RULE_TYPE, ruleType); methodFacts.put(RULE_STEP, PROPOSAL_CREATE_STEP); controller.fire(methodFacts); return new InitiateProposal(agent, methodFacts, controller); } /** * Method handles ACCEPT_PROPOSAL message retrieved from the agent. */ @Override protected void handleAcceptProposal(final ACLMessage accept) { facts.put(RULE_STEP, PROPOSAL_HANDLE_ACCEPT_STEP); facts.put(PROPOSAL_ACCEPT_MESSAGE, accept); controller.fire(facts); postProcessAcceptProposal(facts); } /** * Method handles REJECT_PROPOSAL message retrieved from the agent. */ @Override protected void handleRejectProposal(final ACLMessage reject) { facts.put(RULE_STEP, PROPOSAL_HANDLE_REJECT_STEP); facts.put(PROPOSAL_REJECT_MESSAGE, reject); controller.fire(facts); postProcessRejectProposal(facts); } /** * Method can be optionally overridden in order to perform facts-based actions after handling acceptance message */ protected void postProcessAcceptProposal(final RuleSetFacts facts) { // to be overridden if necessary } /** * Method can be optionally overridden in order to perform facts-based actions after handling rejection message */ protected void postProcessRejectProposal(final RuleSetFacts facts) { // to be overridden if necessary } }
import {Link, withRouter} from 'react-router-dom'; import S from './style.scss'; let propTypes = { userInfo: PT.object, initMyPage: PT.func }; function AuthorInfo({userInfo, initMyPage, history}){ let {avatar, user_name, user_id} = userInfo; return ( <div className={S.author_info}> <Link to="/my_page" className={S.avatar} onClick={ ev=>{ ev.stopPropagation(); ev.preventDefault(); history.push('/my_page', {userInfo}); initMyPage(user_id, {user_id}, '所有文章'); } } > <img src={avatar} alt=""/> </Link> <div className={S.title}> <span className={S.name} > {user_name} </span> </div> </div> ); } AuthorInfo.propTypes = propTypes; export default withRouter(AuthorInfo);
((Session) => { const TRX_KEY = 'trxData'; // Función para obtener los datos almacenados en localStorage const getData = (KEY) => { const data = localStorage.getItem(KEY); return data ? JSON.parse(data) : []; } // Función para guardar los datos en localStorage const setData = (data, key) => { localStorage.setItem(key, JSON.stringify(data)); } const app = { htmlElements: { btnSignUp: document.getElementById('btn-signup'), username : document.getElementById('username'), frmTransaccion: document.getElementById('transaction-form'), type: document.getElementById('type'), amount: document.getElementById('amount'), transactionTable: document.getElementById('transactions-table'), chart: document.getElementById('comparison-chart') }, transactions: [], chartInstance: null, initialize() { Session.shouldBeLoggedIn('../Login/Login.html'); app.htmlElements.btnSignUp.addEventListener('click', app.handlers.handleSignUp); app.htmlElements.frmTransaccion.addEventListener('submit', app.handlers.handleSubmit); app.render(); }, handlers: { handleSubmit(event) { event.preventDefault(); const amount = parseInt(app.htmlElements.amount.value); const type = app.htmlElements.type.value; if(!isNaN(amount)) { app.methods.addTransaction(type, amount); } }, handleSignUp(event) { event.preventDefault(); app.methods.logout(); } }, methods : { logout() { Session.logout('../Login/Login.html'); }, addTransaction(type, amount) { const trxData = getData(TRX_KEY); const currentUser = Session.getCurrentUsername(); trxData.push({currentUser, type, amount}); setData(trxData, TRX_KEY); app.render(); }, updateTable(currentUsername) { const tableBody = app.htmlElements.transactionTable; console.log(tableBody); tableBody.innerHTML = ''; const trxData = getData(TRX_KEY); trxData.forEach(transaction => { if(transaction.currentUser === currentUsername) { const row = document.createElement('tr'); row.innerHTML = ` <td>${transaction.type === 'inflow' ? 'Ingreso' : 'Gasto'}</td> <td>${transaction.amount.toFixed(2)}</td> `; tableBody.appendChild(row); } }); }, updateChart(currentUsername) { const trxData = getData(TRX_KEY); const inflow = trxData.filter(t => t.currentUser === currentUsername && t.type === 'inflow').reduce((acc, t) => acc + t.amount, 0); const outflow = trxData.filter(t => t.currentUser === currentUsername && t.type === 'outflow').reduce((acc, t) => acc + t.amount, 0); if(app.chartInstance) { app.chartInstance.data.datasets[0].data = [inflow, outflow]; app.chartInstance.update(); }else { const ctx = app.htmlElements.chart.getContext('2d'); app.chartInstance = new Chart(ctx, { type: 'pie', data: { labels: ['Ingresos', 'Gastos'], datasets: [{ label: 'My First Dataset', data: [inflow, outflow], backgroundColor: [ 'rgb(54, 162, 235)', 'rgb(255, 99, 132)', ], hoverOffset: 4 }] } }); } } }, render: () => { const currentUserString = Session.getCurrentNameOfUser(); const currentUsername = Session.getCurrentUsername(); app.htmlElements.username.innerHTML = currentUserString; app.methods.updateTable(currentUsername); app.methods.updateChart(currentUsername); } }; app.initialize(); })(window.Session);
import { IStorageData } from "./StorageData.js" const configName = "festKasse"; export let applicationConfig: IStorageData = { articles: [], screens: [], printConfig: {}, config: { currency: '€', codepage: 'cp858', header: ' 1. Mai Fest', depositText : 'Pfand' } }; let data = localStorage.getItem(configName); //data=`{"articles":[{"key":"cola","name":"Cola, Fanta, Spezi","price":200},{"key":"wasser","name":"Wasser (0.5)","price":200},{"key":"haenchen","name":"Hähnchen","price":750},{"key":"pommes","name":"Pommes","price":400}],"screens":[{"html":"<book-button article=\"wasser\" style=\"grid-column:1;grid-row:1;grid-column-start:1;grid-column-end:3;grid-row-start:1;grid-row-end:3;\"></book-button>\n<book-button article=\"wasser\" style=\"grid-column:1;grid-row:3;grid-column-start:1;grid-column-end:3;grid-row-start:3;grid-row-end:5;\"></book-button>\n<book-button article=\"haenchen\" style=\"grid-column:4;grid-row:1;grid-column-start:4;grid-column-end:6;grid-row-start:1;grid-row-end:3;\"></book-button>\n<book-button article=\"pommes\" style=\"grid-column:4;grid-row:3;grid-column-start:4;grid-column-end:6;grid-row-start:3;grid-row-end:5;\"></book-button>\n","style":"\n:host {\n box-sizing: border-box;\n display: grid;\n grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;\n grid-template-rows: 1fr 1fr 1fr 1fr 1fr 1fr 1fr 1fr;\n gap: 10px;\n padding: 10px;\n background: black;\n user-select: none;\n}\n\n* {\n font-family: 'Courier New', Courier, monospace;\n user-select: none;\n}\n\nbook-button {\n display: flex;\n justify-content: center;\n align-items: center;\n background: #222222;\n color: white;\n border: 1px solid white;\n cursor: pointer;\n}\n\naction-button {\n display: flex;\n justify-content: center;\n align-items: center;\n background: lightgray;\n color: black;\n font-weight: 900;\n border: 1px solid white;\n cursor: pointer;\n}\n\naction-button[active] {\n background: red;\n}"}],"printConfig":{},"config":{"currency":"€"}}` if (data) { const loadedConfig = JSON.parse(data); loadedConfig.config = { ...applicationConfig.config, ...loadedConfig.config }; applicationConfig = loadedConfig } export function saveConfig() { const data = JSON.stringify(applicationConfig) localStorage.setItem(configName, data); }
class Account::Balance::Calculator attr_reader :daily_balances, :errors, :warnings @daily_balances = [] @errors = [] @warnings = [] def initialize(account, options = {}) @account = account @calc_start_date = [ options[:calc_start_date], @account.effective_start_date ].compact.max end def calculate prior_balance = implied_start_balance calculated_balances = ((@calc_start_date + 1.day)...Date.current).map do |date| valuation = normalized_valuations.find { |v| v["date"] == date } if valuation current_balance = valuation["value"] else txn_flows = transaction_flows(date) current_balance = prior_balance - txn_flows end prior_balance = current_balance { date: date, balance: current_balance, currency: @account.currency, updated_at: Time.current } end @daily_balances = [ { date: @calc_start_date, balance: implied_start_balance, currency: @account.currency, updated_at: Time.current }, *calculated_balances, { date: Date.current, balance: @account.balance, currency: @account.currency, updated_at: Time.current } # Last balance must always match "source of truth" ] if @account.foreign_currency? converted_balances = convert_balances_to_family_currency @daily_balances.concat(converted_balances) end self end private def convert_balances_to_family_currency rates = ExchangeRate.get_rate_series( @account.currency, @account.family.currency, @calc_start_date..Date.current ).to_a @daily_balances.map do |balance| rate = rates.find { |rate| rate.date == balance[:date] } raise "Rate for #{@account.currency} to #{@account.family.currency} on #{balance[:date]} not found" if rate.nil? converted_balance = balance[:balance] * rate.rate { date: balance[:date], balance: converted_balance, currency: @account.family.currency, updated_at: Time.current } end end # For calculation, all transactions and valuations need to be normalized to the same currency (the account's primary currency) def normalize_entries_to_account_currency(entries, value_key) entries.map do |entry| currency = entry.currency date = entry.date value = entry.send(value_key) if currency != @account.currency rate = ExchangeRate.find_by(base_currency: currency, converted_currency: @account.currency, date: date) raise "Rate for #{currency} to #{@account.currency} not found" unless rate value *= rate.rate currency = @account.currency end entry.attributes.merge(value_key.to_s => value, "currency" => currency) end end def normalized_valuations @normalized_valuations ||= normalize_entries_to_account_currency(@account.valuations.where("date >= ?", @calc_start_date).order(:date).select(:date, :value, :currency), :value) end def normalized_transactions @normalized_transactions ||= normalize_entries_to_account_currency(@account.transactions.where("date >= ?", @calc_start_date).order(:date).select(:date, :amount, :currency), :amount) end def transaction_flows(date) flows = normalized_transactions.select { |t| t["date"] == date }.sum { |t| t["amount"] } flows *= -1 if @account.classification == "liability" flows end def implied_start_balance oldest_valuation_date = normalized_valuations.first&.dig("date") oldest_transaction_date = normalized_transactions.first&.dig("date") oldest_entry_date = [ oldest_valuation_date, oldest_transaction_date ].compact.min if oldest_entry_date == oldest_valuation_date oldest_valuation = normalized_valuations.find { |v| v["date"] == oldest_valuation_date } oldest_valuation["value"].to_d else net_transaction_flows = normalized_transactions.sum { |t| t["amount"].to_d } net_transaction_flows *= -1 if @account.classification == "liability" @account.balance.to_d + net_transaction_flows end end end
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Decoration Order Booking</title> <style> /* Add your CSS styles here */ body { font-family: Arial, sans-serif; margin: 0; padding: 0; background: linear-gradient(45deg, #6d5dff, #71ffc3); } h1 { text-align: center; color: #fff; text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2); font-size: 36px; margin: 20px 0; } form { max-width: 600px; margin: 0 auto; padding: 20px; background-color: rgba(255, 255, 255, 0.9); border-radius: 10px; box-shadow: 0px 2px 8px rgba(0, 0, 0, 0.2); transition: background-color 0.3s, box-shadow 0.3s; } form:hover { background-color: #fff; /* Change background color on hover */ box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.3); /* Add shadow on hover */ } .form-group { margin-bottom: 20px; } label { display: block; font-weight: bold; color: #333; } input[type="text"], input[type="email"], input[type="tel"], select, textarea { width: 100%; padding: 10px; margin-top: 5px; border: 1px solid #ccc; border-radius: 5px; font-size: 16px; transition: border-color 0.3s; } input[type="text"]:focus, input[type="email"]:focus, input[type="tel"]:focus, select:focus, textarea:focus { border-color: #6d5dff; /* Change border color on focus */ } button[type="submit"] { background-color: #6d5dff; color: #fff; border: none; padding: 10px 20px; border-radius: 5px; font-size: 18px; cursor: pointer; transition: background-color 0.3s; } button[type="submit"]:hover { background-color: #71ffc3; /* Change button color on hover */ } .whatsap{ background-color: #6d5dff; color: #fff; border: none; padding: 10px 20px; border-radius: 5px; font-size: 18px; cursor: pointer; transition: background-color 0.3s; } .whatsap:hover{ background-color: #71ffc3; } </style> </head> <body> <h1>Exotic Order Booking</h1> <form id="booking-form"> <div class="form-group"> <label for="orderDate">Date of Order:</label> <input type="date" id="orderDate" name="orderDate" required> </div> <div class="form-group"> <label for="email">Email:</label> <input type="email" id="email" name="email" required> </div> <div class="form-group"> <label for="mobileNumber">Mobile Number:</label> <input type="tel" id="mobileNumber" name="mobileNumber" required> </div> <div class="form-group"> <label for="fullName">Full Name:</label> <input type="text" id="fullName" name="fullName" required> </div> <div class="form-group"> <label for="eventPlace">Event Place:</label> <input type="text" id="eventPlace" name="eventPlace" required> </div> <!-- Add more fields as needed --> <div class="form-group"> <label for="eventType">Event Type:</label> <select id="eventType" name="eventType"> <option value="wedding">Wedding</option> <option value="birthday">Birthday</option> <option value="corporate">Baby Shower</option> <option value="corporate">Corporate</option> <!-- Add more event types as needed --> </select> </div> <div class="form-group"> <label for="message">Additional Message:</label> <textarea id="message" name="message" rows="4"></textarea> </div> <div class="form-group"> <a href="https://wa.link/5cbxsm" class="whatsap">submit</a> </div> </form> <script> document.addEventListener('DOMContentLoaded', function () { const form = document.getElementById('booking-form'); form.addEventListener('submit', function (e) { e.preventDefault(); // Collect form data const formData = new FormData(form); const formDataObject = {}; formData.forEach((value, key) => { formDataObject[key] = value; }); // You can now process or send the formDataObject as needed (e.g., via AJAX) // For demonstration purposes, we'll log the data to the console console.log('Form Data:', formDataObject); }); }); </script> </body> </html>
pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Role is StandardToken { using SafeMath for uint256; address public owner; address public admin; uint256 public contractDeployed = now; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event AdminshipTransferred( address indexed previousAdmin, address indexed newAdmin ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the admin. */ modifier onlyAdmin() { require(msg.sender == admin); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) external onlyOwner { _transferOwnership(_newOwner); } /** * @dev Allows the current admin to transfer control of the contract to a newAdmin. * @param _newAdmin The address to transfer adminship to. */ function transferAdminship(address _newAdmin) external onlyAdmin { _transferAdminship(_newAdmin); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); balances[owner] = balances[owner].sub(balances[owner]); balances[_newOwner] = balances[_newOwner].add(balances[owner]); owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } /** * @dev Transfers control of the contract to a newAdmin. * @param _newAdmin The address to transfer adminship to. */ function _transferAdminship(address _newAdmin) internal { require(_newAdmin != address(0)); emit AdminshipTransferred(admin, _newAdmin); admin = _newAdmin; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Role { event Pause(); event Unpause(); event NotPausable(); bool public paused = false; bool public canPause = true; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused || msg.sender == owner); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state **/ function pause() onlyOwner whenNotPaused public { require(canPause == true); paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { require(paused == true); paused = false; emit Unpause(); } /** * @dev Prevent the token from ever being paused again **/ function notPausable() onlyOwner public{ paused = false; canPause = false; emit NotPausable(); } } contract SamToken is Pausable { using SafeMath for uint; uint256 _lockedTokens; uint256 _bountyLockedTokens; uint256 _teamLockedTokens; bool ownerRelease; bool releasedForOwner ; // Team release bool team_1_release; bool teamRelease; // bounty release bool bounty_1_release; bool bountyrelase; uint256 public ownerSupply; uint256 public adminSupply ; uint256 public teamSupply ; uint256 public bountySupply ; //The name of the token string public constant name = "SAM Token"; //The token symbol string public constant symbol = "SAM"; //The precision used in the balance calculations in contract uint public constant decimals = 0; event Burn(address indexed burner, uint256 value); event CompanyTokenReleased( address indexed _company, uint256 indexed _tokens ); event TransferTokenToTeam( address indexed _beneficiary, uint256 indexed tokens ); event TransferTokenToBounty( address indexed bounty, uint256 indexed tokens ); constructor( address _owner, address _admin, uint256 _totalsupply, address _development, address _bounty ) public { owner = _owner; admin = _admin; _totalsupply = _totalsupply; totalSupply_ = totalSupply_.add(_totalsupply); adminSupply = 450000000; teamSupply = 200000000; ownerSupply = 100000000; bountySupply = 50000000; _lockedTokens = _lockedTokens.add(ownerSupply); _bountyLockedTokens = _bountyLockedTokens.add(bountySupply); _teamLockedTokens = _teamLockedTokens.add(teamSupply); balances[admin] = balances[admin].add(adminSupply); balances[_development] = balances[_development].add(150000000); balances[_bounty] = balances[_bounty].add(50000000); emit Transfer(address(0), admin, adminSupply); } modifier onlyPayloadSize(uint numWords) { assert(msg.data.length >= numWords * 32 + 4); _; } /** * @dev Locked number of tokens in existence */ function lockedTokens() public view returns (uint256) { return _lockedTokens; } /** * @dev Locked number of tokens for bounty in existence */ function lockedBountyTokens() public view returns (uint256) { return _bountyLockedTokens; } /** * @dev Locked number of tokens for team in existence */ function lockedTeamTokens() public view returns (uint256) { return _teamLockedTokens; } /** * @dev function to check whether passed address is a contract address */ function isContract(address _address) private view returns (bool is_contract) { uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_address) } return (length > 0); } /** * @dev Gets the balance of the specified address. * @param tokenOwner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param tokenOwner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param tokens The amount to be transferred. */ function transfer(address to, uint tokens) public whenNotPaused onlyPayloadSize(2) returns (bool success) { require(to != address(0)); require(tokens > 0); require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param tokens The amount of tokens to be spent. */ function approve(address spender, uint tokens) public whenNotPaused onlyPayloadSize(2) returns (bool success) { require(spender != address(0)); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param tokens uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint tokens) public whenNotPaused onlyPayloadSize(3) returns (bool success) { require(tokens > 0); require(from != address(0)); require(to != address(0)); require(allowed[from][msg.sender] > 0); require(balances[from]>0); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(msg.sender, _value); return true; } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address from, uint _value) public returns (bool success) { require(balances[from] >= _value); require(_value <= allowed[from][msg.sender]); balances[from] = balances[from].sub(_value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(from, _value); return true; } function () public payable { revert(); } /** * @dev Function to transfer any ERC20 token to owner address which gets accidentally transferred to this contract * @param tokenAddress The address of the ERC20 contract * @param tokens The amount of tokens to transfer. * @return A boolean that indicates if the operation was successful. */ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { require(tokenAddress != address(0)); require(isContract(tokenAddress)); return ERC20(tokenAddress).transfer(owner, tokens); } /** * @dev Function to Release Company token to owner address after Locking period is over * @param _company The address of the owner * @return A boolean that indicates if the operation was successful. */ // Transfer token to compnay function companyTokensRelease(address _company) external onlyOwner returns(bool) { require(_company != address(0), "Address is not valid"); require(!ownerRelease, "owner release has already done"); if (now > contractDeployed.add(365 days) && releasedForOwner == false ) { balances[_company] = balances[_company].add(_lockedTokens); releasedForOwner = true; ownerRelease = true; emit CompanyTokenReleased(_company, _lockedTokens); _lockedTokens = 0; return true; } } /** * @dev Function to Release Team token to team address after Locking period is over * @param _team The address of the team * @return A boolean that indicates if the operation was successful. */ // Transfer token to team function transferToTeam(address _team) external onlyOwner returns(bool) { require(_team != address(0), "Address is not valid"); require(!teamRelease, "Team release has already done"); if (now > contractDeployed.add(365 days) && team_1_release == false) { balances[_team] = balances[_team].add(_teamLockedTokens); team_1_release = true; teamRelease = true; emit TransferTokenToTeam(_team, _teamLockedTokens); _teamLockedTokens = 0; return true; } } /** * @dev Function to Release Bounty and Bonus token to Bounty address after Locking period is over * @param _bounty The address of the Bounty * @return A boolean that indicates if the operation was successful. */ function transferToBounty(address _bounty) external onlyOwner returns(bool) { require(_bounty != address(0), "Address is not valid"); require(!bountyrelase, "Bounty release already done"); if (now > contractDeployed.add(180 days) && bounty_1_release == false) { balances[_bounty] = balances[_bounty].add(_bountyLockedTokens); bounty_1_release = true; bountyrelase = true; emit TransferTokenToBounty(_bounty, _bountyLockedTokens); _bountyLockedTokens = 0; return true; } } }
// 抽象关键字 abstract // 抽象类不能被实例化 abstract class Geom { getType() { return "Geom"; } // abstract 定义抽象方法,不能写实现,只能定义它的类型 // 抽象方法必须在抽象类里面 abstract getArea(): number; } // 抽象类只能被继承,且继承了之后必须要实现抽象类里的抽象方法 class Circle extends Geom { getArea(): number { return 123; } }
import { CreateContactInput } from './create-contact.input'; import { InputType, Field, Int, PartialType } from '@nestjs/graphql'; import { Optional } from '@nestjs/common'; @InputType() export class UpdateContactInput extends PartialType(CreateContactInput) { @Field(() => Int) id: number; @Field() firstName: string; @Field() lastName: string; @Field(() => String, { defaultValue: 'no nickName' }) nickName: string; @Field() address: string; @Field((type) => [String], { defaultValue: [] }) // nullable: false makes no difference at all phoneNumbers: string[]; @Field(() => String, { defaultValue: 'no picture' }) photo: string; }
--- import MobileMenu from "@components/navigation/MobileMenu.astro"; import NavLink from "@components/navigation/NavLink.astro"; import DropDown from "@components/navigation/DropDown.astro"; import { NAV_LINKS } from "@consts"; import { isNavLinkActive } from "@lib/utils"; import type { Link } from "@types"; import { Icon } from "astro-icon"; const pathname = new URL(Astro.request.url).pathname; const currentPath = pathname.slice(1); // remove the first "/" --- <header class="z-10 items-center grid-in-header bg-branding-gray dark:bg-branding-neutral-800" x-data="{mobileOpen: false}"> <div class="flex h-[52px] 2xl:h-[62px]"> <button type="button" aria-label="Toggle Mobile Sidebar" class="h-full p-3 duration-75 hover:backdrop-brightness-75 inline-flex place-items-center dark:hover:backdrop-brightness-125 lg:hidden" @click="sidebarOpen = !sidebarOpen"> <Icon name="heroicons/bars-3-bottom-left-20-solid" class="w-5 h-5 transition duration-150 text-branding-black dark:text-branding-white" :class="{'rotate-90': sidebarOpen === true}" focusable="false" aria-hidden="true" /> <span class="sr-only">Toggle Mobile Sidebar</span> </button> <nav class="h-full"> <ul class="hidden lg:flex h-full items-center space-x-4"> { NAV_LINKS.map((link: Link) => { if (link.children) { let url = link.children[0].href.split("/")[1]; return ( <DropDown name={link.name} active={isNavLinkActive(url, currentPath.split("/")[0])} children={link.children} /> ); } else { let url = link.href.split("/")[1]; return ( <NavLink name={link.name} href={link.href} active={isNavLinkActive(url, currentPath.split("/")[0])} /> ); } }) } </ul> </nav> <div class="flex items-center h-full my-auto space-x-4 ml-auto"> <button type="button" class="h-full p-3 duration-75 hover:backdrop-brightness-75 inline-flex place-items-center dark:hover:backdrop-brightness-125" aria-label="Toggle Dark Mode" @click="darkMode = !darkMode"> <Icon name="heroicons/sun-solid" class="text-branding-white hidden dark:inline-block w-5 h-5" focusable="false" aria-hidden="true" /> <Icon name="heroicons/moon-solid" class="text-branding-black dark:hidden inline-block w-5 h-5" focusable="false" aria-hidden="true" /> </button> <button type="button" aria-label="Toggle mobile menu" class="h-full p-3 hover:backdrop-brightness-75 dark:hover:backdrop-brightness-125 duration-150 lg:hidden text-branding-black dark:text-branding-white" x-on:click="mobileOpen = !mobileOpen"> <Icon name="heroicons/bars-3-bottom-right-20-solid" class="h-5 w-5" aria-hidden="true" focusable="false" /> </button> </div> </div> <MobileMenu /> </header>
--- title: PC端和移动端交互事件 layout: doc --- # PC端和移动端交互事件 <el-divider /> <div style='display: flex;gap: 10px;'> <el-tag>javascript</el-tag> </div> ## 鼠标事件 ### 鼠标左键单击 ```javascript click() { console.log('鼠标左键点击 ') }, ``` ### 鼠标右键单击 ```javascript contextmenu() { console.log('鼠标右键点击 ') }, ``` ### 鼠标左键双击点击 ```javascript dblclick() { console.log('鼠标左键双击点击 ') }, ``` ### 鼠标按下 ```javascript mousedown() { console.log('鼠标按下') }, ``` ### 鼠标释放 ```javascript mouseup() { console.log('鼠标释放') }, ``` ### 鼠标移动 ```javascript mousemove() { console.log('鼠标移动') }, ``` ### 鼠标移入 ```javascript mouseover() { console.log('鼠标移入') }, ``` ### 鼠标移出 ```javascript mouseout() { console.log('鼠标移出') }, ``` ### 鼠标进入(在元素内移动时触发,不会冒泡) ```javascript mouseenter() { console.log('鼠标进入(在元素内移动时触发,不会冒泡)') }, ``` ### 鼠标离开(从元素内移出时触发,不会冒泡) ```javascript mouseleave() { console.log('鼠标离开(从元素内移出时触发,不会冒泡)') }, ``` ### 鼠标滚轮滚动 ```javascript wheel() { console.log('鼠标滚轮滚动') }, ``` ## 键盘事件 ### 键盘按键按下 ```javascript keydown() { console.log('键盘按键按下') }, ``` ### 键盘按键释放 ```javascript keyup() { console.log('键盘按键释放') }, ``` ### 键盘按键输入 ```javascript keypress() { console.log('键盘按键输入') }, ``` ## 触摸事件 ### 触摸开始 ```javascript touchstart() { console.log('触摸开始') }, ``` ### 触摸结束 ```javascript touchend() { console.log('触摸结束') }, ``` ### 触摸移动 ```javascript touchmove() { console.log('触摸移动') }, ``` ### 触摸取消 ```javascript touchcancel() { console.log('触摸取消') }, ``` ## 拖放事件 ### 拖动开始 ```javascript dragstart() { console.log('拖动开始') }, ``` ### 拖动结束 ```javascript dragend() { console.log('拖动结束') }, ``` ### 在可拖动元素上方拖动时触发 ```javascript dragover() { console.log('在可拖动元素上方拖动时触发') }, ``` ### 拖动进入目标区域 ```javascript dragenter() { console.log('拖动进入目标区域') }, ``` ### 拖动离开目标区域 ```javascript dragleave() { console.log('拖动离开目标区域') }, ``` ### 完成拖放操作 ```javascript drop() { console.log('完成拖放操作') }, ``` ## 窗口事件 ### 窗口大小改变 ```javascript resize() { console.log('窗口大小改变') }, ``` ### 滚动条滚动 ```javascript scroll() { console.log('滚动条滚动') }, ```
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Exercise:22</title> </head> <body> <script> // More Conditional Tests: You don’t have to limit the number of tests you create to 10. // If you want to try more comparisons, write more tests. // Have at least one True and one False result for each of the following: // • Tests for equality and inequality with strings // • Tests using the lower case function // • Numerical tests involving equality and inequality, greater than and less than, // greater than or equal to, and less than or equal to // • Tests using "and" and "or" operators // • Test whether an item is in a array // • Test whether an item is not in a array let name = "rauf"; let age = 26; let gender = "MALE"; let strArr = ["english", "french", "urdu", "hindi", "persian"]; let numArr = [23, 54, 1, 9, 78, 3]; console.log("Test# 1 : gender should be equal to male, it will evalute to true"); if (gender === "MALE") { console.log("true, he is male"); } console.log("Test# 2 : gender should not be equal to male, it will evalute to false"); if (gender !== "MALE") { console.log("false, he is male"); } console.log("Test# 3 : gender should be equal to male, it will evalute to true"); if (gender.toLowerCase() === "male") { console.log("true, he is male"); } console.log("Test# 4 : gender should not be equal to male, it will evalute to false"); if (gender.toLowerCase() !== "male") { console.log("false, he is male"); } console.log("Test#5 : age should be less than 30, it will evalute to true "); if (age < 30) { console.log("age is less than 30"); } console.log("Test#6 : age should be greater than 18, it will evalute to true"); if (age > 18) { console.log("true, age is greater than 18 "); } console.log("Test#7 : name should not be empty string, it will evalute to true"); if (name != "") { console.log("true, name is not empty string"); } console.log("Test#8 : name should have more than 3 characters, it will evalute to true"); if (name.length >= 3) { console.log("true, name has more than 3 characters"); } console.log("Test#8 : age should not be equal to 26, it will evalute to false "); if (age !== 26) { console.log("false, it's not going to print"); } console.log("Test#9 : age should be equal to 26, it will evalute to true"); if (age === 26) { console.log("true, age is 26"); } console.log( "Test#10 : age should be less or equal to 30 and greater than or equal to 18, it will evalute to true " ); if (age >= 18 && age <= 30) { console.log("true, under range"); } console.log("Test#11 : age should be greater than or equal to 18, it will evalute to true "); if (age >= 18 && name.length > 3) { console.log("true, name and age are in range"); } console.log("Test#12 : gender should be equal to male or female, it will evalute to true "); if (gender === "MALE" || gender === "FEMALE") { console.log("true, under range"); } console.log("Test#13 : is string urdu in the array, it will evalute to true "); if (strArr.includes("urdu")) { console.log("true, urdu is in the array"); } console.log("Test#13 : is string arabic in the array, it will evalute to false "); if (strArr.includes("arabic")) { console.log("false, arabic is in the array"); } console.log("Test#14 : is number 9 in the array, it will evalute to true "); if (numArr.includes(9)) { console.log("true, number 9 is in the array"); } console.log("Test#15 : is number 15 in the array, it will evalute to false"); if (numArr.includes(15)) { console.log("false, number 15 is not in the array"); } </script> </body> </html>
// // File.swift // // // Created by R. Kukuh on 27/03/23. // import XCTest @testable import SwiftCollections class ArrayCollapseTests: XCTestCase { func testCollapseIntArray() { let nestedArray: [[Int]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] let collapsedArray = nestedArray.collapse() XCTAssertEqual(collapsedArray, [1, 2, 3, 4, 5, 6, 7, 8, 9], "The collapsed array should match the expected array.") } func testCollapseMixedArray() { let mixedNestedArray: [[Any]] = [["A", "B"], [1, 2, 3], ["C", "D"]] let mixedCollapsedArray = mixedNestedArray.collapse() XCTAssertEqual(mixedCollapsedArray.count, 7, "The count of the collapsed array should be 7.") XCTAssertTrue(mixedCollapsedArray.contains { $0 as? String == "A" }, "The collapsed array should contain \"A\".") XCTAssertTrue(mixedCollapsedArray.contains { $0 as? Int == 1 }, "The collapsed array should contain 1.") } }
# -*- coding: utf-8 -*- # Copyright IRT Antoine de Saint Exupéry et Université Paul Sabatier Toulouse III - All # rights reserved. DEEL is a research program operated by IVADO, IRT Saint Exupéry, # CRIAQ and ANITI - https://www.deel.ai/ # # 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. import os import numpy as np import pandas as pd import tensorflow as tf from absl import app from ml_collections import config_dict from ml_collections import config_flags import wandb from deel.lipdp.dynamic import AdaptiveQuantileClipping from deel.lipdp.layers import DP_AddBias from deel.lipdp.layers import DP_BoundedInput from deel.lipdp.layers import DP_ClipGradient from deel.lipdp.layers import DP_Flatten from deel.lipdp.layers import DP_GroupSort from deel.lipdp.layers import DP_LayerCentering from deel.lipdp.layers import DP_ScaledL2NormPooling2D from deel.lipdp.layers import DP_SpectralConv2D from deel.lipdp.layers import DP_SpectralDense from deel.lipdp.losses import * from deel.lipdp.model import DP_Accountant from deel.lipdp.model import DP_Sequential from deel.lipdp.model import DPParameters from deel.lipdp.pipeline import bound_normalize from deel.lipdp.pipeline import default_delta_value from deel.lipdp.pipeline import load_and_prepare_images_data from deel.lipdp.sensitivity import get_max_epochs from experiments.wandb_utils import init_wandb from experiments.wandb_utils import run_with_wandb from wandb.keras import WandbCallback def default_cfg_mnist(): cfg = config_dict.ConfigDict() cfg.add_biases = True cfg.batch_size = 2_000 cfg.clip_loss_gradient = None # not required for dynamic clipping. cfg.dynamic_clipping = "quantiles" # can be "fixed", "laplace", "quantiles". "fixed" requires a clipping value. cfg.dynamic_clipping_quantiles = ( 0.9 # crop to 90% of the distribution of gradient norm. ) cfg.epsilon_max = 3.0 cfg.input_clipping = 0.7 cfg.learning_rate = 5e-3 cfg.loss = "TauCategoricalCrossentropy" cfg.log_wandb = "disabled" cfg.noise_multiplier = 1.5 cfg.noisify_strategy = "per-layer" cfg.optimizer = "Adam" cfg.opt_iterations = None cfg.save = False cfg.save_folder = os.getcwd() cfg.sweep_yaml_config = "" cfg.sweep_id = "" cfg.tau = 32.0 return cfg cfg = default_cfg_mnist() _CONFIG = config_flags.DEFINE_config_dict("cfg", cfg) def create_ConvNet(dp_parameters, dataset_metadata): norm_max = 1.0 all_layers = [ DP_BoundedInput(input_shape=(28, 28, 1), upper_bound=dataset_metadata.max_norm), DP_SpectralConv2D( filters=16, kernel_size=3, kernel_initializer="orthogonal", strides=1, use_bias=False, ), DP_AddBias(norm_max=norm_max), DP_GroupSort(2), DP_ScaledL2NormPooling2D(pool_size=2, strides=2), DP_LayerCentering(), DP_SpectralConv2D( filters=32, kernel_size=3, kernel_initializer="orthogonal", strides=1, use_bias=False, ), DP_AddBias(norm_max=norm_max), DP_GroupSort(2), DP_ScaledL2NormPooling2D(pool_size=2, strides=2), DP_LayerCentering(), DP_Flatten(), DP_SpectralDense(1024, use_bias=False, kernel_initializer="orthogonal"), DP_AddBias(norm_max=norm_max), DP_SpectralDense(10, use_bias=False, kernel_initializer="orthogonal"), DP_AddBias(norm_max=norm_max), DP_ClipGradient( clip_value=cfg.clip_loss_gradient, mode="dynamic", ), ] if not cfg.add_biases: all_layers = [ layer for layer in all_layers if not isinstance(layer, DP_AddBias) ] model = DP_Sequential( all_layers, dp_parameters=dp_parameters, dataset_metadata=dataset_metadata, ) return model def compile_model(model, cfg): # Choice of optimizer if cfg.optimizer == "SGD": optimizer = tf.keras.optimizers.SGD(learning_rate=cfg.learning_rate) elif cfg.optimizer == "Adam": optimizer = tf.keras.optimizers.Adam(learning_rate=cfg.learning_rate) else: print("Illegal optimizer argument : ", cfg.optimizer) # Choice of loss function if cfg.loss == "MulticlassHKR": if cfg.optimizer == "SGD": cfg.learning_rate = cfg.learning_rate / cfg.alpha loss = DP_MulticlassHKR( alpha=50.0, min_margin=0.5, reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE, ) elif cfg.loss == "MulticlassHinge": loss = DP_MulticlassHinge( min_margin=0.5, reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE, ) elif cfg.loss == "MulticlassKR": loss = DP_MulticlassKR(reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE) elif cfg.loss == "TauCategoricalCrossentropy": loss = DP_TauCategoricalCrossentropy( cfg.tau, reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE ) elif cfg.loss == "KCosineSimilarity": loss = DP_KCosineSimilarity( 0.99, reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE ) elif cfg.loss == "MAE": loss = DP_MeanAbsoluteError( reduction=tf.keras.losses.Reduction.SUM_OVER_BATCH_SIZE ) else: raise ValueError(f"Illegal loss argument {cfg.loss}") # Compile model model.compile( # decreasing alpha and increasing min_margin improve robustness (at the cost of accuracy) # note also in the case of lipschitz networks, more robustness require more parameters. loss=loss, optimizer=optimizer, metrics=["accuracy"], ) return model def train(): init_wandb(cfg=cfg, project="MNIST_ClipLess_SGD") ds_train, ds_test, dataset_metadata = load_and_prepare_images_data( "mnist", cfg.batch_size, colorspace="grayscale", drop_remainder=True, bound_fct=bound_normalize(), ) model = create_ConvNet( DPParameters( noisify_strategy=cfg.noisify_strategy, noise_multiplier=cfg.noise_multiplier, delta=default_delta_value(dataset_metadata), ), dataset_metadata, ) model = compile_model(model, cfg) model.summary() num_epochs = get_max_epochs(cfg.epsilon_max, model) adaptive = AdaptiveQuantileClipping( ds_train=ds_train, patience=1, noise_multiplier=cfg.noise_multiplier * 5, # more noisy. quantile=cfg.dynamic_clipping_quantiles, learning_rate=1.0, ) adaptive.set_model(model) callbacks = [ WandbCallback(save_model=False, monitor="val_accuracy"), DP_Accountant(), adaptive, ] hist = model.fit( ds_train, epochs=num_epochs, validation_data=ds_test, batch_size=cfg.batch_size, callbacks=callbacks, ) def main(_): run_with_wandb(cfg=cfg, train_function=train, project="ICLR_MNIST_acc") if __name__ == "__main__": app.run(main)
// @ts-nocheck /* * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import BatteryInfo from "@ohos.batteryInfo"; import commonEvent from "@ohos.commonEvent"; import createOrGet from "../../../../../../common/src/main/ets/default/SingleInstanceHelper"; import Constants from "./common/constants"; import Log from "../../../../../../common/src/main/ets/default/Log"; import { CommonEventData } from "commonEvent/commonEventData"; import { CommonEventManager, getCommonEventManager, POLICY, } from "../../../../../../common/src/main/ets/default/commonEvent/CommonEventManager"; const TAG = "BatteryComponent-batteryModelSc"; const DEFAULT_PROGRESS = 100; const SUBSCRIBE_INFO = { events: [commonEvent.Support.COMMON_EVENT_BATTERY_CHANGED], }; function getChargingStatus(state: typeof BatteryInfo.BatteryChargeState): boolean { Log.showDebug(TAG, `charging status update: ${state}`); let batteryStatus = false; switch (state) { case BatteryInfo.BatteryChargeState.DISABLE: case BatteryInfo.BatteryChargeState.ENABLE: case BatteryInfo.BatteryChargeState.FULL: batteryStatus = true; break; default: batteryStatus = false; break; } return batteryStatus; } export class BatteryModel { private mBatterySoc: any; private mBatteryCharging: any; private mManager?: CommonEventManager; initBatteryModel() { if (this.mManager) { return; } this.mManager = getCommonEventManager( TAG, SUBSCRIBE_INFO, () => this.updateBatteryStatus(), (isSubscribe: boolean) => isSubscribe && this.updateBatteryStatus() ); Log.showDebug(TAG, "initBatteryModel"); this.mBatterySoc = AppStorage.SetAndLink("batterySoc", 0); this.mBatteryCharging = AppStorage.SetAndLink("batteryCharging", false); this.mManager.subscriberCommonEvent(); this.mManager.applyPolicy([POLICY.SCREEN_POLICY]); } unInitBatteryModel() { Log.showDebug(TAG, "unInitBatteryModel"); this.mManager?.release(); this.mManager = undefined; } /** * Get battery status and remaining power */ private updateBatteryStatus() { Log.showDebug(TAG, "updateBatteryStatus"); let batterySoc = BatteryInfo.batterySOC ?? DEFAULT_PROGRESS; let batteryCharging = BatteryInfo.chargingStatus; if (batterySoc <= 0) { // If the result is a negative number, set it as positive number. batterySoc = Math.abs(batterySoc) * Constants.PERCENT_NUMBER; } Log.showInfo(TAG, "batterySoc = " + batterySoc); // Set the battery status as charging when there is no battery hardware this.mBatterySoc.set(batterySoc); this.mBatteryCharging.set(getChargingStatus(batteryCharging)); } } let mBatteryModel = createOrGet(BatteryModel, TAG); export default mBatteryModel as BatteryModel;
import uuid from django.db import models from django.utils.html import mark_safe from django.contrib.auth.models import User from apps.core.model_tools import AvatarField, IntegerRangeField from .validators import ( validate_phone_number, normalize_phone, validate_address ) from apps.core.media_tools import OverwriteCodedStorage from apps.core.model_tools import SvgField, NamedImageField import apps.shop.model_funcs as model_funcs class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.CharField(max_length=64, validators=[validate_phone_number], help_text="Enter a phone in format +375 (29) XXX-XX-XX") address = models.CharField(max_length=64, validators=[validate_address]) avatar = AvatarField(upload_to='profile_avatars', default='profile_avatars/avatar_default.jpg', blank=True, get_color=model_funcs.get_profile_avatar_color, avatar_size=300, get_filename=model_funcs.get_profile_avatar_filename) coupons = models.ManyToManyField('Coupon', help_text="Select a coupon for this user", blank=True, related_name='users') def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): if self.phone: self.phone = normalize_phone(self.phone) super().save(*args, **kwargs) def delete(self, using=None, keep_parents=False): self.avatar.delete(save=False) super().delete(using=using, keep_parents=keep_parents) def get_avatar_as_html_image(self, size): return mark_safe(f'<img src = "{self.avatar.url}" width="{size}" />') class Meta: verbose_name = "profile" verbose_name_plural = "profiles" class Provider(User): pass class Category(models.Model): name = models.CharField(max_length=64, unique=True, help_text="Enter a category (e.g. Oil, Tire etc.)") image_key = models.UUIDField(default=uuid.uuid4, editable=False) logo = SvgField(upload_to='categories_logo', default='categories_logo/logo_default.svg', get_filename=model_funcs.get_category_logo_filename, storage=OverwriteCodedStorage()) image = NamedImageField(upload_to='categories_images', default='categories_images/image_default.png', get_filename=model_funcs.get_category_image_filename, storage=OverwriteCodedStorage()) def delete(self, using=None, keep_parents=False): if self.logo != self.logo.field.default: self.logo.delete(save=False) if self.image != self.image.field.default: self.image.delete(save=False) super().delete(using=using, keep_parents=keep_parents) def __str__(self): return self.name def get_absolute_url(self): return f'/category/{self.id}/' def get_logo_as_html_image(self, *, height, width=None): return mark_safe(f'<img src="{self.logo.url}" height="{height}" {f"width={width}" if width else ""} />') def get_image_as_html_image(self, *, height, width=None): return mark_safe(f'<img src="{self.image.url}" height="{height}" {f"width={width}" if width else ""} />') class Meta: verbose_name = "category" verbose_name_plural = "categories" ordering = ("name",) class Product(models.Model): name = models.CharField(max_length=64, unique=True) category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL) article = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, help_text="Unique ID for this product") price = IntegerRangeField(min_value=0) providers = models.ManyToManyField(Provider, help_text="Select a provider for this product", blank=True, related_name='products') image_key = models.UUIDField(default=uuid.uuid4, editable=False) image = NamedImageField(upload_to='products_images', get_filename=model_funcs.get_product_image_filename, storage=OverwriteCodedStorage()) def get_absolute_url(self): return f"/product/{self.article}/" def get_few_providers(self): max_count = 3 providers = self.providers.all() if len(providers) > max_count: # We cut one less to replace more than one provider. return ', '.join([provider.username for provider in providers[:max_count - 1]]) + " and others" else: return ', '.join([provider.username for provider in providers]) get_few_providers.short_description = 'Providers' def __str__(self): return self.name def get_image_as_html_image(self, *, height, width=None): return mark_safe(f'<img src="{self.image.url}" height="{height}" {f"width={width}" if width else ""} />') class Meta: verbose_name = "product" verbose_name_plural = "products" ordering = ("name",) class Buy(models.Model): date = models.DateField(auto_now_add=True, editable=False) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) product = models.ForeignKey('Product', null=True, on_delete=models.CASCADE) count = IntegerRangeField(min_value=1) card_num = IntegerRangeField(min_value=0, max_value=1000000) def __str__(self): return f"Buy {self.product.name} x{self.count} by {self.user}" def get_absolute_url(self): return f'buy/{self.id}/' class Meta: verbose_name = "buy" verbose_name_plural = "buys" ordering = ("-date", "product", 'user', "count") class Coupon(models.Model): discount = IntegerRangeField(min_value=1, max_value=100) def __str__(self): return f"-{self.discount} %" def get_absolute_url(self): return f"/coupon/{self.id}/" class Review(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) content = models.TextField() product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): # The first 3 words are taken and if their length exceeds 15 then a words are slice. return (' '.join(str(self.content).split()[:3]))[:15] + '...' class Meta: verbose_name = "review" verbose_name_plural = "reviews" class News(models.Model): title = models.CharField(max_length=64, blank=True) content = models.TextField() class Meta: verbose_name = "news" verbose_name_plural = "news" def __str__(self): return self.title def get_absolute_url(self): return f"/news/{self.id}/" class Faq(models.Model): date = models.DateTimeField(auto_now_add=True, editable=False) title = models.CharField(max_length=64, blank=True) content = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return f"/faq/{self.id}/" class CarouselItem(models.Model): image_key = models.UUIDField(default=uuid.uuid4, editable=False) image = NamedImageField(upload_to='carousel_items_images', get_filename=model_funcs.get_carousel_item_image_filename, storage=OverwriteCodedStorage()) content = models.TextField(default=""" <div style="text-align: center;color: #f2f2f2;font-size: 15px;"> <h1 style='margin-bottom:100px; font: 62.5% "Roboto","Arial","Helvetica",sans-serif; font-size: 5em; font-weight: 700;'> CREATE </h1> <h3 style='font: 62.5% "Roboto","Arial","Helvetica",sans-serif; font-size: 1.9em;'> Our workers are the best </h3> </div> """.replace('\n ', '\n').replace('\n', '', 1)) def __str__(self): return (' '.join(str(self.content).split()[:3]))[:15] + '...' def get_image_as_html_image(self, *, height, width=None): return mark_safe(f'<img src="{self.image.url}" height="{height}" {f"width={width}" if width else ""} />') def delete(self, using=None, keep_parents=False): self.image.delete(save=False) super().delete(using=using, keep_parents=keep_parents)
using System.ComponentModel.DataAnnotations; namespace TraderEngine.Common.DTOs.API.Request; /// <summary> /// Market, pair of quote currency and base currency. /// </summary> public class MarketReqDto : IEquatable<MarketReqDto> { /// <summary> /// The quote currency to value <see cref="BaseSymbol"/> against. /// </summary> [Required] public string QuoteSymbol { get; set; } = null!; /// <summary> /// The base currency valued by <see cref="QuoteSymbol"/>. /// </summary> [Required] public string BaseSymbol { get; set; } = null!; public MarketReqDto() { } /// <param name="quoteSymbol"><inheritdoc cref="QuoteSymbol"/></param> /// <param name="baseSymbol"><inheritdoc cref="BaseSymbol"/></param> public MarketReqDto(string quoteSymbol, string baseSymbol) { QuoteSymbol = quoteSymbol.ToUpper(); BaseSymbol = baseSymbol.ToUpper(); } public override bool Equals(object? obj) => Equals(obj as MarketReqDto); public bool Equals(MarketReqDto? obj) => obj is not null && QuoteSymbol.Equals(obj.QuoteSymbol, StringComparison.OrdinalIgnoreCase) && BaseSymbol.Equals(obj.BaseSymbol, StringComparison.OrdinalIgnoreCase); public override int GetHashCode() => $"{QuoteSymbol.ToUpper()}{BaseSymbol.ToUpper()}".GetHashCode(); public static bool operator ==(MarketReqDto a, MarketReqDto b) => a.Equals(b); public static bool operator !=(MarketReqDto a, MarketReqDto b) => !a.Equals(b); }
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/dist/query/react"; import { ICoupon } from "../interface/coupons"; const couponApi = createApi({ reducerPath: "coupons", tagTypes: ["Coupons"], baseQuery: fetchBaseQuery({ baseUrl: import.meta.env.VITE_API_URL, prepareHeaders: (headers) => { const token = JSON.parse(localStorage.getItem("accessToken")!); try { headers.set("Authorization", `Bearer ${token}`); } catch (error) { console.error("Invalid token:", token); } return headers; }, }), endpoints: (builder) => ({ addCoupon: builder.mutation<ICoupon, ICoupon>({ query: (data) => ({ url: "/coupons", method: "POST", body: data, }), invalidatesTags: ["Coupons"], }), applyCoupon: builder.mutation<ICoupon, void>({ query: (data) => ({ url: "/coupons/apply", method: "POST", body: data, }), invalidatesTags: ["Coupons"], }), getCouponsAdmin: builder.query<ICoupon, void>({ query: () => `/coupons`, providesTags: ["Coupons"], }), getCouponsAllUsers: builder.query<ICoupon, void>({ query: () => `/get-coupon-all-users`, providesTags: ["Coupons"], }), getCouponsByUsers: builder.query<ICoupon, string>({ query: (data) => `/coupons/users/${data}`, providesTags: ["Coupons"], }), removeCoupon: builder.mutation<ICoupon, ICoupon>({ query: (id) => ({ url: `/coupons/${id}`, method: "DELETE", }), invalidatesTags: ["Coupons"], }), getByIdCoupon: builder.query<ICoupon, string>({ query: (id) => ({ url: `/coupons/${id}`, method: "GET", }), providesTags: ["Coupons"], }), getByUserCoupon: builder.query<ICoupon, string | number>({ query: (id) => ({ url: `/coupons/userApply/${id}`, method: "GET", }), providesTags: ["Coupons"], }), updateCoupon: builder.mutation<ICoupon, ICoupon>({ query: (data) => { const { _id, ...body } = data; return { url: `/coupons/${_id as string}`, method: "PUT", body, }; }, invalidatesTags: ["Coupons"], }), patchCoupon: builder.mutation<ICoupon, ICoupon>({ query: (data) => { const { _id, ...body } = data; return { url: `/coupon/patch/${_id as string}`, method: "PATCH", body, }; }, invalidatesTags: ["Coupons"], }), }), }); export const { useGetCouponsAdminQuery, useGetCouponsAllUsersQuery, useGetCouponsByUsersQuery, usePatchCouponMutation, useAddCouponMutation, useApplyCouponMutation, useGetByIdCouponQuery, useGetByUserCouponQuery, useRemoveCouponMutation, useUpdateCouponMutation, } = couponApi; export const couponReducer = couponApi.reducer; export default couponApi;
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {SafeERC20} from "./SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @notice Inherit this to allow for rescuing ERC20 tokens sent to the contract in error. */ abstract contract Rescuable { using SafeERC20 for IERC20; /** @notice Rescues ERC20 tokens sent to the contract in error. @dev Need to implement {_authorizeRescue} to do access-control for this function. @param token The ERC20 token to rescue @param target The address to send the tokens to */ function rescue(address token, address target) external virtual { // make sure we're not stealing funds or something _authorizeRescue(token, target); // transfer token to target IERC20 tokenContract = IERC20(token); tokenContract.safeTransfer( target, tokenContract.balanceOf(address(this)) ); } /** @dev IMPORTANT MUST READ IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY MAKE SURE YOU DO ALL OF THE FOLLOWING 1) You MUST revert during a call to this function if the token rescue should be stopped. 2) You MUST implement proper access control to prevent stealing funds. 3) You MUST revert if `token` is a token your contract holds as user funds. @param token The ERC20 token to rescue @param target The address to send the tokens to */ function _authorizeRescue(address token, address target) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** @dev Modified from openzeppelin. Instead of reverting when the allowance is non-zero, we first set the allowance to 0 and then call approve(spender, currentAllowance + value). This provides support for non-standard tokens such as USDT that revert in this scenario. */ function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance > 0) { _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, 0) ); } _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, currentAllowance + value ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {Rescuable} from "../libs/Rescuable.sol"; // Interface for money market protocols (Compound, Aave, etc.) abstract contract MoneyMarket is Rescuable, OwnableUpgradeable, AccessControlUpgradeable { bytes32 internal constant RESCUER_ROLE = keccak256("RESCUER_ROLE"); function __MoneyMarket_init(address rescuer) internal initializer { __Ownable_init(); __AccessControl_init(); // RESCUER_ROLE is managed by itself _setupRole(RESCUER_ROLE, rescuer); _setRoleAdmin(RESCUER_ROLE, RESCUER_ROLE); } function deposit(uint256 amount) external virtual; function withdraw(uint256 amountInUnderlying) external virtual returns (uint256 actualAmountWithdrawn); /** @notice The total value locked in the money market, in terms of the underlying stablecoin */ function totalValue() external returns (uint256) { return _totalValue(_incomeIndex()); } /** @notice The total value locked in the money market, in terms of the underlying stablecoin */ function totalValue(uint256 currentIncomeIndex) external view returns (uint256) { return _totalValue(currentIncomeIndex); } /** @notice Used for calculating the interest generated (e.g. cDai's price for the Compound market) */ function incomeIndex() external returns (uint256 index) { return _incomeIndex(); } function stablecoin() external view virtual returns (ERC20); function claimRewards() external virtual; // Claims farmed tokens (e.g. COMP, CRV) and sends it to the rewards pool function setRewards(address newValue) external virtual; /** @dev IMPORTANT MUST READ This function is for restricting unauthorized accounts from taking funds and ensuring only tokens not used by the MoneyMarket can be rescued. IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY MAKE SURE YOU DO ALL OF THE FOLLOWING 1) You MUST override it in a MoneyMarket implementation. 2) You MUST make `super._authorizeRescue(token, target);` the first line of your overriding function. 3) You MUST revert during a call to this function if a token used by the MoneyMarket is being rescued. 4) You SHOULD look at how existing MoneyMarkets do it as an example. */ function _authorizeRescue( address, /*token*/ address /*target*/ ) internal view virtual override { require(hasRole(RESCUER_ROLE, msg.sender), "MoneyMarket: not rescuer"); } function _totalValue(uint256 currentIncomeIndex) internal view virtual returns (uint256); function _incomeIndex() internal virtual returns (uint256 index); event ESetParamAddress( address indexed sender, string indexed paramName, address newValue ); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {SafeERC20} from "../../libs/SafeERC20.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { AddressUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {MoneyMarket} from "../MoneyMarket.sol"; import {ILendingPool} from "./imports/ILendingPool.sol"; import { ILendingPoolAddressesProvider } from "./imports/ILendingPoolAddressesProvider.sol"; import {IAaveMining} from "./imports/IAaveMining.sol"; contract AaveMarket is MoneyMarket { using SafeERC20 for ERC20; using AddressUpgradeable for address; uint16 internal constant REFERRALCODE = 20; // Aave referral program code ILendingPoolAddressesProvider public provider; // Used for fetching the current address of LendingPool ERC20 public override stablecoin; ERC20 public aToken; IAaveMining public aaveMining; address public rewards; function initialize( address _provider, address _aToken, address _aaveMining, address _rewards, address _rescuer, address _stablecoin ) external initializer { __MoneyMarket_init(_rescuer); // Verify input addresses require( _provider.isContract() && _aToken.isContract() && _aaveMining.isContract() && _rewards != address(0) && _stablecoin.isContract(), "AaveMarket: An input address is not a contract" ); provider = ILendingPoolAddressesProvider(_provider); stablecoin = ERC20(_stablecoin); aaveMining = IAaveMining(_aaveMining); aToken = ERC20(_aToken); rewards = _rewards; } function deposit(uint256 amount) external override onlyOwner { require(amount > 0, "AaveMarket: amount is 0"); ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); // Transfer `amount` stablecoin from `msg.sender` stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Approve `amount` stablecoin to lendingPool stablecoin.safeIncreaseAllowance(address(lendingPool), amount); // Deposit `amount` stablecoin to lendingPool lendingPool.deposit( address(stablecoin), amount, address(this), REFERRALCODE ); } function withdraw(uint256 amountInUnderlying) external override onlyOwner returns (uint256 actualAmountWithdrawn) { require(amountInUnderlying > 0, "AaveMarket: amountInUnderlying is 0"); ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); // Redeem `amountInUnderlying` aToken, since 1 aToken = 1 stablecoin // Transfer `amountInUnderlying` stablecoin to `msg.sender` lendingPool.withdraw( address(stablecoin), amountInUnderlying, msg.sender ); return amountInUnderlying; } function claimRewards() external override { address[] memory assets = new address[](1); assets[0] = address(aToken); aaveMining.claimRewards(assets, type(uint256).max, rewards); } /** Param setters */ function setRewards(address newValue) external override onlyOwner { require(newValue != address(0), "AaveMarket: 0 address"); rewards = newValue; emit ESetParamAddress(msg.sender, "rewards", newValue); } /** @dev IMPORTANT MUST READ This function is for restricting unauthorized accounts from taking funds and ensuring only tokens not used by the MoneyMarket can be rescued. IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY MAKE SURE YOU DO ALL OF THE FOLLOWING 1) You MUST override it in a MoneyMarket implementation. 2) You MUST make `super._authorizeRescue(token, target);` the first line of your overriding function. 3) You MUST revert during a call to this function if a token used by the MoneyMarket is being rescued. 4) You SHOULD look at how existing MoneyMarkets do it as an example. */ function _authorizeRescue(address token, address target) internal view override { super._authorizeRescue(token, target); require(token != address(aToken), "AaveMarket: no steal"); } function _totalValue( uint256 /*currentIncomeIndex*/ ) internal view override returns (uint256) { return aToken.balanceOf(address(this)); } function _incomeIndex() internal view override returns (uint256 index) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); index = lendingPool.getReserveNormalizedIncome(address(stablecoin)); require(index > 0, "AaveMarket: BAD_INDEX"); } uint256[45] private __gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IAaveMining { function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; // Aave lending pool interface // Documentation: https://docs.aave.com/developers/the-core-protocol/lendingpool/ilendingpool // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { function getLendingPool() external view returns (address); }
-- criação do banco de dados para o cenário de E-commerce create database if not exists ecommerce; use ecommerce; -- clients -- criar tabela Clientes create table clientes( idCliente int auto_increment primary key, cli_Nome varchar(10), cli_NomeMeio varchar(10), cli_Sobrenome varchar(10), cli_CPF char(11) not null, cli_End_Logradouro varchar(255), cli_End_Numero int, cli_End_Complemento varchar(20), cli_End_Bairro varchar(30), cli_End_CEP char(8), cli_End_Cidade varchar(30), cli_End_Estado enum('AC','AL','AP','AM','BA','CE','DF','ES','GO','MA','MT','MS','MG','PA', 'PB','PR','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO') not null, cli_Nascimento date not null, constraint unique_cpf_cliente unique (cli_CPF) ); -- products -- criar tabela Produtos create table produtos( idProduto int auto_increment primary key, prod_Nome varchar(255) not null, prod_ClassificacaoKids bool default false, prod_Categoria enum('Eletrônico','Vestimenta','Brinquedos','Alimentos','Móveis') not null, prod_Descricao text, prod_Preco decimal(10,2) not null, prod_Avaliacao float default 0, prod_Tamanho varchar(10) ); -- para ser continuado no desafio: termine de implementar a tabela e crie a conexão com as tabelas necessárias -- além disso, reflita essa modificação no diagrama de esquema relacional -- criar constraints relacionadas ao pagamento -- payments -- criar tabela de Pagamentos create table pagamentos( idClientePagamento int, idPagamento int, pag_Tipo enum('Boleto','Cartão Crédito'), pag_LimiteLiberado float, pag_NumeroCartao int(16), primary key(idClientePagamento, idPagamento), constraint fk_pagamentos_cliente foreign key(idClientePagamento) references clientes(idCliente) ); -- orders -- criar tabela Pedidos create table pedidos( idPedido int auto_increment primary key, idPedidoCliente int, ped_Status enum('Cancelado','Confirmado','Em processamento','Enviado','Entregue') default 'Em processamento', ped_Descricao varchar(255), ped_ValorEnvio decimal(10,2) default 10, ped_Pagamento boolean default false, constraint fk_pedidos_cliente foreign key (idPedidoCliente) references clientes(idCliente) on update cascade ); -- storage -- criar tabela de Estoques create table estoqueProdutos( idProdutoEstoque int auto_increment primary key, est_Localidade varchar(255), est_Quantidade int default 0 ); -- suplier -- criar tabela de Fornecedores create table fornecedores( idFornecedor int auto_increment primary key, for_NomeSocial varchar(255) not null, for_CNPJ char(15) not null, for_ContatoTelefone varchar(11) not null, for_Email varchar(100) not null, constraint unique_fornecedor unique (for_CNPJ) ); -- seller -- criar tabela Vendedores create table vendedores( idVendedor int auto_increment primary key, ven_nomeSocial varchar(255) not null, ven_nomeAbstrato varchar(255), ven_CNPJ char(15), ven_CPF char(11), ven_localidade varchar(255), ven_contatoTelefone char(11) not null, ven_Email varchar(100) not null, constraint unique_cnpj_vendedores unique (ven_CNPJ), constraint unique_cpf_vendedores unique (ven_CPF) ); -- tabelas de relacionamentos M:N -- productSeller -- criar tabela de Vendedores de Produtos create table produtosVendedores( idpVendedor int, idpProduto int, prodVend_Quantidade int default 1, primary key (idpVendedor, idpProduto), constraint fk_produtos_vendedor foreign key (idpVendedor) references vendedores(idVendedor), constraint fk_produtos_produto foreign key (idpProduto) references produtos(idProduto) ); -- productOrder -- criar tabela de Ordem de Pedidos create table ordemPedidos( idOrdemProduto int, idOrdemPedido int, ord_Quantidade int default 1, ord_StatusPedido enum('Disponível', 'Sem estoque') default 'Disponível', primary key (idOrdemProduto, idOrdemPedido), constraint fk_ordemPedidos_produto foreign key (idOrdemProduto) references produtos(idProduto), constraint fk_ordemPedidos_pedido foreign key (idOrdemPedido) references pedidos(idPedido) ); -- storageLocation -- criar tabela de Localização dos Estoques create table estoquesLocalidades( idProdutoEstoque int, idEstoque int, est_Localidade varchar(255) not null, primary key (idProdutoEstoque, idEstoque), constraint fk_estoquesLocalidades_produtos foreign key (idProdutoEstoque) references produtos(idProduto), constraint fk_estoquesLocalidades_estoque foreign key (idEstoque) references estoqueProdutos(idProdutoEstoque) ); -- productSupplier -- criar a tabela de Produtos que são Fornecidos pelos Fornecedores create table produtosFornecedores( idProdFor_Fornecedor int, idProdFor_Produto int, prodFor_Quantidade int not null, primary key (idProdFor_Fornecedor, idProdFor_Produto), constraint fk_produtosFornecedores_fornecedor foreign key (idProdFor_Fornecedor) references fornecedores(idFornecedor), constraint fk_produtosFornecedores_produto foreign key (idProdFor_Produto) references produtos(idProduto) );
import axios from 'axios'; import React, { useEffect, useState } from 'react'; import toast from 'react-hot-toast'; import { useParams } from 'react-router-dom'; import { IoIosCheckmarkCircle, IoIosCloseCircle, IoIosAlert, } from 'react-icons/io'; import { HiOutlineDownload } from 'react-icons/hi'; import CompletedImage from '../../assets/completed.svg'; import FailedImage from '../../assets/failed.svg'; import ProgressImage from '../../assets/progress.svg'; import Cta from '../../components/Cta'; import { Button } from '@headlessui/react'; const Status = () => { const { video } = useParams(); const [response, setResponse] = useState({}); useEffect(() => { const loadStatus = async () => { try { const { data } = await axios.get( `${process.env.REACT_APP_API_URL}/api/${video}/status` ); setResponse(data); if (data?.success) { toast.success(data?.message); } } catch (error) { if (error?.message) { toast.error(error?.message); } } }; if (video) { loadStatus(); } }, [video]); const download = async () => { try { const response = await axios.get( `${process.env.REACT_APP_API_URL}/api/${video}/download`, { responseType: 'blob', } ); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', `${video}.zip`); document.body.appendChild(link); link.click(); document.body.removeChild(link); toast.success('Downloaded successfully'); } catch (error) { if (error?.message) { toast.error(error?.message); } } }; return ( <div className='container mx-auto h-full py-10 px-4'> <div className='bg-white rounded-lg shadow-lg p-8 w-full text-center'> <div className='flex flex-row gap-2 items-center justify-center mb-4'> <h2 className='text-5xl font-semibold text-gray-800'>Video status</h2> <div> {response?.status == 1 && ( <IoIosCheckmarkCircle size={50} className='text-green-600' /> )} {response?.status == 2 && ( <IoIosCloseCircle size={50} className='text-rose-600' /> )} {response?.status == 0 && ( <IoIosAlert size={50} className='text-blue-600' /> )} </div> </div> <div className='flex flex-col justify-center items-center md:h-full mb-6'> <img src={ response?.status == 1 ? CompletedImage : response?.status == 2 ? FailedImage : ProgressImage } className='h-[300px] md:h-[400px]' /> </div> <p className={`text-lg mb-4 ${ response?.status == 1 ? 'text-green-600' : response?.status == 2 ? 'text-rose-500' : 'text-blue-500' }`} > {response?.message} </p> <div className='flex flex-row gap-4 justify-center'> {response?.status == 1 && ( <> <Button className={ 'flex gap-3 items-center px-8 py-4 bg-green-600 border-b-green-700 border-b-4 text-white font-bold rounded-lg transition-transform transform-gpu hover:-translate-y-1 hover:shadow-lg ml-3' } onClick={download} > <span>Download now</span> <HiOutlineDownload size={25} /> </Button> </> )} <Cta text={`${ response?.status == 1 ? 'Try another' : response?.status == 2 ? 'Try again' : 'Make new' }`} /> </div> </div> </div> ); }; export default Status;
import React, { useContext } from "react"; import "./CardItem.css"; import { Link } from "react-router-dom"; import ReadMoreButton from "../../button/ReadMoreButton"; import { enFormattedDate, idFormattedDate } from "../../../utils"; import PropTypes from "prop-types"; import LocaleContext from "../../../contexts/LocaleContext"; import ThemeContext from "../../../contexts/ThemeContext"; const CardItem = ({ id, title, body, createdAt }) => { const { locale } = useContext(LocaleContext); const { theme } = useContext(ThemeContext); return ( <> <div className={`card-item-wrapper ${ theme === "dark" ? "mid-dark-theme shadow-for-dark" : "light-theme shadow-for-light" }`} > <div className="card-item-header"> <p className={ theme === "dark" ? "low-dark-text dates-item" : "soft-blue-text dates-item" } > {locale === "id" ? idFormattedDate(createdAt) : enFormattedDate(createdAt)} </p> <Link to={`/notes/${id}`} className="dec-none"> <h4 className={theme === "dark" ? "low-dark-text title-item" : "soft-blue-text title-item"}> {title} </h4> </Link> </div> <div className={theme === "dark" ? "light-text card-item-body" : "dark-text card-item-body"}> <p>{body}</p> </div> <Link to={`/notes/${id}`}> <ReadMoreButton /> </Link> </div> </> ); }; CardItem.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string.isRequired, body: PropTypes.string.isRequired, createdAt: PropTypes.string.isRequired, }; export default CardItem;
#!/usr/bin/env Rscript ### <PACKAGES> ### suppressMessages(library("circlize")) suppressMessages(library("ggplot2")) suppressMessages(library("grDevices")) suppressMessages(library("RSQLite")) suppressMessages(library("D3GB")) suppressMessages(library("docopt")) suppressMessages(library("GenomicRanges")) suppressMessages(library("checkmate")) suppressMessages(library("R.utils")) ### </PACKAGES> ### ### <MAN> ### "usage: BRASSVis.R [options] options: -i --inputFile=<file> BRASS file path.\n -e --exonsFile=<file> annnotation file.\n -o --outputFile=<file> output file name.\n --fusionFlagThreshold=<numeric> fusion flag threshold [default: 720].\n --transcriptSelection=<character> transcript selection [default: provided].\n --pdfWidth=<numeric> pdf width [default: 11.692].\n --pdfHeight=<numeric> pdf height [default: 8.267].\n --cytobandsFile=<file> cytobans file.\n --proteinDomainsFile=<character> protein domains file.\n --color1=<character> color 1 used in the visualization [default: #e5a5a5].\n --color2=<character> color 2 used in the visualization [default: #a7c4e5].\n --printExonLabels=<logical> print exon labels [default: TRUE].\n --fontSize=<numeric> font size [default: 1]" -> doc opt <- docopt(doc) opt$fusionFlagThreshold <- as.numeric(opt$fusionFlagThreshold) opt$pdfWidth <- as.numeric(opt$pdfWidth) opt$pdfHeight <- as.numeric(opt$pdfHeight) opt$fontSize <- as.numeric(opt$fontSize) if(is.null(opt$inputFile)) stop("Input BEDPE file neeed to be defined!") if(is.null(opt$outputFile)) stop("Output file neeed to be defined!") if(is.null(opt$exonsFile)) stop("Annotation file neeed to be defined!") if(is.null(opt$cytobandsFile)) message("Cytobands file not provided. Using default GRCh38 ideograms...") if(is.null(opt$proteinDomainsFile)) message("Protein domains file not provided.") checkmate::assert_string(opt$transcriptSelection, pattern = "provided|canonical") ### </MAN> ### ### <FUNCTIONS> ### # read and transform BRASS bedpe readBrass <- function(path) { checkmate::assert_string(path, pattern = "bedpe") brasInput <- data.table::fread(path, sep = "\t", fill = TRUE, skip = "# chr1") data.frame(`gene1` = brasInput$gene1, `gene2` = brasInput$gene2, `strand1` = paste0(brasInput$strand1, "/", brasInput$strand1), `strand2` = paste0(brasInput$strand2, "/", brasInput$strand2), `direction1` = ifelse(brasInput$strand1 == "+", "downstream", "upstream"), `direction2` = ifelse(brasInput$strand2 == "-", "downstream", "upstream"), `breakpoint1` = paste0(brasInput$`# chr1`, ":", brasInput$start1), `breakpoint2` = paste0(brasInput$chr2, ":", brasInput$start2), `site2` = 'splice-site', `type` = brasInput$svclass, `transcript_id1` = brasInput$transcript_id1, `transcript_id2` = brasInput$transcript_id2, `fusion_flag` = brasInput$fusion_flag, `total_region_count1` = brasInput$total_region_count1, `total_region_count2` = brasInput$total_region_count2, `assembly_score` = brasInput$assembly_score, `exonsSelected1` = brasInput$region_number1, `exonsSelected2` = brasInput$region_number2, `stringsAsFactors` = FALSE) } # remove 'chr' from contig name removeChr <- function(contig) { sub("^chr", "", sub("^chrM", "MT", contig), perl = TRUE) } # convenience function to check if a value is between two others between <- function(value, start, end) { value >= start & value <= end } # define colors changeColorBrightness <- function(color, delta) { rgb( min(255, max(0,col2rgb(color)["red",] + delta)), min(255, max(0,col2rgb(color)["green",] + delta)), min(255, max(0,col2rgb(color)["blue",] + delta)), maxColorValue = 255 ) } # get dark color of a given RGB getDarkColor <- function(color) { changeColorBrightness(color, - 100) } # draw vertical gradient drawVerticalGradient <- function(left, right, y, color, selection=NULL) { # check if gradient should only be drawn in part of the region if (!is.null(selection)) { y <- y[selection] left <- left[selection] right <- right[selection] } # draw gradient for (i in seq_len(length(y))) { polygon( c(left[seq_len(i)], right[seq_len(i)]), c(y[seq_len(i)], y[seq_len(i)]), border = NA, col = rgb(col2rgb(color)["red",], col2rgb(color)["green",], col2rgb(color)["blue",], col2rgb(color, alpha = T)["alpha",] * (1 / length(y)), max = 255) ) } } # parse gtf file parseGtfAttribute <- function(attribute, exons) { parsed <- gsub(paste0(".*", attribute, " \"?([^;\"]+)\"?;.*"), "\\1", exons$attributes) failedToParse <- parsed == exons$attributes if (any(failedToParse)) { warning(paste0("Failed to parse '", attribute, "' attribute of ", sum(failedToParse), " GTF record(s).")) parsed <- ifelse(failedToParse, "", parsed) } return(parsed) } # draw curly brace on plot drawCurlyBrace <- function(left, right, top, bottom, tip) { smoothness <- 20 x <- cumsum(exp(-seq(-2.5, 2.5, len = smoothness) ^ 2)) x <- x / max(x) y <- seq(top, bottom, len = smoothness) lines(left + (tip-left) + x * (left - tip), y) lines(tip + x * (right - tip), y) } # draw ideogram drawIdeogram <- function(adjust, left, right, y, cytobands, contig, breakpoint) { # define design of ideogram bandColors <- setNames(rgb(100:0, 100:0, 100:0, maxColorValue = 100), paste0("gpos", 0:100)) bandColors <- c(bandColors, gneg="#ffffff", acen="#ec4f4f", stalk="#0000ff") cytobands$color <- bandColors[cytobands$giemsa] arcSteps <- 30 # defines roundness of arc curlyBraceHeight <- 0.03 ideogramHeight <- 0.04 ideogramWidth <- 0.4 # extract bands of given contig bands <- cytobands[cytobands$contig == contig,] if (nrow(bands) == 0) { warning(paste("Ideogram of contig", contig, "cannot be drawn, because no Giemsa staining information is available.")) return(NULL) } # scale width of ideogram to fit inside given region bands$left <- bands$start / max(cytobands$end) * ideogramWidth bands$right <- bands$end / max(cytobands$end) * ideogramWidth # left/right-align cytobands offset <- ifelse(adjust=="left", left, right - max(bands$right)) bands$left <- bands$left + offset bands$right <- bands$right + offset # draw curly braces tip <- min(bands$left) + (max(bands$right)-min(bands$left)) / (max(bands$end) - min(bands$start)) * breakpoint drawCurlyBrace(left, right, y-0.05+curlyBraceHeight, y - 0.05, tip) # draw title of chromosome text((max(bands$right)+min(bands$left)) / 2, y + 0.07, paste("chromosome", contig), font = 2, cex = as.numeric(opt$fontSize), adj = c(0.5,0)) # draw name of band bandName <- bands[which(between(breakpoint, bands$start, bands$end)), "name"] tryCatch({ text(tip, y + 0.03, bandName, cex = as.numeric(opt$fontSize), adj = c(0.5,0)) }, error = function(e) { print("Lack of name of band") }) # draw start of chromosome leftArcX <- bands[1,"left"] + (1+cos(seq(pi / 2,1.5 * pi,len=arcSteps))) * (bands[1,"right"] - bands[1,"left"]) leftArcY <- y + sin(seq(pi / 2,1.5 * pi, len = arcSteps)) * (ideogramHeight / 2) polygon(leftArcX, leftArcY, col = bands[1,"color"]) # draw bands centromereStart <- NULL centromereEnd <- NULL for (band in 2:(nrow(bands)-1)) { if (bands[band,"giemsa"] != "acen") { rect(bands[band,"left"], y - ideogramHeight / 2, bands[band,"right"], y + ideogramHeight / 2, col = bands[band,"color"]) } else { # draw centromere if (is.null(centromereStart)) { polygon(c(bands[band,"left"], bands[band,"right"], bands[band,"left"]), c(y - ideogramHeight / 2, y, y + ideogramHeight / 2), col = bands[band,"color"]) centromereStart <- bands[band,"left"] } else { polygon(c(bands[band,"right"], bands[band,"left"], bands[band,"right"]), c(y - ideogramHeight / 2, y, y + ideogramHeight / 2), col = bands[band,"color"]) centromereEnd <- bands[band,"right"] } } } # draw end of chromosome band <- nrow(bands) rightArcX <- bands[band,"right"] - (1 + cos(seq(1.5 * pi,pi / 2, len = arcSteps))) * (bands[band,"right"] - bands[band,"left"]) rightArcY <- y + sin(seq(pi / 2,1.5 * pi, len = arcSteps)) * ideogramHeight/2 polygon(rightArcX, rightArcY, col = bands[band,"color"]) # if there is no centromere, make an artificial one with length zero if (is.null(centromereStart) || is.null(centromereEnd)) { centromereStart <- bands[1,"right"] centromereEnd <- bands[1,"right"] } # draw gradients for 3D effect drawVerticalGradient(leftArcX, rep(centromereStart, arcSteps), leftArcY, rgb(0,0,0,0.8), seq_len(round(arcSteps * 0.4))) # black from top on p-arm drawVerticalGradient(leftArcX, rep(centromereStart, arcSteps), leftArcY, rgb(1,1,1,0.7), round(arcSteps * 0.4):round(arcSteps * 0.1)) # white to top on p-arm drawVerticalGradient(leftArcX, rep(centromereStart, arcSteps), leftArcY, rgb(1,1,1,0.7), round(arcSteps * 0.4):round(arcSteps * 0.6)) # white to bottom on p-arm drawVerticalGradient(leftArcX, rep(centromereStart, arcSteps), leftArcY, rgb(0,0,0,0.9), arcSteps:round(arcSteps * 0.5)) # black from bottom on p-arm drawVerticalGradient(rightArcX, rep(centromereEnd, arcSteps), rightArcY, rgb(0,0,0,0.8), seq_len(round(arcSteps * 0.4))) # black from top on q-arm drawVerticalGradient(rightArcX, rep(centromereEnd, arcSteps), rightArcY, rgb(1,1,1,0.7), round(arcSteps * 0.4):round(arcSteps * 0.1)) # white to top on q-arm drawVerticalGradient(rightArcX, rep(centromereEnd, arcSteps), rightArcY, rgb(1,1,1,0.7), round(arcSteps * 0.4):round(arcSteps * 0.6)) # white to bottom on q-arm drawVerticalGradient(rightArcX, rep(centromereEnd, arcSteps), rightArcY, rgb(0,0,0,0.9), arcSteps:round(arcSteps * 0.5)) # black from bottom on q-arm } # draw strand drawStrand <- function(left, right, y, color, strand) { if (strand %in% c("+", "-")) { # draw strand lines(c(left + 0.001, right - 0.001), c(y, y), col = color, lwd = 2) lines(c(left + 0.001, right - 0.001), c(y, y), col = rgb(1,1,1,0.1), lwd = 1) # indicate orientation if (right - left > 0.01) for (i in seq(left + 0.005, right - 0.005, by = sign(right - left - 2 * 0.005) * 0.01)) { arrows(i, y, i + 0.001 * ifelse(strand == "+", 1, -1), y, col = color, length = 0.05, lwd = 2, angle = 60) arrows(i, y, i + 0.001 * ifelse(strand == "+", 1, -1), y, col = rgb(1,1,1,0.1), length = 0.05, lwd = 1, angle = 60) } } } # draw exons drawExon <- function(left, right, y, color, title, type) { gradientSteps <- 10 # defines smoothness of gradient exonHeight <- 0.03 if (type == "CDS") { # draw coding regions as thicker bars rect(left, y + exonHeight, right, y + exonHeight / 2 - 0.001, col = color, border = NA) rect(left, y - exonHeight, right, y - exonHeight / 2 + 0.001, col = color, border = NA) # draw border lines(c(left, left, right, right), c(y + exonHeight / 2, y + exonHeight, y + exonHeight, y + exonHeight / 2), col = getDarkColor(color), lend = 2) lines(c(left, left, right, right), c(y - exonHeight / 2, y - exonHeight, y - exonHeight, y - exonHeight / 2), col = getDarkColor(color), lend = 2) # draw gradients for 3D effect drawVerticalGradient(rep(left, gradientSteps), rep(right, gradientSteps), seq(y + 0.03, y + 0.015, len = gradientSteps), rgb(0,0,0,0.2)) drawVerticalGradient(rep(left, gradientSteps), rep(right, gradientSteps), seq(y - 0.03, y - 0.015, len = gradientSteps), rgb(0,0,0,0.3)) } else if (type == "exon") { rect(left, y + exonHeight / 2, right, y - exonHeight / 2, col = color, border = getDarkColor(color)) # draw gradients for 3D effect drawVerticalGradient(rep(left, gradientSteps), rep(right, gradientSteps), seq(y, y + exonHeight / 2, len = gradientSteps), rgb(1,1,1,0.6)) drawVerticalGradient(rep(left, gradientSteps), rep(right, gradientSteps), seq(y, y - exonHeight / 2, len = gradientSteps), rgb(1,1,1,0.6)) # add exon label text((left + right) / 2, y, title, cex = 0.9 * as.numeric(opt$fontSize)) } } # draw circos drawCircos <- function(fusion, fusions, cytobands, minConfidenceForCircosPlot) { # check if Giemsa staining information is available for (contig in unlist(fusions[fusion,c("contig1", "contig2")])) { if (!any(cytobands$contig == contig)) { warning(paste0("Circos plot cannot be drawn, because no Giemsa staining information is available for contig ", contig, ".")) return(NULL) } } # initialize with empty circos plot circos.clear() circos.initializeWithIdeogram(cytoband=cytobands, labels.cex = 1.1, axis.labels.cex = 0.6) # use gene names as labels or <contig>:<position> for intergenic breakpoints geneLabels <- data.frame( contig = c(fusions[fusion,"contig1"], fusions[fusion,"contig2"]), start = c(fusions[fusion,"breakpoint1"], fusions[fusion,"breakpoint2"]) ) geneLabels$end <- geneLabels$start + 1 geneLabels$gene <- c(fusions[fusion,"gene1"], fusions[fusion,"gene2"]) geneLabels$gene <- ifelse(c(fusions[fusion,"site1"], fusions[fusion,"site2"]) == "intergenic", paste0(c(fusions[fusion,"display_contig1"], fusions[fusion,"display_contig2"]), ":", geneLabels$start), geneLabels$gene) # draw gene labels circos.genomicLabels(geneLabels, labels.column = 4, side ="inside", cex = as.numeric(opt$fontSize) - 0.1) # draw chromosome labels in connector plot for (contig in unique(cytobands$contig)) { set.current.cell(track.index = 2, sector.index = contig) # draw in gene label connector track (track.index=2) circos.text(CELL_META$xcenter, CELL_META$ycenter, contig, cex = 0.25) } } drawProteinDomains <- function(fusion, exons1, exons2, proteinDomains, color1, color2, mergeDomainsOverlappingBy) { exonHeight <- 0.2 exonsY <- 0.5 geneNamesY <- exonsY - exonHeight / 2 - 0.05 # find coding exons codingExons1 <- exons1[exons1$type == "CDS" & fusion$site1 != "intergenic",] codingExons2 <- exons2[exons2$type == "CDS" & fusion$site2 != "intergenic",] # cut off coding regions beyond breakpoint if (fusion$direction1 == "upstream") { codingExons1 <- codingExons1[codingExons1$end >= fusion$breakpoint1, ] codingExons1$start <- ifelse(codingExons1$start < fusion$breakpoint1, fusion$breakpoint1, codingExons1$start) } else { codingExons1 <- codingExons1[codingExons1$start <= fusion$breakpoint1, ] codingExons1$end <- ifelse(codingExons1$end > fusion$breakpoint1, fusion$breakpoint1, codingExons1$end) } if (fusion$direction2 == "upstream") { codingExons2 <- codingExons2[codingExons2$end >= fusion$breakpoint2, ] codingExons2$start <- ifelse(codingExons2$start < fusion$breakpoint2, fusion$breakpoint2, codingExons2$start) } else { codingExons2 <- codingExons2[codingExons2$start <= fusion$breakpoint2, ] codingExons2$end <- ifelse(codingExons2$end > fusion$breakpoint2, fusion$breakpoint2, codingExons2$end) } # find overlapping domains exonsGRanges1 <- GRanges(codingExons1$contig, IRanges(codingExons1$start, codingExons1$end), strand = codingExons1$strand) exonsGRanges2 <- GRanges(codingExons2$contig, IRanges(codingExons2$start, codingExons2$end), strand = codingExons2$strand) domainsGRanges <- GRanges(proteinDomains$contig, IRanges(proteinDomains$start, proteinDomains$end), strand = proteinDomains$strand) domainsGRanges$proteinDomainName <- proteinDomains$proteinDomainName domainsGRanges$proteinDomainID <- proteinDomains$proteinDomainID domainsGRanges$color <- proteinDomains$color domainsGRanges <- domainsGRanges[suppressWarnings(unique(queryHits(findOverlaps(domainsGRanges, GenomicRanges::union(exonsGRanges1, exonsGRanges2)))))] # group overlapping domains by domain ID domainsGRangesList <- GRangesList(lapply(unique(domainsGRanges$proteinDomainID), function(x) { domainsGRanges[domainsGRanges$proteinDomainID == x] })) # trim protein domains to exon boundaries trimDomains <- function(domainsGRangesList, exonsGRanges) { do.call( "rbind", lapply( domainsGRangesList, function(x) { intersected <- as.data.frame(reduce(suppressWarnings(GenomicRanges::intersect(x, exonsGRanges)))) if (nrow(intersected) > 0) { intersected$proteinDomainName <- head(x$proteinDomainName, 1) intersected$proteinDomainID <- head(x$proteinDomainID, 1) intersected$color <- head(x$color, 1) } else { intersected$proteinDomainName <- character() intersected$proteinDomainID <- character() intersected$color <- character() } return(intersected) } ) ) } retainedDomains1 <- trimDomains(domainsGRangesList, exonsGRanges1) retainedDomains2 <- trimDomains(domainsGRangesList, exonsGRanges2) # calculate length of coding exons codingExons1$length <- codingExons1$end - codingExons1$start + 1 codingExons2$length <- codingExons2$end - codingExons2$start + 1 # abort, if there are no coding regions if (sum(exons1$type == "CDS") + sum(exons2$type == "CDS") == 0) { text(0.5, 0.5, "Genes are not protein-coding.") return(NULL) } codingLength1 <- sum(codingExons1$length) codingLength2 <- sum(codingExons2$length) if (codingLength1 + codingLength2 == 0) { text(0.5, 0.5, "No coding regions retained in fusion transcript.") return(NULL) } antisenseTranscription1 <- sub("/.*", "", fusion$strand1) != sub(".*/", "", fusion$strand1) antisenseTranscription2 <- sub("/.*", "", fusion$strand2) != sub(".*/", "", fusion$strand2) if ((codingLength1 == 0 || antisenseTranscription1) && (codingLength2 == 0 || antisenseTranscription2)) { text(0.5, 0.5, "No coding regions due to antisense transcription.") return(NULL) } # remove introns from protein domains removeIntronsFromProteinDomains <- function(codingExons, retainedDomains) { if (nrow(codingExons) == 0) return(NULL) cumulativeIntronLength <- 0 previousExonEnd <- 0 for (exon in seq_len(nrow(codingExons))) { if (codingExons[exon, "start"] > previousExonEnd) cumulativeIntronLength <- cumulativeIntronLength + codingExons[exon,"start"] - previousExonEnd domainsInExon <- which(between(retainedDomains$start, codingExons[exon,"start"], codingExons[exon, "end"])) retainedDomains[domainsInExon, "start"] <- retainedDomains[domainsInExon,"start"] - cumulativeIntronLength domainsInExon <- which(between(retainedDomains$end, codingExons[exon,"start"], codingExons[exon, "end"])) retainedDomains[domainsInExon, "end"] <- retainedDomains[domainsInExon,"end"] - cumulativeIntronLength previousExonEnd <- codingExons[exon, "end"] } # merge adjacent domains retainedDomains <- do.call( "rbind", lapply( unique(retainedDomains$proteinDomainID), function(x) { domain <- retainedDomains[retainedDomains$proteinDomainID == x,] merged <- reduce(GRanges(domain$seqnames, IRanges(domain$start, domain$end), strand=domain$strand)) merged$proteinDomainName <- head(domain$proteinDomainName, 1) merged$proteinDomainID <- head(domain$proteinDomainID, 1) merged$color <- head(domain$color, 1) return(as.data.frame(merged)) } ) ) return(retainedDomains) } retainedDomains1 <- removeIntronsFromProteinDomains(codingExons1, retainedDomains1) retainedDomains2 <- removeIntronsFromProteinDomains(codingExons2, retainedDomains2) # abort, if no domains are retained if (is.null(retainedDomains1) && is.null(retainedDomains2)) { text(0.5, 0.5, "No protein domains retained in fusion.") return(NULL) } # merge domains with similar coordinates mergeSimilarDomains <- function(domains, mergeDomainsOverlappingBy) { if (is.null(domains)) return(domains) merged <- domains[FALSE, ] # create empty data frame domains <- domains[order(domains$end - domains$start, decreasing = FALSE), ] # start with bigger domains => bigger domains are retained for (domain in rownames(domains)) { if (!any((abs(merged$start - domains[domain, "start"]) + abs(merged$end - domains[domain,"end"])) / (domains[domain,"end"] - domains[domain,"start"]) <= 1 - mergeDomainsOverlappingBy)) merged <- rbind(merged, domains[domain,]) } return(merged) } retainedDomains1 <- mergeSimilarDomains(retainedDomains1, as.logical(0.9)) retainedDomains2 <- mergeSimilarDomains(retainedDomains2, as.logical(0.9)) # normalize length to 1 codingExons1$length <- codingExons1$length / (codingLength1 + codingLength2) codingExons2$length <- codingExons2$length / (codingLength1 + codingLength2) retainedDomains1$start <- retainedDomains1$start / (codingLength1 + codingLength2) retainedDomains1$end <- retainedDomains1$end / (codingLength1 + codingLength2) retainedDomains2$start <- retainedDomains2$start / (codingLength1 + codingLength2) retainedDomains2$end <- retainedDomains2$end / (codingLength1 + codingLength2) # draw coding regions rect(0, exonsY - exonHeight / 2, sum(codingExons1$length), exonsY + exonHeight / 2, col = opt$color1, border = NA) rect(sum(codingExons1$length), exonsY - exonHeight / 2, sum(codingExons1$length) + sum(codingExons2$length), exonsY + exonHeight / 2, col = opt$color2, border = NA) # indicate exon boundaries as dotted lines exonBoundaries <- cumsum(c(codingExons1$length, codingExons2$length)) if (length(exonBoundaries) > 1) { exonBoundaries <- exonBoundaries[1:(length(exonBoundaries)-1)] for (exonBoundary in exonBoundaries) lines(c(exonBoundary, exonBoundary), c(exonsY - exonHeight, exonsY + exonHeight), col = "white", lty = 3) } # find overlapping domains # nest if one is contained in another # stack if they overlap partially nestDomains <- function(domains) { if (length(unlist(domains)) == 0) return(domains) domains <- domains[order(domains$end - domains$start, decreasing = TRUE), ] rownames(domains) <- seq_len(nrow(domains)) # find nested domains and make tree structure domains$parent <- 0 for (domain in rownames(domains)) domains[domains$start >= domains[domain, "start"] & domains$end <= domains[domain, "end"] & rownames(domains) != domain, "parent"] <- domain # find partially overlapping domains maxOverlappingDomains <- max(coverage(IRanges(domains$start*10e6, domains$end*10e6))) padding <- 1 / maxOverlappingDomains * 0.4 domains$y <- 0 domains$height <- 0 adjustPositionAndHeight <- function(parentDomain, y, height, padding, e) { for (domain in which(e$domains$parent == parentDomain)) { overlappingDomains <- which((between(e$domains$start, e$domains[domain, "start"], e$domains[domain, "end"]) | between(e$domains$end, e$domains[domain, "start"], e$domains[domain, "end"])) & e$domains$parent == parentDomain) e$domains[domain, "height"] <- height / length(overlappingDomains) - padding * (length(overlappingDomains) - 1) / length(overlappingDomains) e$domains[domain, "y"] <- y + (which(domain == overlappingDomains) - 1) * (e$domains[domain,"height"] + padding) adjustPositionAndHeight(domain, e$domains[domain, "y"] + padding, e$domains[domain, "height"] - 2 * padding, padding, e) } } adjustPositionAndHeight(0, 0, 1, padding, environment()) domains <- domains[order(domains$height, decreasing=TRUE), ] # draw nested domains last return(domains) } retainedDomains1 <- nestDomains(retainedDomains1) retainedDomains2 <- nestDomains(retainedDomains2) retainedDomains1$y <- exonsY - exonHeight / 2 + 0.025 + (exonHeight - 2 * 0.025) * retainedDomains1$y retainedDomains2$y <- exonsY - exonHeight / 2 + 0.025 + (exonHeight - 2 * 0.025) * retainedDomains2$y retainedDomains1$height <- retainedDomains1$height * (exonHeight - 2 * 0.025) retainedDomains2$height <- retainedDomains2$height * (exonHeight - 2 * 0.025) # draw domains drawProteinDomainRect <- function(left, bottom, right, top, color) { rect(left, bottom, right, top, col = color, border = getDarkColor(color)) # draw gradients for 3D effect gradientSteps <- 20 drawVerticalGradient(rep(left, gradientSteps), rep(right, gradientSteps), seq(top, bottom, len=gradientSteps), rgb(1,1,1,0.7)) drawVerticalGradient(rep(left, gradientSteps), rep(right, gradientSteps), seq(bottom, bottom+(top-bottom) * 0.4, len = gradientSteps), rgb(0,0,0,0.1)) } if (length(unlist(retainedDomains1)) > 0) for (domain in seq_len(nrow(retainedDomains1))) drawProteinDomainRect(retainedDomains1[domain, "start"], retainedDomains1[domain, "y"], retainedDomains1[domain, "end"], retainedDomains1[domain, "y"] + retainedDomains1[domain, "height"], retainedDomains1[domain, "color"]) if (length(unlist(retainedDomains2)) > 0) for (domain in seq_len(nrow(retainedDomains2))) drawProteinDomainRect(sum(codingExons1$length)+retainedDomains2[domain,"start"], retainedDomains2[domain,"y"], sum(codingExons1$length)+retainedDomains2[domain,"end"], retainedDomains2[domain,"y"]+retainedDomains2[domain,"height"], retainedDomains2[domain,"color"]) # draw gene names, if there are coding exons if (codingLength1 > 0) text(sum(codingExons1$length) / 2, geneNamesY, fusion$gene1, font = 2, cex = opt$fontSize) if (codingLength2 > 0) text(sum(codingExons1$length) + sum(codingExons2$length) / 2, geneNamesY, fusion$gene2, font = 2, cex = opt$fontSize) # calculate how many non-adjacent unique domains there are # we need this info to know where to place labels vertically countUniqueDomains <- function(domains) { uniqueDomains <- 0 if (length(unlist(domains)) > 0) { uniqueDomains <- 1 if (nrow(domains) > 1) { previousDomain <- domains[1, "proteinDomainID"] for (domain in 2:nrow(domains)) { if (previousDomain != domains[domain, "proteinDomainID"]) uniqueDomains <- uniqueDomains + 1 previousDomain <- domains[domain, "proteinDomainID"] } } } return(uniqueDomains) } if (length(unlist(retainedDomains1)) > 0) retainedDomains1 <- retainedDomains1[order(retainedDomains1$start), ] uniqueDomains1 <- countUniqueDomains(retainedDomains1) if (length(unlist(retainedDomains2)) > 0) retainedDomains2 <- retainedDomains2[order(retainedDomains2$end, decreasing = TRUE), ] uniqueDomains2 <- countUniqueDomains(retainedDomains2) # draw title of plot titleY <- exonsY + exonHeight / 2 + (uniqueDomains1 + 2) * 0.05 text(0.5, titleY + 0.01, "RETAINED PROTEIN DOMAINS", adj = c(0.5, 0), font = 2, cex = opt$fontSize) # draw domain labels for gene1 if (length(unlist(retainedDomains1)) > 0) { previousConnectorX <- -1 previousLabelX <- -1 labelY <- exonsY + exonHeight / 2 + uniqueDomains1 * 0.05 for (domain in seq_len(nrow(retainedDomains1))) { # if possible avoid overlapping lines of labels connectorX <- min(retainedDomains1[domain, "start"] + 0.01, (retainedDomains1[domain, "start"] + retainedDomains1[domain, "end"]) / 2) if (connectorX - previousConnectorX < 0.01 && retainedDomains1[domain, "end"] > previousConnectorX + 0.01) connectorX <- previousConnectorX + 0.01 labelX <- max(connectorX, previousLabelX) + 0.02 # use a signle label for adjacent domains of same type adjacentDomainsOfSameType <- domain + 1 <= nrow(retainedDomains1) && retainedDomains1[domain + 1, "proteinDomainID"] == retainedDomains1[domain, "proteinDomainID"] if (adjacentDomainsOfSameType) { labelX <- retainedDomains1[domain + 1, "start"] + 0.015 } else { text(labelX, labelY, retainedDomains1[domain, "proteinDomainName"], adj = c(0,0.5), col = getDarkColor(retainedDomains1[domain, "color"]), cex = opt$fontSize) } lines(c(labelX - 0.005, connectorX, connectorX), c(labelY, labelY, retainedDomains1[domain, "y"] + retainedDomains1[domain, "height"]), col = getDarkColor(retainedDomains1[domain, "color"])) if (!adjacentDomainsOfSameType) labelY <- labelY - 0.05 previousConnectorX <- connectorX previousLabelX <- labelX } } # draw domain labels for gene2 if (length(unlist(retainedDomains2)) > 0) { previousConnectorX <- 100 previousLabelX <- 100 labelY <- exonsY - exonHeight / 2 - (uniqueDomains2+1) * 0.05 for (domain in seq_len(nrow(retainedDomains2))) { # if possible avoid overlapping connector lines of labels connectorX <- sum(codingExons1$length) + max(retainedDomains2[domain, "end"] - 0.01, (retainedDomains2[domain, "start"] + retainedDomains2[domain, "end"]) / 2) if (previousConnectorX - connectorX < 0.01 && sum(codingExons1$length) + retainedDomains2[domain, "start"] < previousConnectorX - 0.01) connectorX <- previousConnectorX - 0.01 labelX <- min(connectorX, previousLabelX) - 0.02 # use a signle label for adjacent domains of same type adjacentDomainsOfSameType <- domain + 1 <= nrow(retainedDomains2) && retainedDomains2[domain + 1, "proteinDomainID"] == retainedDomains2[domain, "proteinDomainID"] if (adjacentDomainsOfSameType) { labelX <- sum(codingExons1$length) + retainedDomains2[domain + 1, "end"] - 0.015 } else { text(labelX, labelY, retainedDomains2[domain, "proteinDomainName"], adj = c(1,0.5), col = getDarkColor(retainedDomains2[domain, "color"]), cex = opt$fontSize) } lines(c(labelX + 0.005, connectorX, connectorX), c(labelY, labelY, retainedDomains2[domain, "y"]), col = getDarkColor(retainedDomains2[domain, "color"])) if (!adjacentDomainsOfSameType) labelY <- labelY + 0.05 previousConnectorX <- connectorX previousLabelX <- labelX } } } findExons <- function(exons, contig, gene, direction, breakpoint, coverage, transcriptId, transcriptSelection) { # use the provided transcript if desired if (transcriptSelection == "provided" && transcriptId != "." && transcriptId != "") { candidateExons <- exons[exons$transcript == transcriptId,] if (nrow(candidateExons) == 0) { warning(paste0("Unknown transcript given in fusions file (", transcriptId, "), selecting a different one")) } else { return(candidateExons) } } if (transcriptSelection == "canonical") { candidateExons <- exons[exons$geneName == gene & exons$contig == contig,] } else { # look for exon with breakpoint as splice site transcripts <- exons[exons$geneName == gene & exons$contig == contig & exons$type == "exon" & (direction == "downstream" & abs(exons$end - breakpoint) <= 2 | direction == "upstream" & abs(exons$start - breakpoint) <= 2), "transcript"] candidateExons <- exons[exons$transcript %in% transcripts, ] # if none was found, use all exons of the gene closest to the breakpoint if (nrow(candidateExons) == 0) { candidateExons <- exons[exons$geneName == gene & exons$contig == contig,] if (length(unique(candidateExons$geneID)) > 0) { # more than one gene found with the given name => use the closest one distanceToBreakpoint <- aggregate(seq_len(nrow(candidateExons)), by = list(candidateExons$geneID), function(x) { min(abs(candidateExons[x, "start"] - breakpoint), abs(candidateExons[x, "end"] - breakpoint)) }) closestGene <- head(distanceToBreakpoint[distanceToBreakpoint[, 2] == min(distanceToBreakpoint[, 2]), 1], 1) candidateExons <- candidateExons[candidateExons$geneID == closestGene,] } } # if we have coverage information, use the transcript with the highest coverage if there are multiple hits if (!is.null(coverage)) { highestCoverage <- -1 transcriptWithHighestCoverage <- NULL lengthOfTranscriptWithHighestCoverage <- 0 for (transcript in unique(candidateExons$transcript)) { exonsOfTranscript <- candidateExons[candidateExons$transcript == transcript,] exonsOfTranscript$start <- sapply(exonsOfTranscript$start, max, min(start(coverage))) exonsOfTranscript$end <- sapply(exonsOfTranscript$end, min, max(end(coverage))) lengthOfTranscript <- sum(exonsOfTranscript$end - exonsOfTranscript$start + 1) coverageSum <- sum(as.numeric(coverage[IRanges(exonsOfTranscript$start, exonsOfTranscript$end)])) # we prefer shorter transcripts over longer ones, because otherwise there is a bias towards transcripts with long UTRs # => a longer transcript must have substantially higher coverage to replace a shorter one substantialDifference <- (1 - min(lengthOfTranscript, lengthOfTranscriptWithHighestCoverage) / max(lengthOfTranscript, lengthOfTranscriptWithHighestCoverage)) / 10 if (lengthOfTranscript > lengthOfTranscriptWithHighestCoverage && coverageSum * (1 - substantialDifference) > highestCoverage || lengthOfTranscript < lengthOfTranscriptWithHighestCoverage && coverageSum > highestCoverage * (1 - substantialDifference)) { highestCoverage <- coverageSum transcriptWithHighestCoverage <- transcript lengthOfTranscriptWithHighestCoverage <- lengthOfTranscript } } candidateExons <- candidateExons[candidateExons$transcript==transcriptWithHighestCoverage,] } # if the gene has multiple transcripts, search for transcripts which encompass the breakpoint if (length(unique(candidateExons$transcript)) > 1) { transcriptStart <- aggregate(candidateExons$start, by = list(candidateExons$transcript), min) rownames(transcriptStart) <- transcriptStart[, 1] transcriptEnd <- aggregate(candidateExons$end, by = list(candidateExons$transcript), max) rownames(transcriptEnd) <- transcriptEnd[, 1] candidateExons <- candidateExons[between(breakpoint, transcriptStart[candidateExons$transcript, 2], transcriptEnd[candidateExons$transcript, 2]), ] } } # find the consensus transcript, if there are multiple hits if (length(unique(candidateExons$transcript)) > 1) { consensusTranscript <- ifelse(grepl("appris_principal_1", candidateExons$attributes), 12, ifelse(grepl("appris_principal_2", candidateExons$attributes), 11, ifelse(grepl("appris_principal_3", candidateExons$attributes), 10, ifelse(grepl("appris_principal_4", candidateExons$attributes), 9, ifelse(grepl("appris_principal_5", candidateExons$attributes), 8, ifelse(grepl("appris_principal", candidateExons$attributes), 7, ifelse(grepl("appris_candidate_longest", candidateExons$attributes), 6, ifelse(grepl("appris_candidate", candidateExons$attributes), 5, ifelse(grepl("appris_alternative_1", candidateExons$attributes), 4, ifelse(grepl("appris_alternative_2", candidateExons$attributes), 3, ifelse(grepl("appris_alternative", candidateExons$attributes), 2, ifelse(grepl("CCDS", candidateExons$attributes), 1, 0 )))))))))))) candidateExons <- candidateExons[consensusTranscript == max(consensusTranscript), ] } # use the transcript with the longest coding sequence, if there are still multiple hits if (length(unique(candidateExons$transcript)) > 1) { codingSequenceLength <- ifelse(candidateExons$type == "CDS", candidateExons$end - candidateExons$start, 0) totalCodingSequenceLength <- aggregate(codingSequenceLength, by=list(candidateExons$transcript), sum) rownames(totalCodingSequenceLength) <- totalCodingSequenceLength[, 1] candidateExons <- candidateExons[totalCodingSequenceLength[candidateExons$transcript,2] == max(totalCodingSequenceLength[, 2]), ] } # use the transcript with the longest overall sequence, if there are still multiple hits if (length(unique(candidateExons$transcript)) > 1) { exonLength <- candidateExons$end - candidateExons$start totalExonLength <- aggregate(exonLength, by=list(candidateExons$transcript), sum) rownames(totalExonLength) <- totalExonLength[, 1] candidateExons <- candidateExons[totalExonLength[candidateExons$transcript, 2] == max(totalExonLength[, 2]), ] } # if there are still multiple hits, select the first one candidateExons <- unique(candidateExons[candidateExons$transcript == head(unique(candidateExons$transcript), 1), ]) return(candidateExons) } ### </FUNCTIONS> ### ### <MAIN> ### darkColor1 <- getDarkColor(opt$color1) darkColor2 <- getDarkColor(opt$color2) fusions <- readBrass(opt$inputFile) fusions$display_contig1 <- sub(":[^:]*$", "", fusions$breakpoint1, perl = TRUE) fusions$display_contig2 <- sub(":[^:]*$", "", fusions$breakpoint2, perl = TRUE) fusions$contig1 <- gsub(":.*", "", fusions$breakpoint1) fusions$contig2 <- gsub(":.*", "", fusions$breakpoint2) fusions$breakpoint1 <- as.numeric(sub(".*:", "", fusions$breakpoint1, perl = TRUE)) fusions$breakpoint2 <- as.numeric(sub(".*:", "", fusions$breakpoint2, perl = TRUE)) fusions$site1 <- rep("exon", nrow(fusions)) fusions$site2 <- rep("exon", nrow(fusions)) fusions$confidence <- rep("high", nrow(fusions)) pdf(opt$outputFile, onefile = TRUE, width = as.numeric(opt$pdfWidth), height = as.numeric(opt$pdfHeight), title = "Title") if (nrow(fusions) == 0) { plot(0, 0, type="l", xaxt="n", yaxt="n", xlab="", ylab="") text(0, 0, "Error: empty input file\n") dev.off() quit("no") } message("Loading ideograms") if(is.null(opt$cytobandsFile)){ cytobands <- GRCh38.bands } else { cytobands <- read.table(opt$cytobandsFile, header = TRUE, sep = "\t") } colnames(cytobands)[1] <- "contig" names(cytobands)[5] <- "giemsa" cytobands <- cytobands[order(cytobands$contig, cytobands$start, cytobands$end),] message("Loading annotation") exons <- read.table(opt$exonsFile, header = FALSE, sep = "\t", comment.char = "#", quote = "", stringsAsFactors = FALSE)[,c(1, 3, 4, 5, 7, 9)] colnames(exons) <- c("contig", "type", "start", "end", "strand", "attributes") exons <- exons[exons$type %in% c("exon", "CDS"),] exons$contig <- removeChr(exons$contig) exons$geneID <- parseGtfAttribute("gene_id", exons) exons$geneName <- parseGtfAttribute("gene_name", exons) exons$geneName <- ifelse(exons$geneName == "", exons$geneID, exons$geneName) exons$transcript <- parseGtfAttribute("transcript_id", exons) exons$exonNumber <- ifelse(rep(as.logical(opt$printExonLabels), nrow(exons)), parseGtfAttribute("exon_number", exons), "") proteinDomains <- NULL if (!is.null(opt$proteinDomainsFile)) { message("Loading protein domains") proteinDomains <- read.table(opt$proteinDomainsFile, header = FALSE, sep = "\t", comment.char = "", quote = "", stringsAsFactors = FALSE)[,c(1,4,5,7,9)] colnames(proteinDomains) <- c("contig", "start", "end", "strand", "attributes") proteinDomains$color <- sub(";.*", "", sub(".*color=", "", proteinDomains$attributes, perl = TRUE), perl = TRUE) proteinDomains$proteinDomainName <- sapply(sub(";.*", "", sub(".*Name=", "", proteinDomains$attributes, perl = TRUE), perl = TRUE), URLdecode) proteinDomains$proteinDomainID <- sub(";.*", "", sub(".*protein_domain_id=", "", proteinDomains$attributes, perl = TRUE), perl = TRUE) proteinDomains <- proteinDomains[ , colnames(proteinDomains) != "attributes"] } # insert dummy annotations for intergenic breakpoints if (any(fusions$site1 == "intergenic" | fusions$site2 == "intergenic")) { intergenicBreakpoints <- rbind( setNames(fusions[fusions$site1 == "intergenic", c("gene1", "strand1", "contig1", "breakpoint1")], c("gene", "strand", "contig", "breakpoint")), setNames(fusions[fusions$site2 == "intergenic", c("gene2", "strand2", "contig2", "breakpoint2")], c("gene", "strand", "contig", "breakpoint")) ) exons <- rbind(exons, data.frame( contig = intergenicBreakpoints$contig, type = "intergenic", start = intergenicBreakpoints$breakpoint-1000, end = intergenicBreakpoints$breakpoint+1000, strand = ".", attributes = "", geneName = intergenicBreakpoints$gene, geneID = intergenicBreakpoints$gene, transcript = intergenicBreakpoints$gene, exonNumber = "intergenic" )) } fusions$tandem <- ifelse(fusions$type == "tandem-duplication", 2, 1) fusions <- fusions[rep(seq_len(nrow(fusions)), fusions$tandem), ] duplicatedFusion <- which(duplicated(fusions)) fusions[duplicatedFusion, "direction1"] <- "downstream" fusions[duplicatedFusion, "direction2"] <- "upstream" for (fusion in seq_len(nrow(fusions))) { message(paste0("Drawing fusion #", fusion, ": ", fusions[fusion, "gene1"], ":", fusions[fusion, "gene2"])) if(fusions[fusion, "fusion_flag"] < opt$fusionFlagThreshold) { message(sprintf("Fusion flag lower than %s. Omiting...", opt$fusionFlagThreshold)) next } # compute coverage from alignments file coverage1 <- NULL coverage2 <- NULL # find all exons belonging to the fused genes exons1 <- findExons(exons, fusions[fusion, "contig1"], fusions[fusion, "gene1"], fusions[fusion, "direction1"], fusions[fusion, "breakpoint1"], coverage1, fusions[fusion, "transcript_id1"], opt$transcriptSelection) exons2 <- findExons(exons, fusions[fusion, "contig2"], fusions[fusion, "gene2"], fusions[fusion, "direction2"], fusions[fusion, "breakpoint2"], coverage2, fusions[fusion, "transcript_id2"], opt$transcriptSelection) if (nrow(exons1) == 0 || nrow(exons2) == 0) next if(unique(exons1$geneID) == unique(exons2$geneID)) next # sort coding exons last, such that they are drawn over the border of non-coding exons exons1 <- exons1[order(exons1$start, -rank(exons1$type)), ] exons2 <- exons2[order(exons2$start, -rank(exons2$type)), ] # insert dummy exons, if breakpoints are outside the gene (e.g., in UTRs) # this avoids plotting artifacts breakpoint1 <- fusions[fusion, "breakpoint1"] breakpoint2 <- fusions[fusion, "breakpoint2"] if (breakpoint1 < min(exons1$start)) { exons1 <- rbind(c(exons1[1, "contig"], "dummy", breakpoint1 - 1000, breakpoint1 - 1000, exons1[1, "strand"], "", "dummy", exons1[1, "geneID"], exons1[1, "transcript"], ""), exons1) } else if (breakpoint1 > max(exons1$end)) { exons1 <- rbind(exons1, c(exons1[1, "contig"], "dummy", breakpoint1 + 1000, breakpoint1 + 1000, exons1[1, "strand"], "", "dummy", exons1[1, "geneID"], exons1[1, "transcript"], "")) } if (breakpoint2 < min(exons2$start)) { exons2 <- rbind(c(exons2[1, "contig"], "dummy", breakpoint2 - 1000, breakpoint2 - 1000, exons2[1, "strand"], "", "dummy", exons2[1, "geneID"], exons2[1, "transcript"], ""), exons2) } else if (breakpoint2 > max(exons2$end)) { exons2 <- rbind(exons2, c(exons2[1, "contig"], "dummy", breakpoint2 + 1000, breakpoint2 + 1000, exons2[1, "strand"], "", "dummy", exons2[1, "geneID"], exons2[1, "transcript"], "")) } exons1$start <- as.integer(exons1$start) exons1$end <- as.integer(exons1$end) exons2$start <- as.integer(exons2$start) exons2$end <- as.integer(exons2$end) exons1$left <- exons1$start exons1$right <- exons1$end exons2$left <- exons2$start exons2$right <- exons2$end squishedIntronSize <- 200 # hide introns in gene1 cumulativeIntronLength <- 0 previousExonEnd <- -squishedIntronSize for (exon in seq_len(nrow(exons1))) { if (breakpoint1 > previousExonEnd + 1 && breakpoint1 < exons1[exon, "left"]) breakpoint1 <- (breakpoint1 - previousExonEnd) / (exons1[exon, "left"] - previousExonEnd) * squishedIntronSize + previousExonEnd - cumulativeIntronLength if (exons1[exon, "left"] > previousExonEnd) { cumulativeIntronLength <- cumulativeIntronLength + exons1[exon, "left"] - previousExonEnd - squishedIntronSize previousExonEnd <- exons1[exon, "right"] } if (breakpoint1 >= exons1[exon, "left"] && breakpoint1 <= exons1[exon, "right"] + 1) breakpoint1 <- breakpoint1 - cumulativeIntronLength exons1[exon, "left"] <- exons1[exon, "left"] - cumulativeIntronLength exons1[exon, "right"] <- exons1[exon, "right"] - cumulativeIntronLength } # hide introns in gene2 cumulativeIntronLength <- 0 previousExonEnd <- -squishedIntronSize for (exon in seq_len(nrow(exons2))) { if (breakpoint2 > previousExonEnd + 1 && breakpoint2 < exons2[exon, "left"]) breakpoint2 <- (breakpoint2 - previousExonEnd) / (exons2[exon, "left"] - previousExonEnd) * squishedIntronSize + previousExonEnd - cumulativeIntronLength if (exons2[exon, "left"] > previousExonEnd) { cumulativeIntronLength <- cumulativeIntronLength + exons2[exon, "left"] - previousExonEnd - squishedIntronSize previousExonEnd <- exons2[exon, "right"] } if (breakpoint2 >= exons2[exon, "left"] && breakpoint2 <= exons2[exon, "right"] + 1) breakpoint2 <- breakpoint2 - cumulativeIntronLength exons2[exon, "left"] <- exons2[exon, "left"] - cumulativeIntronLength exons2[exon, "right"] <- exons2[exon, "right"] - cumulativeIntronLength } # scale exon sizes to 1 scalingFactor <- max(exons1$right) + max(exons2$right) exons1$left <- exons1$left / scalingFactor exons1$right <- exons1$right / scalingFactor exons2$left <- exons2$left / scalingFactor exons2$right <- exons2$right / scalingFactor breakpoint1 <- breakpoint1 / scalingFactor breakpoint2 <- breakpoint2 / scalingFactor # shift gene2 to the right of gene1 with a little bit of padding gene2Offset <- max(exons1$right) + 0.05 # center fusion horizontally fusionOffset1 <- (max(exons1$right) + gene2Offset) / 2 - ifelse(fusions[fusion, "direction1"] == "downstream", breakpoint1, max(exons1$right) - breakpoint1) fusionOffset2 <- fusionOffset1 + ifelse(fusions[fusion, "direction1"] == "downstream", breakpoint1, max(exons1$right) - breakpoint1) # layout: fusion on top, circos plot on bottom left, protein domains on bottom center, statistics on bottom right layout(matrix(c(1, 1, 1, 2, 3, 4), 2, 3, byrow = TRUE), widths = c(0.9, 1.2, 0.9)) par(mar = c(0, 0, 0, 0)) plot(0, 0, type = "l", xlim = c(-0.12, 1.12), ylim = c(0.4, 1.1), bty = "n", xaxt = "n", yaxt = "n") # vertical coordinates of layers yIdeograms <- 0.84 yBreakpointLabels <- 0.76 yCoverage <- 0.72 yExons <- 0.67 yGeneNames <- 0.58 yFusion <- 0.5 yTranscript <- 0.45 yScale <- 0.407 yTrajectoryBreakpointLabels <- yBreakpointLabels - 0.035 yTrajectoryExonTop <- yExons + 0.03 yTrajectoryExonBottom <- yExons - 0.055 yTrajectoryFusion <- yFusion + 0.03 # draw ideograms if (!is.null(cytobands)) { drawIdeogram("left", min(exons1$left), max(exons1$right), yIdeograms, cytobands, fusions[fusion, "contig1"], fusions[fusion, "breakpoint1"]) drawIdeogram("right", gene2Offset, gene2Offset + max(exons2$right), yIdeograms, cytobands, fusions[fusion, "contig2"], fusions[fusion, "breakpoint2"]) } # draw gene & transcript names text(max(exons1$right) / 2, yGeneNames, fusions[fusion, "gene1"], font = 2, cex = opt$fontSize, adj = c(0.5, 0)) if (fusions[fusion,"site1"] != "intergenic") text(max(exons1$right)/2, yGeneNames-0.01, head(exons1$transcript,1), cex = 0.9 * opt$fontSize, adj = c(0.5, 1)) text(gene2Offset+max(exons2$right) / 2, yGeneNames, fusions[fusion,"gene2"], font = 2, cex = opt$fontSize, adj = c(0.5, 0)) if (fusions[fusion,"site2"] != "intergenic") text(gene2Offset+max(exons2$right) / 2, yGeneNames - 0.01, head(exons2$transcript,1), cex = 0.9 * opt$fontSize, adj = c(0.5, 1)) # if multiple genes in the vicinity are shown, label them if (fusions[fusion,"site1"] == "intergenic") for (gene in unique(exons1$geneName)) { exonsOfGene <- exons1[exons1$geneName == gene & exons1$type != "dummy",] if (any(exonsOfGene$type == "exon")) text(mean(c(min(exonsOfGene$left), max(exonsOfGene$right))), yExons - 0.04, gene, cex = 0.9 * opt$fontSize, adj = c(0.5, 1)) } if (fusions[fusion,"site2"] == "intergenic") for (gene in unique(exons2$geneName)) { exonsOfGene <- exons2[exons2$geneName == gene & exons2$type != "dummy",] if (any(exonsOfGene$type == "exon")) text(gene2Offset + mean(c(min(exonsOfGene$left), max(exonsOfGene$right))), yExons - 0.04, gene, cex = 0.9 * opt$fontSize, adj = c(0.5, 1)) } # label breakpoints text(breakpoint1 + 0.01, yBreakpointLabels - 0.03, paste0("breakpoint\n", fusions[fusion, "display_contig1"], ":", fusions[fusion, "breakpoint1"]), adj = c(1, 0), cex = opt$fontSize) text(gene2Offset + breakpoint2 - 0.01, yBreakpointLabels - 0.03, paste0("breakpoint\n", fusions[fusion, "display_contig2"], ":", fusions[fusion, "breakpoint2"]), adj = c(0, 0), cex = opt$fontSize) # plot gene 1 lines(c(min(exons1$left), max(exons1$right)), c(yExons, yExons), col = darkColor1) for (gene in unique(exons1$geneName)) drawStrand(min(exons1[exons1$geneName == gene,"left"]), max(exons1[exons1$geneName == gene, "right"]), yExons, darkColor1, head(exons1[exons1$geneName == gene, "strand"], 1)) for (exon in seq_len(nrow(exons1))) drawExon(exons1[exon, "left"], exons1[exon, "right"], yExons, opt$color1, exons1[exon, "exonNumber"], exons1[exon, "type"]) # plot gene 2 lines(c(gene2Offset, gene2Offset+max(exons2$right)), c(yExons, yExons), col = darkColor2) for (gene in unique(exons2$geneName)) drawStrand(gene2Offset + min(exons2[exons2$geneName == gene,"left"]), gene2Offset + max(exons2[exons2$geneName == gene,"right"]), yExons, darkColor2, head(exons2[exons2$geneName == gene,"strand"], 1)) for (exon in seq_len(nrow(exons2))) drawExon(gene2Offset+exons2[exon,"left"], gene2Offset+exons2[exon,"right"], yExons, opt$color2, exons2[exon,"exonNumber"], exons2[exon,"type"]) # plot gene1 of fusion if (fusions[fusion,"direction1"] == "downstream") { # plot strands lines(c(fusionOffset1, fusionOffset1 + breakpoint1), c(yFusion, yFusion), col = darkColor1) for (gene in unique(exons1$geneName)) { exonsOfGene <- exons1[exons1$geneName == gene,] if (min(exonsOfGene$start) <= fusions[fusion, "breakpoint1"]) drawStrand(fusionOffset1 + min(exonsOfGene$left), fusionOffset1 + min(breakpoint1, max(exonsOfGene$right)), yFusion, col = darkColor1, exonsOfGene$strand[1]) } # plot exons for (exon in seq_len(nrow(exons1))) if (exons1[exon,"start"] <= fusions[fusion,"breakpoint1"]) drawExon(fusionOffset1 + exons1[exon, "left"], fusionOffset1 + min(breakpoint1, exons1[exon,"right"]), yFusion, opt$color1, exons1[exon,"exonNumber"], exons1[exon,"type"]) # plot trajectories lines(c(0, 0, fusionOffset1), c(yTrajectoryExonTop, yTrajectoryExonBottom, yTrajectoryFusion), col = "red", lty = 2) lines(c(breakpoint1, breakpoint1, fusionOffset1 + breakpoint1), c(yTrajectoryBreakpointLabels, yTrajectoryExonBottom, yTrajectoryFusion), col = "red", lty = 2) } else if (fusions[fusion, "direction1"] == "upstream") # plot strands lines(c(fusionOffset1, fusionOffset2), c(yFusion, yFusion), col = darkColor1) for (gene in unique(exons1$geneName)) { exonsOfGene <- exons1[exons1$geneName == gene, ] if (max(exonsOfGene$end + 1) >= fusions[fusion, "breakpoint1"]) drawStrand(fusionOffset2 - max(exonsOfGene$right) + breakpoint1, min(fusionOffset2, fusionOffset2 - min(exonsOfGene$left) + breakpoint1), yFusion, col = darkColor1, chartr("+-", "-+", exonsOfGene$strand[1])) } # plot exons for (exon in seq_len(nrow(exons1))) { if (exons1[exon, "end"] + 1 >= fusions[fusion, "breakpoint1"]) drawExon(fusionOffset1 + max(exons1$right) - exons1[exon, "right"], min(fusionOffset2, fusionOffset1 + max(exons1$right) - exons1[exon, "left"]), yFusion, opt$color1, exons1[exon, "exonNumber"], exons1[exon, "type"]) # plot trajectories lines(c(max(exons1$right), max(exons1$right), fusionOffset1), c(yTrajectoryExonTop, yTrajectoryExonBottom, yTrajectoryFusion), col = "red", lty = 2) lines(c(breakpoint1, breakpoint1, fusionOffset1 + max(exons1$right) - breakpoint1), c(yTrajectoryBreakpointLabels, yTrajectoryExonBottom, yTrajectoryFusion), col = "red", lty = 2) } # plot gene2 of fusion if (fusions[fusion, "direction2"] == "downstream") { # plot strands lines(c(fusionOffset2, fusionOffset2 + breakpoint2), c(yFusion, yFusion), col = darkColor2) for (gene in unique(exons2$geneName)) { exonsOfGene <- exons2[exons2$geneName == gene,] if (min(exonsOfGene$start) <= fusions[fusion, "breakpoint2"]) drawStrand(max(fusionOffset2, fusionOffset2 + breakpoint2 - max(exonsOfGene$right)), fusionOffset2 + breakpoint2 - min(exonsOfGene$left), yFusion, col = darkColor2, chartr("+-", "-+", exonsOfGene$strand[1])) } # plot exons for (exon in seq_len(nrow(exons2))) if (exons2[exon,"start"] <= fusions[fusion, "breakpoint2"]) drawExon(max(fusionOffset2, fusionOffset2+breakpoint2 - exons2[exon, "right"]), fusionOffset2 + breakpoint2 - exons2[exon, "left"], yFusion, opt$color2, exons2[exon, "exonNumber"], exons2[exon, "type"]) # plot trajectories lines(c(gene2Offset, gene2Offset, fusionOffset2+breakpoint2), c(yTrajectoryExonTop, yTrajectoryExonBottom, yTrajectoryFusion), col = "red", lty = 2) lines(c(gene2Offset + breakpoint2, gene2Offset+breakpoint2, fusionOffset2), c(yTrajectoryBreakpointLabels, yTrajectoryExonBottom, yTrajectoryFusion), col = "red", lty = 2) } else if (fusions[fusion, "direction2"] == "upstream") { # plot strands lines(c(fusionOffset2, fusionOffset2 + max(exons2$right) - breakpoint2), c(yFusion, yFusion), col = darkColor2) for (gene in unique(exons2$geneName)) { exonsOfGene <- exons2[exons2$geneName == gene,] if (max(exonsOfGene$end+1) >= fusions[fusion, "breakpoint2"]) drawStrand(max(fusionOffset2, fusionOffset2 + min(exonsOfGene$left) - breakpoint2), fusionOffset2 + max(exonsOfGene$right) - breakpoint2, yFusion, col = darkColor2, exonsOfGene$strand[1]) } } # plot exons for (exon in seq_len(nrow(exons2))) { if (exons2[exon,"end"] + 1 >= fusions[fusion, "breakpoint2"]) drawExon(max(fusionOffset2, fusionOffset2 + exons2[exon, "left"] - breakpoint2), fusionOffset2 + exons2[exon, "right"] - breakpoint2, yFusion, opt$color2, exons2[exon, "exonNumber"], exons2[exon, "type"]) # plot trajectories lines(c(gene2Offset + max(exons2$right), gene2Offset + max(exons2$right), fusionOffset2 + max(exons2$right) - breakpoint2), c(yTrajectoryExonTop, yTrajectoryExonBottom, yTrajectoryFusion), col = "red", lty = 2) lines(c(gene2Offset + breakpoint2, gene2Offset + breakpoint2, fusionOffset2), c(yTrajectoryBreakpointLabels, yTrajectoryExonBottom, yTrajectoryFusion), col= "red", lty = 2) } # draw scale realScale <- max(exons1$end - exons1$start, exons2$end - exons2$start) mapScale <- max(exons1$right - exons1$left, exons2$right - exons2$left) # choose scale which is closest to desired scale length desiredScaleSize <- 0.2 realScale <- desiredScaleSize / mapScale * realScale mapScale <- desiredScaleSize realScaleOptimalFit <- signif(realScale, 1) # round to most significant digit mapScaleOptimalFit <- realScaleOptimalFit / realScale * mapScale # draw scale line lines(c(0, mapScaleOptimalFit), c(yScale, yScale)) # scale line lines(c(0, 0), c(yScale - 0.007, yScale + 0.007)) # left whisker lines(c(mapScaleOptimalFit, mapScaleOptimalFit), c(yScale - 0.007, yScale + 0.007)) # right whisker # draw units above scale line realScaleThousands <- max(0, min(3, floor(log10(realScaleOptimalFit) / 3))) scaleUnits <- c("bp", "kbp", "Mbp", "Gbp") scaleLabel <- paste(realScaleOptimalFit / max(1, 1000 ^ realScaleThousands), scaleUnits[realScaleThousands + 1]) text(mapScaleOptimalFit / 2, yScale + 0.005, scaleLabel, adj = c(0.5, 0), cex = opt$fontSize * 0.9) text(mapScaleOptimalFit, yScale, " introns not to scale", adj = c(0, 0.5), cex = opt$fontSize * 0.9, font = 3) # draw circos plot par(mar = c(0, 0, 0, 0)) drawCircos(fusion, fusions, cytobands, "medium") par(mar = c(0, 0, 0, 0)) # draw protein domains plot(0, 0, type = "l", xlim = c(-0.1, 1.1), ylim = c(0, 1), bty = "n", xaxt = "n", yaxt = "n") par(xpd = NA) if (!is.null(proteinDomains)) drawProteinDomains(fusions[fusion, ], exons1, exons2, proteinDomains, opt$color1, opt$color2, 0.9) par(xpd = FALSE) # print statistics about supporting alignments plot(0, 0, type = "l", xlim = c(0, 1), ylim = c(0, 1), bty = "n", xaxt = "n", yaxt = "n") text(0, 0.575, "SUPPORTING READ COUNT", font = 2, adj = c(0, 0), cex = opt$fontSize) text(0, 0.525, paste0("Total region count in ", unique(exons1$geneName[exons1$type != "dummy"]), " = ", fusions[fusion, "total_region_count1"], "\n", "Total region count in ", unique(exons2$geneName[exons2$type != "dummy"]), " = ", fusions[fusion, "total_region_count2"], "\n", "Assembly score", " = ", fusions[fusion, "assembly_score"], "\n", "Fusion flag = ", fusions[fusion, "fusion_flag"]), adj = c(0, 1), cex = opt$fontSize) } devNull <- dev.off() message("Done") ### </MAIN> ###
import { useEffect, useState } from 'react' export function useCatImage ({ fact }) { const [imageUrl, setImageUrl] = useState() const CAT_PREFIX_IMAGE_URL = 'https://cataas.com' // Recuperar la imagen cada vez que tenemos una cita nueva useEffect(() => { if (!fact) return const threefirstWords = fact.split(' ', 3).join(' ') // console.log(threefirstWords) fetch(`https://cataas.com/cat/says/${threefirstWords}?size=50&color=red&json=true`) .then(res => res.json()) .then(response => { const { url } = response setImageUrl(url) // console.log(response) // --> revisamos si la URL en este caso no tiene el prefijo https://cataas.com }) }, [fact]) return { imageUrl: `${CAT_PREFIX_IMAGE_URL}${imageUrl}` } } // {imageUrl: 'https:// ...'}
/* * Copyright (c) 2022 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thread> #include "napi/native_api.h" #include "napi/native_node_api.h" #include "uv.h" struct CallbackContext { napi_env env = nullptr; napi_ref callbackRef = nullptr; int retData = 0; }; void callbackTest(CallbackContext* context) { uv_loop_s* loop = nullptr; napi_get_uv_event_loop(context->env, &loop); uv_work_t* work = new uv_work_t; context->retData = 1; work->data = (void*)context; uv_queue_work( loop, work, [](uv_work_t* work) {}, // using callback function back to JS thread [](uv_work_t* work, int status) { CallbackContext* context = (CallbackContext*)work->data; napi_handle_scope scope = nullptr; napi_open_handle_scope(context->env, &scope); if (scope == nullptr) { return; } napi_value callback = nullptr; napi_get_reference_value(context->env, context->callbackRef, &callback); napi_value retArg; napi_create_int32(context->env, context->retData, &retArg); napi_value ret; napi_call_function(context->env, nullptr, callback, 1, &retArg, &ret); napi_delete_reference(context->env, context->callbackRef); napi_close_handle_scope(context->env, scope); if (work != nullptr) { delete work; } delete context; } ); } static napi_value JSTest(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value argv[1] = { 0 }; napi_value thisVar = nullptr; void* data = nullptr; napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); napi_valuetype valueType = napi_undefined; napi_typeof(env, argv[0], &valueType); if (valueType != napi_function) { return nullptr; } auto asyncContext = new CallbackContext(); asyncContext->env = env; napi_create_reference(env, argv[0], 1, &asyncContext->callbackRef); // using callback function on other thread std::thread testThread(callbackTest, asyncContext); testThread.detach(); return nullptr; } /*********************************************** * Module export and register ***********************************************/ static napi_value CallbackExport(napi_env env, napi_value exports) { static napi_property_descriptor desc[] = { DECLARE_NAPI_FUNCTION("test", JSTest) }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); return exports; } // callback module define static napi_module callbackModule = { .nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, .nm_register_func = CallbackExport, .nm_modname = "callback", .nm_priv = ((void*)0), .reserved = { 0 }, }; // callback module register extern "C" __attribute__((constructor)) void CallbackTestRegister() { napi_module_register(&callbackModule); }
import os import time import glob from pathlib import Path import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from tqdm import tqdm from rain import rain def distortion(index_x, index_y, x_dist, y_dist, shape): ''' -- Description: performs the distortion correction according to x_dist and y_dist assumes that x_dist and y_dist are both functions of x and y -- Returns: the distortion corrected pixel coordinates -- Arguments: index_x: the x index of the pixel index_y: the y index of the pixel x_dist: distortion map in x y_dist: distortion map in y ''' # center on pixel x_actual = index_x+0.5 y_actual = index_y+0.5 xpad_width = (1024-shape[1])//2 ypad_width = (1024-shape[0])//2 x_dist = x_dist[ypad_width:-ypad_width,:] x_dist = x_dist[:,xpad_width:-xpad_width] y_dist = y_dist[ypad_width:-ypad_width,:] y_dist = y_dist[:,xpad_width:-xpad_width] return x_actual+x_dist[index_y,index_x], y_actual+y_dist[index_y,index_x] def do_rain(data_dir): # standard way to run #n_cpu = os.cpu_count() n_cpu = 32 kernel='lanczos3_lut' pixel_frac = 1 # pixel fraction, fraction of pixel side length n_div = 1 # number of divisions per pixel n_pad = 0 data_dir = Path(data_dir) for input_path in sorted(data_dir.glob('r_*.fits')): basename = Path(input_path).name output_folder = data_dir.parent / 'rain' output_folder.mkdir(parents=True, exist_ok=True) output_path = output_folder / 'rain_{}'.format(basename) print('Correcting {} -> {}'.format(input_path, output_path)) image = fits.getdata(input_path) header = fits.getheader(input_path) iy,ix = image.shape x_offset = int((1024 - ix)/2) y_offset = int((1024 - iy)/2) xs = np.arange(0,ix,1) ys = np.arange(0,iy,1) grid = np.meshgrid(xs, ys) index_coords = np.stack(grid).T.reshape(-1,2) #bad_pixel_map = fits.getdata('./masks/nirc2mask.fits') bad_pixel_map = None x_dist = fits.getdata('distortion/nirc2_distort_X_pre20150413_v2.fits') y_dist = fits.getdata('distortion/nirc2_distort_Y_pre20150413_v2.fits') new_pc_coords = [] for index_x,index_y in tqdm(index_coords, desc='Generate New Coordinates'): new_pc_coords.append(distortion(index_x, index_y, x_dist, y_dist, image.shape)) time_start = time.time() wet_image, missed_pixels = rain(image, pixel_frac, new_pc_coords, n_div, kernel=kernel, n_pad=n_pad, bad_pixel_map=bad_pixel_map, parallel=True, n_cpu=n_cpu) time_end = time.time() time_diff = time_end - time_start print('Time : {:.3f}'.format(time_diff)) print('Original Image Sum : {:.3f}'.format(np.sum(image))) print('Wet Image Sum : {:.3f}'.format(np.sum(wet_image))) print('Missed Pixels : {:.3f}'.format(missed_pixels)) print('Missed + Wet Image : {:.3f}'.format(missed_pixels+np.sum(wet_image))) print('Writing to {}...'.format(output_path)) hdu = fits.PrimaryHDU(wet_image) hdul = fits.HDUList([hdu]) hdul[0].header = header hdul.writeto(output_path, overwrite=True) if __name__=='__main__': do_rain('/home/jsn/landing/data/2023-08-01/reduced/')
enum Setor { MARKETING = "marketing", VENDAS = "vendas", FINANCEIRO = "financeiro" } type Colaborador = { nome : string, salário:number, setor: Setor, presencial : boolean } const Colaboradores : Colaborador[]= [ { nome: "Marcos", salário: 2500, setor: Setor.MARKETING, presencial: true }, { nome: "Maria" ,salário: 1500, setor: Setor.VENDAS, presencial: false}, { nome: "Salete" ,salário: 2200, setor: Setor.FINANCEIRO, presencial: true}, { nome: "João" ,salário: 2800, setor: Setor.MARKETING, presencial: false}, { nome: "Josué" ,salário: 5500, setor: Setor.FINANCEIRO, presencial: true}, { nome: "Natalia" ,salário: 4700, setor: Setor.VENDAS, presencial: true}, { nome: "Paola" ,salário: 3500, setor: Setor.MARKETING, presencial: true } ] const getMarketing = ((pessoa : Colaborador[]) =>{ return pessoa.filter((item)=>{ return item.setor === "marketing" && item.presencial === true }) }) console.log(getMarketing(Colaboradores))
##################################################### # Camada Física da Computação #Carareto #11/08/2022 #Aplicação #################################################### #esta é a camada superior, de aplicação do seu software de comunicação serial UART. #para acompanhar a execução e identificar erros, construa prints ao longo do código! from enlace import * import time import numpy as np import random # voce deverá descomentar e configurar a porta com através da qual ira fazer comunicaçao # para saber a sua porta, execute no terminal : # python -m serial.tools.list_ports # se estiver usando windows, o gerenciador de dispositivos informa a porta #use uma das 3 opcoes para atribuir à variável a porta usada #serialName = "/dev/ttyACM0" # Ubuntu (variacao de) #serialName = "/dev/tty.usbmodem1411" # Mac (variacao de) serialName = "COM3" # Windows(variacao de) def main(): try: print("Iniciou o main") #declaramos um objeto do tipo enlace com o nome "com". Essa é a camada inferior à aplicação. Observe que um parametro #para declarar esse objeto é o nome da porta. # Ativa comunicacao. Inicia os threads e a comunicação seiral com1 = enlace(serialName) com1.enable() time.sleep(.2) com1.sendData(b'00') time.sleep(1) #Se chegamos até aqui, a comunicação foi aberta com sucesso. Faça um print para informar. print("Abriu a comunicação") #aqui você deverá gerar os dados a serem transmitidos. #seus dados a serem transmitidos são um array bytes a serem transmitidos. Gere esta lista com o #nome de txBuffer. Esla sempre irá armazenar os dados a serem enviados. commands = { 1: [0x00, 0x00, 0x00, 0x00], 2: [0x00, 0x00, 0xFF, 0x00], 3: [0xFF, 0x00, 0x00], 4: [0x00, 0xFF, 0x00], 5: [0x00, 0x00, 0xFF], 6: [0x00, 0xFF], 7: [0xFF, 0x00], 8: [0x00], 9: [0xFF], } n_comandos = random.randint(10, 30) print("Número de comandos a serem enviados: {}" .format(n_comandos)) lista_comandos = [random.randint(1, 9) for _ in range(n_comandos)] txBuffer = bytes() #aqui temos que transformar a lista de inteiros em bytes for co in lista_comandos: b = bytearray([len(commands[co])]+commands[co]) print(b) txBuffer += b tamanho =list(b)[0] print("tamanho do comando: {}" .format(tamanho)) txBuffer += bytes([5]) com1.sendData(txBuffer) txLen = len(txBuffer) # rxBuffer, nRx = com1.getData(txLen) #ESCREVE ARQUIVO CÓPIA # print("Salvando dados no arquivo: ") # txBuffer.write(rxBuffer) # print("meu array de bytes tem tamanho {}" .format(len(txBuffer))) #faça aqui uma conferência do tamanho do seu txBuffer, ou seja, quantos bytes serão enviados. #finalmente vamos transmitir os todos. Para isso usamos a funçao sendData que é um método da camada enlace. #faça um print para avisar que a transmissão vai começar. #tente entender como o método send funciona! #Cuidado! Apenas trasmita arrays de bytes! com1.sendData(np.asarray(txBuffer)) #as array apenas como boa pratica para casos de ter uma outra forma de dados txSize = com1.tx.getStatus() print('enviou = {}' .format(txSize)) # A camada enlace possui uma camada inferior, TX possui um método para conhecermos o status da transmissão # O método não deve estar fincionando quando usado como abaixo. deve estar retornando zero. Tente entender como esse método funciona e faça-o funcionar. #Agora vamos iniciar a recepção dos dados. Se algo chegou ao RX, deve estar automaticamente guardado #Observe o que faz a rotina dentro do thread RX #print um aviso de que a recepção vai começar. print("Recepção de dados iniciada") # rxBuffer, nRx = com1.getData(1) timeout = 5 rx = RX(fisica) tempo_inicial = time.time() tempo_duracao = 0 while com1.rx.getBufferLen() < 1: #print(com1.rx.getBufferLen()) tempo_fim = time.time() tempo_duracao = tempo_fim - tempo_inicial if tempo_fim - tempo_inicial > timeout: print("Time out!") com1.disable() break com1.rx.getBufferLen() rxBuffer, nRx = com1.getData(1) comandos_recebidos = int.from_bytes(rxBuffer, byteorder='big') print(comandos_recebidos) print("Tempo de duração da comunicação: {}" .format(tempo_duracao)) if comandos_recebidos == n_comandos: print("recebeu {} comandos! A quantidade de comandos foi igual." .format(comandos_recebidos)) else: print("Ops! recebeu {} comandos! A quantidade de comandos foi diferente do esperado." .format(comandos_recebidos)) #Será que todos os bytes enviados estão realmente guardadas? Será que conseguimos verificar? #Veja o que faz a funcao do enlaceRX getBufferLen #acesso aos bytes recebidos #txLen = len(txBuffer) #rxBuffer, nRx = com1.getData(txLen) # print("recebeu {} bytes" .format(len(rxBuffer))) '''for i in range(len(rxBuffer)): print("recebeu {}" .format(rxBuffer[i]))''' '''txSize = com1.tx.getStatus() print('enviou = {}' .format(txSize))''' # Encerra comunicação print("-------------------------") print("Comunicação encerrada") print("-------------------------") com1.disable() except Exception as erro: print("ops! :-\\") print(erro) com1.disable() #so roda o main quando for executado do terminal ... se for chamado dentro de outro modulo nao roda if __name__ == "__main__": main()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Resume Upload</title> <style> body { font-family: Arial, sans-serif; text-align: center; margin: 50px; } form { display: flex; flex-direction: column; align-items: center; } input { margin-bottom: 10px; } </style> </head> <body> <h2>Upload Your Resume</h2> <form action="upload.php" method="post" enctype="multipart/form-data"> <label for="resume">Select PDF Resume:</label> <input type="file" name="resume" accept=".pdf" required> <br> <input type="submit" value="Upload"> </form> <?php // Check if the form is submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // Check if the file was uploaded without errors if (isset($_FILES["resume"]) && $_FILES["resume"]["error"] == 0) { $targetDir = "uploads/"; // Specify the directory where you want to store the resumes // Generate a unique filename based on the current timestamp $targetFile = $targetDir . time() . "_" . basename($_FILES["resume"]["name"]); // Check if the file is a PDF $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); if ($fileType == "pdf") { // Move the uploaded file to the specified directory if (move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFile)) { echo "<p style='color: green;'>Resume uploaded successfully!</p>"; } else { echo "<p style='color: red;'>Error uploading the resume.</p>"; } } else { echo "<p style='color: red;'>Please upload a PDF file.</p>"; } } else { echo "<p style='color: red;'>Error uploading the resume.</p>"; } } ?> </body> </html>
import { memo, useCallback, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useTranslation } from "react-i18next"; import { classNames } from "shared/lib/classNames/classNames"; import { Button, ButtonTheme } from "shared/ui/Button/Button"; import { LoginModal } from "features/AuthByUsername"; import { userActions, getUserAuthData } from "../../../entities/User"; import styles from "./Navbar.module.scss"; export const Navbar = memo(() => { const [isAuthModal, setIsAuthModal] = useState(false); const { t } = useTranslation(); const authData = useSelector(getUserAuthData); const dispatch = useDispatch(); console.log(authData); const onToggleModal = useCallback(() => { setIsAuthModal(prev => !prev); }, []); const onLogout = useCallback(() => { dispatch(userActions.logout()); }, [dispatch]); if (authData) { return ( <div className={classNames(styles.navbar, {}, [])}> <Button theme={ButtonTheme.CLEAR_INVERTED} className={styles.links} onClick={onLogout} > {t("Выйти")} </Button> </div> ); } return ( <div className={classNames(styles.navbar, {}, [])}> <Button theme={ButtonTheme.CLEAR_INVERTED} className={styles.links} onClick={onToggleModal} > {t("Войти")} </Button> {isAuthModal && <LoginModal isOpen={isAuthModal} onClose={onToggleModal} />} </div> ); });
import { useState } from "react" import { CartItemProps } from "./CartItem" import { CartItemList } from "./CartItemList" import { cartContext } from "./CartContext" const defaultItems: CartItemProps[] = [ { title: 'Pizza da mãe', description: 'Saborosa pizza caseira feita por sua mãe.', price: 79.90, quantity: 1, image: 'https://images.unsplash.com/photo-1513104890138-7c749659a591?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' }, { title: 'Pizza da mama', description: 'Saborosa pizza caseira feita por sua mãe.', price: 59.90, quantity: 1, image: 'https://images.unsplash.com/photo-1513104890138-7c749659a591?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' }, { title: 'Pizza da mãe', description: 'Saborosa pizza caseira feita por sua mãe.', price: 79.90, quantity: 1, image: 'https://images.unsplash.com/photo-1513104890138-7c749659a591?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' }, { title: 'Pizza da mama', description: 'Saborosa pizza caseira feita por sua mãe.', price: 59.90, quantity: 1, image: 'https://images.unsplash.com/photo-1513104890138-7c749659a591?q=80&w=1770&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D' }, ] export const Cart = () => { const [items, setItems] = useState(defaultItems) const quantTotal = items.reduce((prev, item) => prev + item.quantity, 0) const priceTotal = items.reduce((prev, item) => prev + item.quantity * item.price, 0) return ( <cartContext.Provider value={{ items, setItems }}> <h1>Carrinho de compras</h1> <p>Há {quantTotal} itens no carrinho, totalizando {priceTotal.toLocaleString('pt-br', { style: 'currency', currency: 'BRL'})}.</p> <CartItemList items={items} /> </cartContext.Provider> ) }
#ifndef _HAL_INTERFACES_BASE_OUTPUT_DEVICE_H #define _HAL_INTERFACES_BASE_OUTPUT_DEVICE_H #include <types.h> namespace Debug { //Colors enum Color { Black=0, Blue=1, Green=2, Cyan=3, Red=4, Magenta=5, Orange=6, LightGrey=7, DarkGrey=8, LightBlue=9, LightGreen=10, LightCyan=11, LightRed=12, LightMagenta=13, Yellow=14, White=15 }; //Special control characters enum Special { endl, hex, dec }; //Type of debug output device enum DebugOutputDeviceType { None, Serial //TODO: Add GDB/Debugger/Firewire/USB/UDP/whatnot output }; } namespace Debug { //Baseclass for simple character output devices class BaseOutputDevice { protected: int foregroundColor; int backgroundColor; Special printMode; BaseOutputDevice() { foregroundColor = White; backgroundColor = Black; printMode = hex; } virtual ~BaseOutputDevice() {}; void reverseArray(char* arr); public: //Color management void SetForeground(Color c) { foregroundColor = c; } void SetBackground(Color c) { backgroundColor = c; } Color GetForeground() { return (Color)foregroundColor; } Color GetBackground() { return (Color)backgroundColor; } void PrintString(char *c); void PrintString(const char *c) { PrintString((char*)c); } void PrintHex(uint64_t n); void PrintDec(uint64_t n); void PrintDec(int64_t n); void PrintData(char* start, size_t len); BaseOutputDevice &operator<<(char *c); BaseOutputDevice &operator<<(const char *c); BaseOutputDevice &operator<<(unsigned int i); //BaseOutputDevice &operator<<(int i); BaseOutputDevice &operator<<(Special s); virtual void Clear() = 0; virtual void PrintChar(char c) = 0; }; class NullDebugOutputDevice : public BaseOutputDevice { public: NullDebugOutputDevice() {} ~NullDebugOutputDevice() {} //BaseOutputDevice Methods void PrintChar(char c __attribute__((unused))) {} void Clear() {} }; } #endif
import React, { useState, useEffect } from "react"; import { db } from "../../firebase"; import { collection, getDocs, deleteDoc, doc } from "firebase/firestore"; import styled from "styled-components"; const DeleteData = () => { const [products, setProducts] = useState([]); useEffect(() => { const fetchData = async () => { try { const querySnapshot = await getDocs(collection(db, "products")); const dataList = []; querySnapshot.forEach((doc) => { dataList.push({ id: doc.id, ...doc.data() }); }); setProducts(dataList); } catch (error) { console.error("Error fetching documents: ", error); } }; fetchData(); }, []); const handleDelete = async (id) => { try { await deleteDoc(doc(db, "products", id)); setProducts(products.filter((product) => product.id !== id)); console.log("Document successfully deleted!"); window.alert("Document successfully deleted!"); } catch (error) { console.error("Error removing document: ", error); } }; return ( <StyledTable> <thead> <tr> <th>Title</th> <th>Image</th> <th>Category</th> <th>Content</th> <th>Action</th> </tr> </thead> <tbody> {products.map((item) => ( <tr key={item.id}> <td>{item.title}</td> <td> <img src={item.img} alt="img" width={30} /> </td> <td>{item.category}</td> <td>{item.content}</td> <td> <DeleteButton onClick={() => handleDelete(item.id)}> Delete </DeleteButton> </td> </tr> ))} </tbody> </StyledTable> ); }; export default DeleteData; const StyledTable = styled.table` width: 100%; border-collapse: collapse; th, td { border: 1px solid #dddddd; padding: 8px; text-align: left; } th { background-color: #f2f2f2; } `; const DeleteButton = styled.button` padding: 5px 10px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; `;
package ec2 import ( "context" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/cloudquery/cloudquery/plugins/source/aws/client" "github.com/cloudquery/plugin-sdk/v4/schema" "github.com/cloudquery/plugin-sdk/v4/transformers" ) func InstanceTypes() *schema.Table { tableName := "aws_ec2_instance_types" return &schema.Table{ Name: tableName, Description: `https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceTypeInfo.html`, Resolver: fetchEc2InstanceTypes, Multiplex: client.ServiceAccountRegionMultiplexer(tableName, "ec2"), Transform: transformers.TransformWithStruct(&types.InstanceTypeInfo{}, transformers.WithPrimaryKeyComponents("InstanceType")), Columns: []schema.Column{ client.DefaultAccountIDColumn(true), client.DefaultRegionColumn(true), }, } } func fetchEc2InstanceTypes(ctx context.Context, meta schema.ClientMeta, parent *schema.Resource, res chan<- any) error { cl := meta.(*client.Client) svc := cl.Services(client.AWSServiceEc2).Ec2 paginator := ec2.NewDescribeInstanceTypesPaginator(svc, &ec2.DescribeInstanceTypesInput{}) for paginator.HasMorePages() { page, err := paginator.NextPage(ctx, func(options *ec2.Options) { options.Region = cl.Region }) if err != nil { return err } res <- page.InstanceTypes } return nil }
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <!-- Bootstrap css --> <link rel="stylesheet" th:href="@{https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css}" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous" /> <!-- Custom css --> <link rel="stylesheet" th:href="@{./css/main.css}" /> </head> <body> <!-- Form Section --> <section id="auth-form"> <div class="auth--wrapper"> <nav class="navbar navbar-expand-md px-md-5"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <!-- <div class="collapse navbar-collapse" id="navbarSupportedContent">--> <!-- <ul class="navbar-nav ml-auto">--> <!-- <li class="nav-item">--> <!-- <a class="nav-link" th:href="@{/}">Home</a>--> <!-- </li>--> <!-- <li class="nav-item">--> <!-- <a class="nav-link" th:href="@{/reservation}"--> <!-- >Reservations</a--> <!-- >--> <!-- </li>--> <!-- <li class="nav-item dropdown">--> <!-- <a--> <!-- class="nav-link dropdown-toggle"--> <!-- th:href="@{#}"--> <!-- id="navbarDropdown"--> <!-- role="button"--> <!-- data-toggle="dropdown"--> <!-- aria-haspopup="true"--> <!-- aria-expanded="false"--> <!-- >--> <!-- Dropdown--> <!-- </a>--> <!-- <div--> <!-- class="dropdown-menu dropdown-menu-right"--> <!-- aria-labelledby="navbarDropdown"--> <!-- >--> <!--&lt;!&ndash; <span class="dropdown-item"&ndash;&gt;--> <!--&lt;!&ndash; >Signed in as <b>lemon potter</b></span&ndash;&gt;--> <!--&lt;!&ndash; >&ndash;&gt;--> <!-- <div class="dropdown-divider"></div>--> <!-- <a class="dropdown-item" th:href="@{/loginPage}">Log in</a>--> <!-- <a class="dropdown-item" th:href="@{/signup}">Sign up</a>--> <!-- </div>--> <!-- </li>--> <!-- </ul>--> <!-- </div>--> </nav> <div class="bg-image"> <span> Enjoy personalized recommendations, discounts and much more </span> </div> <div class="form-wrapper"> <div class="form-card"> <h2>Log in to your account</h2> <div class="d-none"> Icons made by <a th:href="@{https://www.flaticon.com/authors/freepik}" title="Freepik" >Freepik</a > from <a th:href="@{https://www.flaticon.com/}" title="Flaticon"> www.flaticon.com</a > </div> <form th:action="@{/login}" method="post" class="form"> <div class="form-group"> <label for="username">Email</label> <input type="text" id="username" name="username" placeholder="Enter your username" class="form-control" /> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" id="password" name="password" placeholder="Enter your password" class="form-control" /> </div> <div class="form-group"> <button type="submit" name="login-user" class="btn"> Log in </button> </div> <div class="alternate-auth"> <span> Don't have an account? <a th:href="@{/signup}">&nbsp;Sign up instead</a> </span> </div> </form> </div> </div> </div> </section> <script th:src="@{https://code.jquery.com/jquery-3.5.1.min.js}" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous" ></script> <script th:src="@{https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js}"></script> <!-- Bootstrap --> <script th:src="@{https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js}" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous" ></script> <!-- Custom --> <script> $(document).ready(function () { $("nav").addClass("navbar-light"); }); </script> </body> </html>
import "./App.css"; import Header from "./assets/components/Header"; import Paragraph from "./assets/components/Paragraph"; import SquareLogo from "./assets/svg/square.png"; import { useState } from "react"; function App() { const [visible, setVisible] = useState(false); const [num, setNum] = useState(0); const messages: Array<string> = [ ":D", "Magnifique !", "Il va trop vite...", "J'ai passé 1 heure à coder ce truc", ]; function randomNumberInRange(min: number, max: number) { return Math.floor(Math.random() * (max - min + 1)) + min; } return ( <> <Header name={"Equitable.net"} /> <div className="flex flex-col items-center justify-center gap-25"> <Paragraph text="Bonjour et bienvenue sur le site web de l'entreprise Equitable.net." marginBot={0} /> <Paragraph text="Cliquez sur le bouton ci-dessous pour voir quelque-chose de très drôle : " marginBot={25} /> <button onClick={() => { setNum(randomNumberInRange(0, messages.length - 1)); setVisible(!visible); }} > Cliquez-moi </button> <div style={{ display: visible ? "block" : "none", padding: 50, }} > <img src={SquareLogo} height={150} width={150} className="logo m-14" alt="Funny Square" /> <Paragraph text={messages[num]} marginBot={0} /> </div> </div> </> ); } export default App;
import React, { useEffect, useState } from "react"; import { NavLink, useNavigate, useParams } from "react-router-dom"; import { useDispatch, useSelector } from "react-redux"; import Rating from "../components/Rating"; import { Col, Row, Image, ListGroup, ListGroupItem, Button, Form, } from "react-bootstrap"; import { listProductDetails } from "../action/productAction"; import Loader from "../components/shared/Loader"; import Message from "../components/shared/Message"; const ProductDetails = () => { const params = useParams(); const navigate = useNavigate(); const [qty, setQty] = useState(1); const dispatch = useDispatch(); const productDetails = useSelector((state) => state.productDetails); const { product, error, loading } = productDetails; useEffect(() => { dispatch(listProductDetails(params.id)); }, [dispatch, params.id]); // add to card function const addToCardHandler = () => { navigate(`/cart/${params.id}?qty=${qty}`); }; return ( <> {loading ? ( <Loader /> ) : error ? ( <Message variant={"danger"}>{error}</Message> ) : ( <div> <NavLink to="/" className="btn btn-light"> <i className="fas fa-arrow-left"></i> &nbsp; GO BACK </NavLink> <Row> <Col md={6}> <Image src={product?.image} alt={product?.name} fluid /> </Col> <Col md={3}> <ListGroup variant="flush"> <ListGroupItem> <h3>{product.name}</h3> </ListGroupItem> <ListGroupItem> <Rating value={product.rating} text={`${product?.numReviews} reviews`} /> </ListGroupItem> <ListGroupItem>Price : ${product.price}</ListGroupItem> <ListGroupItem>{product.description}</ListGroupItem> </ListGroup> </Col> <Col md={3}> <ListGroup> <ListGroupItem> <Row> <Col>Status</Col> <Col> {product.countInStock > 0 ? "In Stock" : "Out of Stock"} </Col> </Row> </ListGroupItem> {product.countInStock > 0 && ( <ListGroupItem> <Row> <Col>Qty</Col> <Form.Control as="select" value={qty} onChange={(e) => { setQty(e.target.value); }} > {[...Array(product.countInStock).keys()].map((x) => ( <option key={x + 1} value={x}> {x} </option> ))} </Form.Control> </Row> </ListGroupItem> )} <ListGroupItem> <Button className=" btn btn-block" type="button" onClick={addToCardHandler} > Add to Cart </Button> </ListGroupItem> </ListGroup> </Col> </Row> </div> )} </> ); }; export default ProductDetails;
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AddProductComponent } from './admin/add-product/add-product.component'; import { AdminHomeComponent } from './admin/admin-home/admin-home.component'; import { CarouselSettingsComponent } from './admin/carousel-settings/carousel-settings.component'; import { CategoryComponent } from './admin/category/category.component'; import { EditProductComponent } from './admin/edit-product/edit-product.component'; import { ViewProductsComponent } from './admin/view-products/view-products.component'; import { LoginComponent } from './auth/login/login.component'; import { SignupComponent } from './auth/signup/signup.component'; import { CartComponent } from './cart/cart.component'; import { AuthGuard } from './guards/auth.guard'; import { HomeComponent } from './home/home.component'; import { ShopsComponent } from './shops/shops.component'; import { SingleProductComponent } from './single-product/single-product.component'; const routes: Routes = [ // localhost:4200 -> localhost:4200/ostukorv // localhost:4200/admin { path: "", component: HomeComponent }, { path: "ostukorv", component: CartComponent }, { path: "poed", component: ShopsComponent }, { path: "toode/:productId", component: SingleProductComponent }, { path: "logi-sisse", component: LoginComponent }, { path: "registreeru", component: SignupComponent }, { path: "admin", canActivateChild: [AuthGuard], children: [ { path: "", component: AdminHomeComponent }, { path: "kategooria", component: CategoryComponent }, { path: "lisa", component: AddProductComponent }, { path: "muuda/:productId", component: EditProductComponent }, { path: "vaata-tooteid", component: ViewProductsComponent }, { path: "karuselli-seaded", component: CarouselSettingsComponent }, ] }, // { path: "**", component: NotFoundComponent }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
// Copyright 2008 Dolphin Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #pragma once #include <cstdarg> #include <cstddef> #include <cstdlib> #include <iomanip> #include <limits> #include <locale> #include <sstream> #include <string> #include <type_traits> #include <vector> #include "Common/CommonTypes.h" #ifdef _MSC_VER #include <filesystem> #define HAS_STD_FILESYSTEM #endif std::string StringFromFormatV(const char* format, va_list args); std::string StringFromFormat(const char* format, ...) #if !defined _WIN32 // On compilers that support function attributes, this gives StringFromFormat // the same errors and warnings that printf would give. __attribute__((__format__(printf, 1, 2))) #endif ; // Cheap! bool CharArrayFromFormatV(char* out, int outsize, const char* format, va_list args); template <size_t Count> inline void CharArrayFromFormat(char (&out)[Count], const char* format, ...) { va_list args; va_start(args, format); CharArrayFromFormatV(out, Count, format, args); va_end(args); } // Good std::string ArrayToString(const u8* data, u32 size, int line_len = 20, bool spaces = true); std::string_view StripWhitespace(std::string_view s); std::string_view StripSpaces(std::string_view s); std::string_view StripQuotes(std::string_view s); std::string ReplaceAll(std::string result, std::string_view src, std::string_view dest); void ReplaceBreaksWithSpaces(std::string& str); void TruncateToCString(std::string* s); bool TryParse(const std::string& str, bool* output); template <typename T, std::enable_if_t<std::is_integral_v<T> || std::is_enum_v<T>>* = nullptr> bool TryParse(const std::string& str, T* output, int base = 0) { char* end_ptr = nullptr; // Set errno to a clean slate. errno = 0; // Read a u64 for unsigned types and s64 otherwise. using ReadType = std::conditional_t<std::is_unsigned_v<T>, u64, s64>; ReadType value; if constexpr (std::is_unsigned_v<T>) value = std::strtoull(str.c_str(), &end_ptr, base); else value = std::strtoll(str.c_str(), &end_ptr, base); // Fail if the end of the string wasn't reached. if (end_ptr == nullptr || *end_ptr != '\0') return false; // Fail if the value was out of 64-bit range. if (errno == ERANGE) return false; using LimitsType = typename std::conditional_t<std::is_enum_v<T>, std::underlying_type<T>, std::common_type<T>>::type; // Fail if outside numeric limits. if (value < std::numeric_limits<LimitsType>::min() || value > std::numeric_limits<LimitsType>::max()) { return false; } *output = static_cast<T>(value); return true; } template <typename T, std::enable_if_t<std::is_floating_point_v<T>>* = nullptr> bool TryParse(std::string str, T* const output) { // Replace commas with dots. std::istringstream iss(ReplaceAll(std::move(str), ",", ".")); // Use "classic" locale to force a "dot" decimal separator. iss.imbue(std::locale::classic()); T tmp; // Succeed if a value was read and the entire string was used. if (iss >> tmp && iss.eof()) { *output = tmp; return true; } return false; } template <typename N> bool TryParseVector(const std::string& str, std::vector<N>* output, const char delimiter = ',') { output->clear(); std::istringstream buffer(str); std::string variable; while (std::getline(buffer, variable, delimiter)) { N tmp = 0; if (!TryParse(variable, &tmp)) return false; output->push_back(tmp); } return true; } std::string ValueToString(u16 value); std::string ValueToString(u32 value); std::string ValueToString(u64 value); std::string ValueToString(float value); std::string ValueToString(double value); std::string ValueToString(int value); std::string ValueToString(s64 value); std::string ValueToString(bool value); template <typename T, std::enable_if_t<std::is_enum<T>::value>* = nullptr> std::string ValueToString(T value) { return ValueToString(static_cast<std::underlying_type_t<T>>(value)); } // Generates an hexdump-like representation of a binary data blob. std::string HexDump(const u8* data, size_t size); // TODO: kill this bool AsciiToHex(const std::string& _szValue, u32& result); std::string TabsToSpaces(int tab_size, std::string str); std::vector<std::string> SplitString(const std::string& str, char delim); std::string JoinStrings(const std::vector<std::string>& strings, const std::string& delimiter); // "C:/Windows/winhelp.exe" to "C:/Windows/", "winhelp", ".exe" // This requires forward slashes to be used for the path separators, even on Windows. bool SplitPath(std::string_view full_path, std::string* path, std::string* filename, std::string* extension); // Converts the path separators of a path into forward slashes on Windows, which is assumed to be // true for paths at various places in the codebase. void UnifyPathSeparators(std::string& path); std::string WithUnifiedPathSeparators(std::string path); // Extracts just the filename (including extension) from a full path. // This requires forward slashes to be used for the path separators, even on Windows. std::string PathToFileName(std::string_view path); bool StringBeginsWith(std::string_view str, std::string_view begin); bool StringEndsWith(std::string_view str, std::string_view end); void StringPopBackIf(std::string* s, char c); size_t StringUTF8CodePointCount(const std::string& str); std::string CP1252ToUTF8(std::string_view str); std::string SHIFTJISToUTF8(std::string_view str); std::string UTF8ToSHIFTJIS(std::string_view str); std::string WStringToUTF8(std::wstring_view str); std::string UTF16BEToUTF8(const char16_t* str, size_t max_size); // Stops at \0 std::string UTF16ToUTF8(std::u16string_view str); std::u16string UTF8ToUTF16(std::string_view str); #ifdef _WIN32 std::wstring UTF8ToWString(std::string_view str); #ifdef _UNICODE inline std::string TStrToUTF8(std::wstring_view str) { return WStringToUTF8(str); } inline std::wstring UTF8ToTStr(std::string_view str) { return UTF8ToWString(str); } #else inline std::string TStrToUTF8(std::string_view str) { return str; } inline std::string UTF8ToTStr(std::string_view str) { return str; } #endif #endif #ifdef HAS_STD_FILESYSTEM std::filesystem::path StringToPath(std::string_view path); std::string PathToString(const std::filesystem::path& path); #endif // Thousand separator. Turns 12345678 into 12,345,678 template <typename I> std::string ThousandSeparate(I value, int spaces = 0) { #ifdef _WIN32 std::wostringstream stream; #else std::ostringstream stream; #endif stream << std::setw(spaces) << value; #ifdef _WIN32 return WStringToUTF8(stream.str()); #else return stream.str(); #endif } /// Returns whether a character is printable, i.e. whether 0x20 <= c <= 0x7e is true. /// Use this instead of calling std::isprint directly to ensure /// the C locale is being used and to avoid possibly undefined behaviour. inline bool IsPrintableCharacter(char c) { return std::isprint(c, std::locale::classic()); } /// Returns whether a character is a letter, i.e. whether 'a' <= c <= 'z' || 'A' <= c <= 'Z' /// is true. Use this instead of calling std::isalpha directly to ensure /// the C locale is being used and to avoid possibly undefined behaviour. inline bool IsAlpha(char c) { return std::isalpha(c, std::locale::classic()); } #ifdef _WIN32 std::vector<std::string> CommandLineToUtf8Argv(const wchar_t* command_line); #endif std::string GetEscapedHtml(std::string html); namespace Common { inline char ToLower(char ch) { return std::tolower(ch, std::locale::classic()); } inline char ToUpper(char ch) { return std::toupper(ch, std::locale::classic()); } void ToLower(std::string* str); void ToUpper(std::string* str); } // namespace Common
import abi from "../utils/BuyMeACoffee.json"; import { ethers } from "ethers"; import Head from "next/head"; import Image from "next/image"; import React, { useEffect, useState } from "react"; import styles from "../styles/Home.module.css"; export default function Home() { // Contract Address & ABI const contractAddress = "0xbbe7a0dE24b7057C4e2d9362986699ef31280936"; const contractABI = abi.abi; // Component state const [currentAccount, setCurrentAccount] = useState(""); const [name, setName] = useState(""); const [message, setMessage] = useState(""); const [memos, setMemos] = useState([]); const onNameChange = (event) => { setName(event.target.value); }; const onMessageChange = (event) => { setMessage(event.target.value); }; // Wallet connection logic const isWalletConnected = async () => { try { const { ethereum } = window; const accounts = await ethereum.request({ method: "eth_accounts" }); console.log("accounts: ", accounts); if (accounts.length > 0) { const account = accounts[0]; console.log("wallet is connected! " + account); } else { console.log("make sure MetaMask is connected"); } } catch (error) { console.log("error: ", error); } }; const connectWallet = async () => { try { const { ethereum } = window; if (!ethereum) { console.log("please install MetaMask"); } const accounts = await ethereum.request({ method: "eth_requestAccounts", }); setCurrentAccount(accounts[0]); } catch (error) { console.log(error); } }; const buyCoffee = async () => { try { const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum, "any"); const signer = provider.getSigner(); const buyMeACoffee = new ethers.Contract( contractAddress, contractABI, signer ); console.log("buying coffee.."); const coffeeTxn = await buyMeACoffee.buyCoffee( name ? name : "anon", message ? message : "Enjoy your coffee!", { value: ethers.utils.parseEther("0.001") } ); await coffeeTxn.wait(); console.log("mined ", coffeeTxn.hash); console.log("coffee purchased!"); // Send mailchain message to ENS Address const recipientAddress = document.querySelector( 'input[name="ensAddress"]' ).value; if (recipientAddress) { const { data, error } = await mailchain.sendMail({ from: "[email protected]", to: [`${recipientAddress}@ethereum.mailchain.xyz`], subject: "Coffee Received", content: { text: `Thank you for buying me a coffee, ${name}!`, html: `<p>Thank you for buying me a coffee, ${name}!</p>`, }, }); if (error) { console.warn("Mailchain error", error); } else { console.log("Mail sent successfully:", data); } } if (error) { console.warn("Mailchain error", error); } else { console.log("Mail sent successfully:", data); } // Clear the form fields. setName(""); setMessage(""); } } catch (error) { console.log(error); } }; // Function to fetch all memos stored on-chain. const getMemos = async () => { try { const { ethereum } = window; if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const buyMeACoffee = new ethers.Contract( contractAddress, contractABI, signer ); console.log("fetching memos from the blockchain.."); const memos = await buyMeACoffee.getMemos(); console.log("fetched!"); setMemos(memos); } else { console.log("Metamask is not connected"); } } catch (error) { console.log(error); } }; useEffect(() => { let buyMeACoffee; isWalletConnected(); getMemos(); // Create an event handler function for when someone sends // us a new memo. const onNewMemo = (from, timestamp, name, message) => { console.log("Memo received: ", from, timestamp, name, message); setMemos((prevState) => [ ...prevState, { address: from, timestamp: new Date(timestamp * 1000), message, name, }, ]); }; const { ethereum } = window; // Listen for new memo events. if (ethereum) { const provider = new ethers.providers.Web3Provider(ethereum, "any"); const signer = provider.getSigner(); buyMeACoffee = new ethers.Contract(contractAddress, contractABI, signer); buyMeACoffee.on("NewMemo", onNewMemo); } return () => { if (buyMeACoffee) { buyMeACoffee.off("NewMemo", onNewMemo); } }; }, []); return ( <div className={styles.container}> <Head> <title>Buy Patrick a Coffee!</title> <meta name="description" content="Tipping site" /> <link rel="icon" href="/favicon.ico" /> </Head> <main className={styles.main}> <h1 className={styles.title}>Buy Patrick a Coffee!</h1> {currentAccount ? ( <div> <form> <div> <label>Name</label> <br /> <input id="name" type="text" placeholder="anon" onChange={onNameChange} /> </div> <br /> <div> <label>Send Patrick a message</label> <br /> <textarea rows={3} placeholder="Enjoy your coffee!" id="message" onChange={onMessageChange} required ></textarea> </div> <div> <button type="button" onClick={buyCoffee}> Send 1 Coffee for 0.001ETH </button> </div> </form> </div> ) : ( <button onClick={connectWallet}> Connect your wallet </button> )} {currentAccount && ( <> <div> <h3>Want to Receive a Receipt to your ENS Address?</h3> </div> <form> <div> <label>Enter your ENS Address:</label> <input type="text" name="ensAddress" /> </div> <br /> </form> </> )} <div> <p> A Receipt will be sent directly to your ENS Address. How does that work? We use a specialized web3 communication layer called{" "} <b> <a href="https://mailchain.com/" target="_blank" rel="noreferrer"> Mailchain </a> </b> . If you don't have a mailchain account, don't worry. You can finish your transaction, set up a free mailchain account, and your receipt will generate after setting up your account. Its that easy. </p> </div> </main> {currentAccount && <h1>Memos received</h1>} {currentAccount && memos.map((memo, idx) => { return ( <div key={idx} style={{ border: "2px solid", borderRadius: "5px", padding: "5px", margin: "5px", }} > <p style={{ fontWeight: "bold" }}>"{memo.message}"</p> <p> From: {memo.name} at {memo.timestamp.toString()} </p> </div> ); })} <footer className={styles.footer}> <a href="https://alchemy.com/?a=roadtoweb3weektwo" target="_blank" rel="noopener noreferrer" > Created by @PSkinnerTech for a Maillchain Hackathon </a> </footer> </div> ); }
use crate::server_configuration::ServerConfig; use log::debug; use std::io; use std::net::TcpStream; /// /// function to connect on a server with config /// /// # Return /// stream to communicate with /// /// # Throws /// An error if connection isn't establish /// pub fn connect_to_server(server_config: &ServerConfig) -> io::Result<TcpStream> { let stream = TcpStream::connect(format!( "{}:{}", server_config.ip_address, server_config.port ))?; debug!( "Connected to server {} on {}", server_config.ip_address, server_config.port ); Ok(stream) }
import java.util.ArrayList; import java.util.List; // Observer interface interface Observer { void update(float temperature, float humidity, float pressure); } // Subject interface interface Subject { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObservers(); } // DisplayElement interface interface DisplayElement { void display(); } // WeatherData implementing Subject interface (Singleton pattern) class WeatherData implements Subject { private static WeatherData instance; private List<Observer> observers; private float temperature; private float humidity; private float pressure; private WeatherData() { observers = new ArrayList<>(); } public static synchronized WeatherData getInstance() { if (instance == null) { instance = new WeatherData(); } return instance; } public void registerObserver(Observer o) { observers.add(o); } public void removeObserver(Observer o) { int i = observers.indexOf(o); if (i >= 0) { observers.remove(i); } } public void notifyObservers() { for (Observer observer : observers) { observer.update(temperature, humidity, pressure); } } public void measurementsChanged() { notifyObservers(); } public void setMeasurements(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } } // Display elements implementing Observer and DisplayElement interfaces class CurrentConditionsDisplay implements Observer, DisplayElement { private float temperature; private float humidity; private Subject weatherData; public CurrentConditionsDisplay(Subject weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); } public void update(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; display(); } public void display() { System.out.println("Current conditions: " + temperature + "F degrees and " + humidity + "% humidity"); } } class PressureDisplay implements Observer, DisplayElement { private float pressure; private Subject weatherData; public PressureDisplay(Subject weatherData) { this.weatherData = weatherData; weatherData.registerObserver(this); } public void update(float temperature, float humidity, float pressure) { this.pressure = pressure; display(); } public void display() { System.out.println("Current pressure: " + pressure + " Pa"); } } // Factory method to create display elements class DisplayElementFactory { public static DisplayElement createDisplayElement(String type, Subject weatherData) { switch (type) { case "current": return new CurrentConditionsDisplay(weatherData); case "pressure": return new PressureDisplay(weatherData); default: return null; } } } public class WeatherStation { public static void main(String[] args) { WeatherData weatherData = WeatherData.getInstance(); // Create display elements using the factory method DisplayElement currentConditionsDisplay = DisplayElementFactory.createDisplayElement("current", weatherData); DisplayElement pressureDisplay = DisplayElementFactory.createDisplayElement("pressure", weatherData); // Simulate new weather measurements weatherData.setMeasurements(80, 65, 30.4f); weatherData.setMeasurements(82, 70, 29.2f); weatherData.setMeasurements(78, 90, 29.2f); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="./css/bootstrap.min.css"> <link rel="stylesheet" href="style.css"> <title>Usuarios</title> </head> <body> <header> <div class="container"> <nav class="navbar navbar-expand-lg navbar-dark"> <div class="container-fluid"> <a class="navbar-brand" href="index.html">DoggyQuo</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" aria-current="page" href="servicios.html">Servicios</a> </li> <li class="nav-item"> <a class="nav-link" href="formulario.html">Citas</a> </li> <li class="nav-item"> <a class="nav-link" href="Testimonios.html">Testimonios</a> </li> <li class="nav-item"> <a class="nav-link" href="usuarios.html">Usuarios</a> </li> </ul> <ul class="navbar-nav ms-auto"> <li class="nav-item" id="registroBtn"> <a class="nav-link" aria-current="page" href="registro.html">Registrarse</a> </li> <li class="nav-item" id="inicioSesionBtn"> <a class="nav-link" aria-current="page" href="login.html">Iniciar Sesión</a> </li> <li class="nav-item" id="cerrarSesionBtn" style="display: none;"> <button class="btn btn-link nav-link" id="cerrar-sesion">Cerrar Sesión</button> </li> </ul> </div> </div> </nav> </div> </header> <section class="usuarios"> <h2 class="my-5 text-center">Tabla de usuarios</h2> <div class="container"> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Nombre</th> <th>Contraseña</th> <th>Correo</th> <th>Acciones</th> </tr> </thead> <tbody id="tabla-usuarios"></tbody> </table> </div> </section> <footer class="page-footer text-center font-small mt-4 wow fadeIn"> <div class="footer-copyright py-3 text-white"> © 2023 DoggyQuo. Todos los derechos reservados </div> </footer> <script src="./js/jquery-3.7.0.min.js"></script> <script src="./js/bootstrap.bundle.min.js"></script> <script> $(document).ready(function() { function getCookie(name) { var cookieArr = document.cookie.split(";"); for (var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); var cookieName = cookiePair[0].trim(); if (cookieName === name) { return decodeURIComponent(cookiePair[1]); } } return null; } // Verificar si la cookie de sesión está presente var sesionIniciada = getCookie("sesionIniciada"); if (sesionIniciada) { // Mostrar el botón de "Cerrar Sesión" $("#inicioSesionBtn").hide(); $("#registroBtn").hide(); $("#cerrarSesionBtn").show(); } else { // Mostrar los botones de "Registrarse" e "Iniciar Sesión" $("#inicioSesionBtn").show(); $("#registroBtn").show(); $("#cerrarSesionBtn").hide(); } // Función para eliminar la cookie de sesión function deleteCookie(name) { document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; } // Evento click del botón "Cerrar Sesión" $("#cerrarSesionBtn").click(function () { deleteCookie("sesionIniciada"); alert("Sesión cerrada exitosamente"); window.location.href = "login.html"; }); $.ajax({ url: "https://localhost:7235/api/CRUD", type: "GET", dataType: "json", success: function(data) { var tablaUsuarios = $("#tabla-usuarios"); tablaUsuarios.empty(); $.each(data, function(index, usuario) { var fila = "<tr>" + "<td>" + usuario.id + "</td>" + "<td>" + usuario.user_nombre + "</td>" + "<td>" + usuario.contra + "</td>" + "<td>" + usuario.correo + "</td>" + "<td>" + "<button class='btn btn-primary editar-usuario' data-id='" + usuario.id + "'>Editar</button> " + "<button class='btn btn-danger eliminar-usuario' data-id='" + usuario.id + "'>Eliminar</button>" + "</td>" + "</tr>"; tablaUsuarios.append(fila); }); }, error: function() { console.log("Error al obtener los usuarios"); } }); $(document).on("click", ".editar-usuario", function() { var filaUsuario = $(this).closest("tr"); var idUsuario = $(this).data("id"); var nombreActual = filaUsuario.find("td:nth-child(2)").text(); var contraActual = filaUsuario.find("td:nth-child(3)").text(); var correoActual = filaUsuario.find("td:nth-child(4)").text(); var formularioEdicion = "<td>" + idUsuario + "</td>" + "<td><input type='text' class='form-control nombre' value='" + nombreActual + "'></td>" + "<td><input type='text' class='form-control contra' value='" + contraActual + "'></td>" + "<td><input type='text' class='form-control correo' value='" + correoActual + "'></td>" + "<td>" + "<button class='btn btn-success guardar-edicion' data-id='" + idUsuario + "'>Guardar</button> " + "<button class='btn btn-secondary cancelar-edicion'>Cancelar</button>" + "</td>"; filaUsuario.html(formularioEdicion); }); $(document).on("click", ".guardar-edicion", function() { var filaUsuario = $(this).closest("tr"); var idUsuario = $(this).data("id"); var nuevoNombre = filaUsuario.find("input.nombre").val(); var nuevaContra = filaUsuario.find("input.contra").val(); var nuevoCorreo = filaUsuario.find("input.correo").val(); var usuario = { user_nombre: nuevoNombre, contra: nuevaContra, correo: nuevoCorreo }; $.ajax({ url: 'https://localhost:7235/api/CRUD/' + idUsuario, type: 'PUT', data: JSON.stringify(usuario), contentType: 'application/json', success: function(response) { var nuevaFila = "<td>" + idUsuario + "</td>" + "<td>" + nuevoNombre + "</td>" + "<td>" + nuevaContra + "</td>" + "<td>" + nuevoCorreo + "</td>" + "<td>" + "<button class='btn btn-primary editar-usuario' data-id='" + idUsuario + "'>Editar</button> " + "<button class='btn btn-danger eliminar-usuario' data-id='" + idUsuario + "'>Eliminar</button>" + "</td>"; filaUsuario.html(nuevaFila); console.log(response); }, error: function(error) { console.error(error); } }); }); $(document).on("click", ".cancelar-edicion", function() { location.reload(); }); $(document).on("click", ".eliminar-usuario", function() { var idUsuario = $(this).data("id"); var fila = $(this).closest("tr"); $.ajax({ url: 'https://localhost:7235/api/CRUD/' + idUsuario, type: 'DELETE', success: function(response) { alert("Se ha eliminado el registro de forma correcta."); fila.remove(); }, error: function(error) { alert("No se eliminó el registro."); } }); }); }); </script> </body> </html>
<!DOCTYPE html> <html> <head> <title>DOM Manipulation</title> <script src="path/to/your/script.js"></script> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <style> .box { width: 200px; height: 200px; background-color: lightblue; display: flex; justify-content: center; align-items: center; } .highlight { background-color: yellow; } .darkmode{ background-color: black; color: lightblue; } .addClass { font-size: 24px; } </style> </head> <body> <h1 id="heading">DOM Manipulation Example</h1> <div class="box" id="content"> <p>This is a paragraph.</p> <section> <h1>Hello World</h1> <h2 id="us-company">Faang</h2> <ul id="faang" class="tech"> <li>Facebook</li> <li>Apple</li> <li>Amazon</li> <li>Netflix</li> <li>Google</li> </ul> </section> <form action=""> <label for="name">Name</label> <input type="text"> <br> <br> <button id="button">Click Me</button> </form> </div> <h1>Fruits</h1> <ul id="fruits" class="eat"> <li class="item">Mango</li> <li class="item">Strawberry</li> <li class="item">Banana</li> <li class="item">Apple</li> </ul> <h1 class="properties">Child Elements</h1> <ul id="list-of-list" class="child-lists"> <li class="vegetable">List A</li> <li class="vegetable">List B</li> <li class="vegetable">List C</li> <li class="vegetable">List D</li> </ul> <h1 id="replace">Nodes</h1> <ul class="parent"> <!-- Im comment node --> <li class="child">List 1</li> <li class="child">List 2</li> <li class="child">List 3</li> <li class="child">List 4</li> </ul> <h1 class="replaceHim">Recreate Whole</h1> <ul class="add-items"> <li>Google <button type="button" class="btn btn-primary">Open</button> </li> </ul> <div class="box" id="myBox"> <p class="addClass">Working with Class and Styles</p> </div> <button class="add">Add Class</button> <button class="remove">Remove Class</button> <button class="toggle">Toggle Class</button> <button class="replace">Replace Class</button> <button class="change">Change Styles</button> <script src="/javascript/09 DOM/code/02_search-nodes.js"></script> <script src="/javascript/09 DOM/code/03_properties.js"></script> <script src="/javascript/09 DOM/code/04_create-element.js"></script> <script src="/javascript/09 DOM/code/05_get-whole-ele.js"></script> <script src="/javascript/09 DOM/code/06_insert-element.js"></script> <script src="/javascript/09 DOM/code/08_remove.js"></script> <script src="/javascript/09 DOM/code/09_class-style.js"></script> </body> </html>
#include <stdint.h> #include <stddef.h> #include "salsa20.h" // Implements DJB's definition of '<<<' static uint32_t rotl(uint32_t value, int shift) { return (value << shift) | (value >>(32 - shift)); } static void s20_quarterround(uint32_t *y0, uint32_t *y1, uint32_t *y2, uint32_t *y3) { *y1 = *y1 ^ rotl(*y0 + *y3, 7); *y2 = *y2 ^ rotl(*y1 + *y0 ,9); *y3 = *y3 ^ rotl(*y2 + *y1, 13); *y0 = *y0 ^ rotl(*y3 + *y2, 18); } static void s20_rowround(uint32_t y[static 16]) { s20_quarterround(&y[0], &y[1], &y[2], &y[3]); // 0000 , 0001, 0010, 0011 s20_quarterround(&y[5], &y[6], &y[7], &y[4]); // 0101 , 0110, 0111, 0100 s20_quarterround(&y[10], &y[11], &y[8], &y[9]); // 1010 , 1011, 1000, 1001 s20_quarterround(&y[15], &y[12], &y[13], &y[14]); // 1111, 1100, 1101, 1110 // Binär geordnet ! } static void s20_columnround(uint32_t x[static 16]) { s20_quarterround(&x[0], &x[4], &x[8], &x[12]); // 0000, 0100, 1000, 1100 //erste 2 bitziffern ändern sich + 00 s20_quarterround(&x[5], &x[9], &x[13], &x[1]); // 0101, 1001, 1101, 0001 //erste 2 bitziffern ändern sich + 01 s20_quarterround(&x[10], &x[14], &x[2], &x[6]); // 1010, 1110, 0010, 0110 //erste 2 bitziffern ändern sich + 10 s20_quarterround(&x[15], &x[3], &x[7], &x[11]); // 1111, 0011, 0111, 1011 //erste 2 bitziffern ändern sich + 11 } static void s20_doubleround(uint32_t x[static 16]) { s20_columnround(x); s20_rowround(x); } //creates a little endian word from 4 bytes pointed to by b static uint32_t s20_littleendian(uint8_t *b) { return b[0] + ((uint_fast16_t) b[1] << 8) + ((uint_fast32_t) b[2] << 16) + ((uint_fast32_t) b[3] << 24); } //moves the little endian word into the 4 bytes pointed to by b static void s20_rev_littleendian(uint8_t *b, uint32_t w) { b[0] = w; b[1] = w >> 8; b[2] = w >> 16; b[3] = w >> 24; } // The core funtion of Salsa20 static void s20_hash(uint8_t seq[static 64]) { int i; uint32_t x[16]; uint32_t z[16]; //create two copies of the state in little endian format //first copy is hashed together //second copy is added to first (word by word) for (i = 0; i < 16; ++i) x[i] = z[i] = s20_littleendian(seq +(4 * i)); for (i = 0; i < 16; ++i) { z[i] += x[i]; s20_rev_littleendian(seq + (4 * i), z[i]); } } // s20_hash // The 16-byte (128-bit) key expansion function static void s20_expand16(uint8_t *k, uint8_t n[static 16], uint8_t keystream[static 64]) { int i, j; // The constants specified by the Salsa20 specification, 'tau' // expand 16-byte k uint8_t t[4][4] = { { 'e', 'x', 'p', 'a' }, { 'n', 'd', ' ', '1' }, { '6', '-', 'b', 'y' }, { 't', 'e', ' ', 'k' } }; // Copy all 'tau' into correct spots in our keystream block for (i = 0; i < 64; i+=20) for (j = 0; j < 4; ++j) keystream[i +j] = t[i / 20][j]; // Copy the key and the nonce into the keystream block for (i = 0; i < 16; ++i) { keystream[4+i] = k[i]; keystream[44+i] = k[i]; keystream[24+i] = k[i]; } s20_hash(keystream); } // The 32-byte (256-bit) key expansion function static void s20_expand32(uint8_t *k, uint8_t n[static 16], uint8_t keystream[static 64]) { int i, j; // The constants specified by the Salsa20 specification, 'tau' // expand 32-byte k uint8_t o[4][4] = { { 'e', 'x', 'p', 'a' }, { 'n', 'd', ' ', '3' }, { '2', '-', 'b', 'y' }, { 't', 'e', ' ', 'k' } }; // Copy all 'sig' into correct spots in our keystream block for (i = 0; i < 64; i+=20) for (j = 0; j < 4; ++j) keystream[i +j] = o[i / 20][j]; // Copy the key and the nonce into the keystream block for (i = 0; i < 16; ++i) { keystream[4+i] = k[i]; keystream[44+i] = k[i+16]; keystream[24+i] = n[i]; } s20_hash(keystream); } // Performs up to 2^32 -1 bytes of encryption/decryption under a // 128 or 256- bit key and 64 byte nonce enum s20_status_t s20_crypt(uint8_t *key, enum s20_keylen_t keylen, uint8_t nonce[static 8], uint32_t si, uint8_t *buf, uint32_t buflen) { uint8_t keystream[64]; // 'n' is the 8-byte nonce (unique message number) concatenated // with the per-block 'counter' value (4 bytes in our case, 8 bytes standard). // We leave the high 4 bytes set to zero because we permit only a 32- bit int // from stram idx and length uint32_t n[16] = { 0 }; uint32_t i; // Pick an expansion function based on key size void (*expand) (uint8_t *, uint8_t *, uint8_t *) = NULL; if (keylen == S20_KEYLEN_256) expand = s20_expand32; if (keylen == S20_KEYLEN_128) expand = s20_expand16; // If any of the parameters we received are invalid if ( expand == NULL || key == NULL || nonce == NULL || buf == NULL) return S20_FAILURE; // Set up the low 8 bytes of n with the unique message number for (i = 0; i < 8; ++i) n[i] = nonce[i]; // If we're not on block boundr, compute the first keystream block // This will make the primary loop below cleaner if (si % 64 != 0) { //set the second to highest 4 bytes of n to the block number s20_rev_littleendian(n+8, si / 64); // Expand the key with n and hash to produce a keystream block (*expand)(key, n, keystream); } // Walk over the plaintext byte by byte, xoring the keystream with // the plaintext and producing new keystream blocks as needed for (i = 0; i < buflen; ++i) { // If we've used up our entire keystream block (or have just begun // and happen to be on a block boundary), produce keystream block if ((si +i) % 64 == 0) { s20_rev_littleendian(n+8, ((si +i )/ 64)); (*expand)(key,n,keystream); } //xor the byte of plaintext with one byte of keystream buf[i] ^= keystream[(si +i) % 64]; } return S20_SUCCESS; }
from django.db import models from users.models import User # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) discription = models.TextField(null=True,blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.title} by {self.author.username}'
import { AfterViewInit, Component, ContentChild, DestroyRef, inject, Inject, OnInit } from '@angular/core'; import { VexLayoutService } from '@vex/services/vex-layout.service'; import { MatSidenavContainer, MatSidenavModule } from '@angular/material/sidenav'; import { Event, NavigationEnd, Router, RouterOutlet, Scroll } from '@angular/router'; import { filter, map, startWith, withLatestFrom } from 'rxjs/operators'; import { combineLatest, Observable } from 'rxjs'; import { checkRouterChildsData } from '@vex/utils/check-router-childs-data'; import { AsyncPipe, DOCUMENT, NgIf, NgTemplateOutlet } from '@angular/common'; import { VexConfigService } from '@vex/config/vex-config.service'; import { SearchComponent } from '../components/toolbar/search/search.component'; import { VexProgressBarComponent } from '@vex/components/vex-progress-bar/vex-progress-bar.component'; import { isNil } from '@vex/utils/is-nil'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { VexConfig } from '@vex/config/vex-config.interface'; @Component({ selector: 'vex-base-layout', templateUrl: './base-layout.component.html', styleUrls: ['./base-layout.component.scss'], standalone: true, imports: [ VexProgressBarComponent, SearchComponent, MatSidenavModule, NgTemplateOutlet, RouterOutlet, AsyncPipe, NgIf ] }) export class BaseLayoutComponent implements OnInit, AfterViewInit { config$: Observable<VexConfig> = this.configService.config$; /** * Check if footer should be visible */ isFooterVisible$ = combineLatest([ /** * Check if footer is enabled in the config */ this.configService.config$.pipe(map((config) => config.footer.visible)), /** * Check if footer is enabled on the current route */ this.router.events.pipe( filter((event) => event instanceof NavigationEnd), startWith(null), map(() => checkRouterChildsData( this.router.routerState.root.snapshot, (data) => data.footerVisible ?? true ) ) ) ]).pipe( map(([configEnabled, routeEnabled]) => { if (isNil(routeEnabled)) { return configEnabled; } return configEnabled && routeEnabled; }) ); sidenavCollapsed$ = this.layoutService.sidenavCollapsed$; isDesktop$ = this.layoutService.isDesktop$; scrollDisabled$ = this.router.events.pipe( filter((event) => event instanceof NavigationEnd), startWith(null), map(() => checkRouterChildsData( this.router.routerState.root.snapshot, (data) => data.scrollDisabled ?? false ) ) ); searchOpen$ = this.layoutService.searchOpen$; @ContentChild(MatSidenavContainer, { static: true }) sidenavContainer!: MatSidenavContainer; private readonly destroyRef: DestroyRef = inject(DestroyRef); constructor( private readonly layoutService: VexLayoutService, private readonly configService: VexConfigService, private readonly router: Router, @Inject(DOCUMENT) private readonly document: Document ) {} ngOnInit() { /** * Open sidenav on desktop when layout is not vertical * Close sidenav on mobile or when layout is vertical */ combineLatest([ this.isDesktop$, this.configService.select((config) => config.layout === 'vertical') ]) .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe(([isDesktop, isVerticalLayout]) => { if (isDesktop && !isVerticalLayout) { this.layoutService.openSidenav(); } else { this.layoutService.closeSidenav(); } }); /** * Mobile only: * Close Sidenav after Navigating somewhere (e.g. when a user clicks a link in the Sidenav) */ this.router.events .pipe( filter((event) => event instanceof NavigationEnd), withLatestFrom(this.isDesktop$), filter(([event, matches]) => !matches), takeUntilDestroyed(this.destroyRef) ) .subscribe(() => this.layoutService.closeSidenav()); } ngAfterViewInit(): void { /** * Enable Scrolling to specific parts of the page using the Router */ this.router.events .pipe( filter<Event, Scroll>((e: Event): e is Scroll => e instanceof Scroll), takeUntilDestroyed(this.destroyRef) ) .subscribe((e) => { if (e.position) { // backward navigation this.sidenavContainer.scrollable.scrollTo({ start: e.position[0], top: e.position[1] }); } else if (e.anchor) { // anchor navigation const scroll = (anchor: HTMLElement) => this.sidenavContainer.scrollable.scrollTo({ behavior: 'smooth', top: anchor.offsetTop, left: anchor.offsetLeft }); let anchorElem = this.document.getElementById(e.anchor); if (anchorElem) { scroll(anchorElem); } else { setTimeout(() => { if (!e.anchor) { return; } anchorElem = this.document.getElementById(e.anchor); if (!anchorElem) { return; } scroll(anchorElem); }, 100); } } else { // forward navigation this.sidenavContainer.scrollable.scrollTo({ top: 0, start: 0 }); } }); } }
pragma solidity 0.8.17; // SPDX-License-Identifier: GPL-3.0-only import "./utils/BaseTest.sol"; import {DelegationNodeStatus} from "../../contracts/types/DelegationNodeStatus.sol"; contract DelegationManagerTest is BaseTest { int256 private index; address private nodeID; address private nodeOp; uint256 private ggpBondAmt; uint256 private requestedDelegationAmt; uint256 private duration; uint128 private immutable MIN_DELEGATION_AMT = 25 ether; address private bob; function setUp() public override { super.setUp(); registerMultisig(rialto1); nodeOp = getActorWithTokens(3_000_000 ether, 3_000_000 ether); bob = getActor(2); } function testFullCycle_NotMinipool() public { //make sure that there is a balance in the ggavax contract that can be used for delegation funds vm.deal(bob, 3000000 ether); vm.prank(bob); ggAVAX.depositAVAX{value: 3000000 ether}(); assertEq(bob.balance, 0); //create the delegation node (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); //act as the delegation node and request delegation vm.startPrank(nodeOp); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); index = delegationMgr.getIndexOf(nodeID); //check that the transfer of ggpbond from node op to the contract worked assertEq(vault.balanceOfToken("DelegationManager", ggp), ggpBondAmt); //check that the storage items are correct and the registration was successful address nodeID_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".nodeID"))); assertEq(nodeID_, nodeID); uint256 ggpBondAmt_ = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".ggpBondAmt"))); assertEq(ggpBondAmt_, ggpBondAmt); uint256 status = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".status"))); assertEq(status, uint256(DelegationNodeStatus.Prelaunch)); address nodeOp_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".owner"))); assertEq(nodeOp_, nodeOp); vm.stopPrank(); //start acting as rialto vm.startPrank(rialto1); //start delegation as rialto delegationMgr.claimAndInitiateDelegation(nodeID); //check that all the funds were transfered successfully to rialto assertEq(rialto1.balance, requestedDelegationAmt); //rialto records delegation has started delegationMgr.recordDelegationStart(nodeID, block.timestamp); //testing that if we give an incorrect end time that it will trigger revert vm.expectRevert(DelegationManager.InvalidEndTime.selector); delegationMgr.recordDelegationEnd{value: requestedDelegationAmt}(nodeID, block.timestamp, 0 ether, 0 ether); skip(duration); //testing that if Rialto doesnt send back the original amt of delegation funds that it will trigger revert vm.expectRevert(DelegationManager.InvalidEndingDelegationAmount.selector); delegationMgr.recordDelegationEnd{value: 0 ether}(nodeID, block.timestamp, 0 ether, 0 ether); // // // Give rialto the rewards it needs uint256 rewards = 10 ether; deal(rialto1, rialto1.balance + rewards); //testing that if we give the incorrect amt of rewards it will revert vm.expectRevert(DelegationManager.InvalidEndingDelegationAmount.selector); delegationMgr.recordDelegationEnd{value: rialto1.balance}(nodeID, block.timestamp, 9 ether, 0 ether); //should test that if ther are no rewards then ggp will be slashed? //ggavax has some funds in it from bob uint256 priorBalance_ggAVAX = wavax.balanceOf(address(ggAVAX)); //Is not a minipool, so no rewards for the validator // 10% rewards uint256 delegatorRewards = (requestedDelegationAmt * 10) / 100; uint256 delegationAndRewardsTotal = requestedDelegationAmt + delegatorRewards; delegationMgr.recordDelegationEnd{value: delegationAndRewardsTotal}(nodeID, block.timestamp, delegatorRewards, 0 ether); assertEq((wavax.balanceOf(address(ggAVAX)) - priorBalance_ggAVAX), delegationAndRewardsTotal); vm.stopPrank(); //test that the node op can withdraw the funds they are due vm.startPrank(nodeOp); uint256 priorBalance_ggp = ggp.balanceOf(nodeOp); delegationMgr.withdrawRewardAndBondFunds(nodeID); assertEq((ggp.balanceOf(nodeOp) - priorBalance_ggp), ggpBondAmt); } function testFullCycle_WithMinipool() public { uint256 depositAmt = 1000 ether; uint128 ggpStakeAmt = 100 ether; uint256 avaxAssignmentRequest = 1000 ether; //make sure that there is a balance in the ggavax contract that can be used for delegation funds vm.deal(bob, 3000000 ether); vm.prank(bob); ggAVAX.depositAVAX{value: 3000000 ether}(); assertEq(bob.balance, 0); //create minipool and start staking address nodeID_notNeeded; uint256 minipool_duration; uint256 delegationFee; (nodeID, minipool_duration, delegationFee) = stakeAndCreateMinipool(nodeOp, depositAmt, ggpStakeAmt, avaxAssignmentRequest); assertEq(vault.balanceOf("MinipoolManager"), 1000 ether); vm.startPrank(rialto1); minipoolMgr.claimAndInitiateStaking(nodeID); assertEq(vault.balanceOf("MinipoolManager"), 0); assertEq(rialto1.balance, 2000 ether); //make sure the minipool is staking status bytes32 txID = keccak256("txid"); minipoolMgr.recordStakingStart(nodeID, txID, block.timestamp); vm.stopPrank(); //create the delegation node (nodeID_notNeeded, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); //act as the delegation node and request delegation vm.deal(nodeOp, ggpBondAmt); vm.startPrank(nodeOp); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); index = delegationMgr.getIndexOf(nodeID); //check that the transfer of ggpbond from node op to the contract worked assertEq(vault.balanceOfToken("DelegationManager", ggp), ggpBondAmt); //check that the storage items are correct and the registration was successful address nodeID_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".nodeID"))); assertEq(nodeID_, nodeID); uint256 ggpBondAmt_ = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".ggpBondAmt"))); assertEq(ggpBondAmt_, ggpBondAmt); uint256 status = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".status"))); assertEq(status, uint256(DelegationNodeStatus.Prelaunch)); address nodeOp_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".owner"))); assertEq(nodeOp_, nodeOp); bool isMinipool = store.getBool(keccak256(abi.encodePacked("delegationNode.item", index, ".isMinipool"))); assertEq(isMinipool, true); vm.stopPrank(); //start acting as rialto vm.startPrank(rialto1); uint256 priorBalance_rialto1 = rialto1.balance; //start delegation as rialto delegationMgr.claimAndInitiateDelegation(nodeID); //check that all the funds were transfered successfully to rialto assertEq((rialto1.balance - priorBalance_rialto1), requestedDelegationAmt); //rialto records delegation has started delegationMgr.recordDelegationStart(nodeID, block.timestamp); //testing that if we give an incorrect end time that it will trigger revert vm.expectRevert(DelegationManager.InvalidEndTime.selector); delegationMgr.recordDelegationEnd{value: requestedDelegationAmt}(nodeID, block.timestamp, 0 ether, 0 ether); skip(duration); //testing that if Rialto doesnt send back the original amt of delegation funds that it will trigger revert vm.expectRevert(DelegationManager.InvalidEndingDelegationAmount.selector); delegationMgr.recordDelegationEnd{value: 0 ether}(nodeID, block.timestamp, 0 ether, 0 ether); // // // Give rialto the rewards it needs uint256 rewards = 10 ether; deal(rialto1, (rialto1.balance - priorBalance_rialto1) + rewards); //testing that if we give the incorrect amt of rewards it will revert vm.expectRevert(DelegationManager.InvalidEndingDelegationAmount.selector); delegationMgr.recordDelegationEnd{value: rialto1.balance}(nodeID, block.timestamp, 9 ether, 0 ether); //should test that if ther are no rewards then ggp will be slashed? //ggavax has some funds in it from bob uint256 priorBalance_ggAVAX = wavax.balanceOf(address(ggAVAX)); //Is a minipool, so rewards for the validator and delegator // 5% rewards for each uint256 delegatorRewards = (requestedDelegationAmt * 5) / 100; uint256 validatorRewards = (requestedDelegationAmt * 5) / 100; uint256 delegationAndRewardsTotal = requestedDelegationAmt + delegatorRewards + validatorRewards; delegationMgr.recordDelegationEnd{value: delegationAndRewardsTotal}(nodeID, block.timestamp, delegatorRewards, validatorRewards); assertEq((wavax.balanceOf(address(ggAVAX)) - priorBalance_ggAVAX), (requestedDelegationAmt + delegatorRewards)); assertEq(vault.balanceOf("DelegationManager"), validatorRewards); vm.stopPrank(); //test that the node op can withdraw the funds they are due vm.startPrank(nodeOp); uint256 priorBalance_ggp = ggp.balanceOf(nodeOp); uint256 priorBalance_nodeOp = nodeOp.balance; delegationMgr.withdrawRewardAndBondFunds(nodeID); assertEq((ggp.balanceOf(nodeOp) - priorBalance_ggp), ggpBondAmt); assertEq((nodeOp.balance - priorBalance_nodeOp), validatorRewards); } //taken form MinipoolManager function testExpectedReward() public { uint256 amt = delegationMgr.expectedRewardAmt(365 days, 1_000 ether); assertEq(amt, 100 ether); amt = delegationMgr.expectedRewardAmt((365 days / 2), 1_000 ether); assertEq(amt, 50 ether); amt = delegationMgr.expectedRewardAmt((365 days / 3), 1_000 ether); assertEq(amt, 33333333333333333000); // Set 5% annual expected reward rate dao.setSettingUint("avalanche.expectedRewardRate", 5e16); amt = delegationMgr.expectedRewardAmt(365 days, 1_000 ether); assertEq(amt, 50 ether); amt = delegationMgr.expectedRewardAmt((365 days / 3), 1_000 ether); assertEq(amt, 16.666666666666666 ether); } //taken from MinipoolManager function testCalculateSlashAmt() public { oracle.setGGPPriceInAVAX(1 ether, block.timestamp); uint256 slashAmt = delegationMgr.calculateSlashAmt(100 ether); assertEq(slashAmt, 100 ether); oracle.setGGPPriceInAVAX(0.5 ether, block.timestamp); slashAmt = delegationMgr.calculateSlashAmt(100 ether); assertEq(slashAmt, 200 ether); oracle.setGGPPriceInAVAX(3 ether, block.timestamp); slashAmt = delegationMgr.calculateSlashAmt(100 ether); assertEq(slashAmt, 33333333333333333333); } function testFullCycle_NotMinipool_WithSlashing() public { //make sure that there is a balance in the ggavax contract that can be used for delegation funds vm.deal(bob, 3000000 ether); vm.prank(bob); ggAVAX.depositAVAX{value: 3000000 ether}(); assertEq(bob.balance, 0); //create the delegation node (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); //act as the delegation node and request delegation vm.startPrank(nodeOp); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); index = delegationMgr.getIndexOf(nodeID); //check that the transfer of ggpbond from node op to the contract worked assertEq(vault.balanceOfToken("DelegationManager", ggp), ggpBondAmt); //check that the storage items are correct and the registration was successful address nodeID_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".nodeID"))); assertEq(nodeID_, nodeID); uint256 ggpBondAmt_ = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".ggpBondAmt"))); assertEq(ggpBondAmt_, ggpBondAmt); uint256 status = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".status"))); assertEq(status, uint256(DelegationNodeStatus.Prelaunch)); address nodeOp_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".owner"))); assertEq(nodeOp_, nodeOp); vm.stopPrank(); //start acting as rialto vm.startPrank(rialto1); //start delegation as rialto delegationMgr.claimAndInitiateDelegation(nodeID); //check that all the funds were transfered successfully to rialto assertEq(rialto1.balance, requestedDelegationAmt); //rialto records delegation has started delegationMgr.recordDelegationStart(nodeID, block.timestamp); skip(duration); //ggavax has some funds in it from bob uint256 priorBalance_ggAVAX = wavax.balanceOf(address(ggAVAX)); //ggp price needs to be set inorder to calculate the slash amt oracle.setGGPPriceInAVAX(1 ether, block.timestamp); //testing that if we give zero rewards that the ggp will be slashed delegationMgr.recordDelegationEnd{value: requestedDelegationAmt}(nodeID, block.timestamp, 0 ether, 0 ether); uint256 expectedAmt = delegationMgr.expectedRewardAmt(duration, requestedDelegationAmt); uint256 slashAmt = delegationMgr.calculateSlashAmt(expectedAmt); uint256 slashAmt_ = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".ggpSlashAmt"))); assertEq(slashAmt_, slashAmt); assertEq((wavax.balanceOf(address(ggAVAX)) - priorBalance_ggAVAX), (requestedDelegationAmt)); vm.stopPrank(); //test that the node op can withdraw the funds they are due vm.startPrank(nodeOp); uint256 priorBalance_ggp = ggp.balanceOf(nodeOp); delegationMgr.withdrawRewardAndBondFunds(nodeID); assertEq((ggp.balanceOf(nodeOp) - priorBalance_ggp), (ggpBondAmt - slashAmt)); DelegationManager.DelegationNode memory dn; dn = delegationMgr.getDelegationNode(index); //check that the status is finished for this node assertEq(dn.status, uint256(DelegationNodeStatus.Finished)); //test rejoining once finished delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); int256 new_index = delegationMgr.getIndexOf(nodeID); assertEq(new_index, index); ggpBondAmt_ = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".ggpBondAmt"))); assertEq(ggpBondAmt_, ggpBondAmt); vm.stopPrank(); } //taken from MinipoolManger function testCancelAndReBondWithGGP() public { //create the delegation node (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); //act as the delegation node and request delegation vm.startPrank(nodeOp); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); index = delegationMgr.getIndexOf(nodeID); //check that the transfer of ggpbond from node op to the contract worked assertEq(vault.balanceOfToken("DelegationManager", ggp), ggpBondAmt); //check that the storage items are correct and the registration was successful address nodeID_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".nodeID"))); assertEq(nodeID_, nodeID); uint256 ggpBondAmt_ = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".ggpBondAmt"))); assertEq(ggpBondAmt_, ggpBondAmt); uint256 status = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".status"))); assertEq(status, uint256(DelegationNodeStatus.Prelaunch)); address nodeOp_ = store.getAddress(keccak256(abi.encodePacked("delegationNode.item", index, ".owner"))); assertEq(nodeOp_, nodeOp); uint256 priorBalance_ggp = ggp.balanceOf(nodeOp); //cancel delegation delegationMgr.cancelDelegation(nodeID); DelegationManager.DelegationNode memory dn; dn = delegationMgr.getDelegationNode(index); //verify that it was canceled and the funds returned assertEq(dn.status, uint256(DelegationNodeStatus.Canceled)); assertEq((ggp.balanceOf(nodeOp) - priorBalance_ggp), ggpBondAmt); //try to reregister the node for delegation delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); int256 new_index = delegationMgr.getIndexOf(nodeID); assertEq(new_index, index); ggpBondAmt_ = store.getUint(keccak256(abi.encodePacked("delegationNode.item", index, ".ggpBondAmt"))); assertEq(ggpBondAmt_, ggpBondAmt); vm.stopPrank(); } //taken form MinipoolManager function testCancelByOwner() public { vm.startPrank(nodeOp); //create the delegation node (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); delegationMgr.cancelDelegation(nodeID); vm.stopPrank(); vm.startPrank(rialto1); vm.expectRevert(DelegationManager.OnlyOwnerCanCancel.selector); delegationMgr.cancelDelegation(nodeID); vm.stopPrank(); } //taken form MinipoolManager function testEmptyState() public { vm.startPrank(nodeOp); index = delegationMgr.getIndexOf(ZERO_ADDRESS); assertEq(index, -1); DelegationManager.DelegationNode memory dn; dn = delegationMgr.getDelegationNode(index); assertEq(dn.nodeID, ZERO_ADDRESS); vm.stopPrank(); } //taken form MinipoolManager function testCreateAndGetMany() public { vm.startPrank(nodeOp); for (uint256 i = 0; i < 10; i++) { //create the delegation node (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); } index = delegationMgr.getIndexOf(nodeID); assertEq(index, 9); vm.stopPrank(); } //taken from MinipoolManager function testGetStatusCounts() public { uint256 prelaunchCount; uint256 launchedCount; uint256 delegatedCount; uint256 withdrawableCount; uint256 finishedCount; uint256 canceledCount; vm.startPrank(nodeOp); for (uint256 i = 0; i < 10; i++) { (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); delegationMgr.updateDelegationNodeStatus(nodeID, DelegationNodeStatus.Launched); (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); delegationMgr.updateDelegationNodeStatus(nodeID, DelegationNodeStatus.Delegated); (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); delegationMgr.updateDelegationNodeStatus(nodeID, DelegationNodeStatus.Withdrawable); (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); delegationMgr.updateDelegationNodeStatus(nodeID, DelegationNodeStatus.Finished); (nodeID, requestedDelegationAmt, ggpBondAmt, duration) = randDelegationNode(); delegationMgr.registerNode{value: ggpBondAmt}(nodeID, requestedDelegationAmt, ggpBondAmt, duration); delegationMgr.updateDelegationNodeStatus(nodeID, DelegationNodeStatus.Canceled); } // Get all in one page (prelaunchCount, launchedCount, delegatedCount, withdrawableCount, finishedCount, canceledCount) = delegationMgr.getDelegationNodeCountPerStatus( 0, 0 ); assertEq(prelaunchCount, 10); assertEq(launchedCount, 10); assertEq(delegatedCount, 10); assertEq(withdrawableCount, 10); assertEq(finishedCount, 10); assertEq(canceledCount, 10); // Test pagination (prelaunchCount, launchedCount, delegatedCount, withdrawableCount, finishedCount, canceledCount) = delegationMgr.getDelegationNodeCountPerStatus( 0, 6 ); assertEq(prelaunchCount, 1); assertEq(launchedCount, 1); assertEq(delegatedCount, 1); assertEq(withdrawableCount, 1); assertEq(finishedCount, 1); assertEq(canceledCount, 1); vm.stopPrank(); } }
<template> <div class="card"> <!-- Card header --> <div class="card-header"> <div class="row align-items-center"> <div class="col-8"> <h5 class="h3 mb-0"> Création de notifications </h5> </div> <div class="col text-right"> <base-button size="sm" type="primary" native-type="submit" form="create-notification" > Publier </base-button> </div> </div> </div> <!-- Card body --> <div class="card-body pb-3 "> <form id="create-notification" role="form" @submit.prevent="handleSubmit" > <div class="row"> <!-- title --> <div class="col-md-6"> <base-input v-model="title" v-validate="'required'" :error="getError('titre')" :valid="isValid('titre')" name="titre" label="Titre" class="w-100" placeholder="Entrez un titre" /> </div> <!-- target --> <div class="col-md-6"> <base-input :error="getError('cible')" :valid="isValid('cible')" class="w-100" label="Séléctionnez la cible" > <el-select v-model="select.target" v-validate="'required'" name="cible" multiple filterable > <el-option v-for="group in select.groups" :key="group.label" :label="group.label" :value="group.value" /> </el-select> </base-input> </div> </div> <!-- message --> <div class="row"> <div class="col-md-12"> <base-input :error="getError('message')" :valid="isValid('message')" class="w-100" label="Message" > <textarea v-model="message" v-validate="'required'" name="message" class="form-control" rows="3" resize="none" placeholder="Entrez le message à faire passer..." /> </base-input> </div> </div> <div class="row"> <!-- icon --> <div class="col-md-6"> <base-input v-model="icon" v-validate="'required'" :error="getError('icône')" :valid="isValid('icône')" name="icône" class="w-100" label="Icône" placeholder="fas fa-bell" /> </div> <!-- type --> <div class="col-md-6"> <base-input v-model="type" v-validate="'required'" :error="getError('type')" :valid="isValid('type')" name="type" class="w-100" label="Type" placeholder="primary" /> </div> </div> <!-- preview --> <div class="row"> <div class="col-md-12"> <label class="form-control-label">Prévisualisation</label> <div class="card mb-3" style="border-radius: 10px" > <div class="card-body"> <div class="row align-items-center"> <div class="col-auto"> <i :class="`${icon || 'fas fa-bell'} bg-${type || 'grey'}`" class="avatar rounded-circle" /> </div> <div class="col container ml--2"> <div class="row"> <div class="col"> <h4 class="mb-0 text-sm" v-html="title || `Le titre de la notification !`" /> </div> <div class="col-auto text-right"> <small class="text-muted"> <i class="fas fa-clock mr-1" /> 2h </small> </div> </div> <div class="row mt-1 px-3"> <p class="text-sm mb-0" v-html="message || `Commencez à taper votre message pour voir la prévisualisation s'actualiser.`" /> </div> </div> </div> </div> </div> </div> </div> </form> </div> </div> </template> <script> import { ElSelect, ElOption } from 'element-plus' export default { components: { [ElSelect.name]: ElSelect, [ElOption.name]: ElOption }, data () { return { title: '', message: '', icon: '', type: '', select: { groups: [ { value: 'all', label: 'Tous' } ], target: '' } } }, methods: { handleSubmit () { this.$validator.validate().then(valid => { if (valid) { this.$store.dispatch('notifications/create', { target: this.select.target, title: this.title, message: this.message, icon: this.icon, type: this.type }) } }) }, getError (name) { return this.errors.first(name) }, isValid (name) { return this.validated && !this.errors.has(name) } } } </script>
<!DOCTYPE HTML> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.w3.org/1999/xhtml" lang="ru"> <head> <title>Finance board</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}"> </link> <link th:href="@{/css/jumbotron.css}" rel="stylesheet"> </link> <link th:href="@{/css/site.css}" rel="stylesheet"> </link> </head> <body onload="prettyPrint();"> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Personal Finance</a> </div> <div sec:authorize="isAnonymous()" id="anonymous-navbar" class="navbar-collapse collapse"> <form th:action="@{/login}" method="post" class="navbar-form navbar-right"> <div class="form-group"> <input type="text" name="username" placeholder="User" class="form-control" /> </div> <div class="form-group"> <input type="password" name="password" placeholder="Password" class="form-control" /> </div> <button type="submit" class="btn btn-success" value="login">Log in</button> </form> </div> <div sec:authorize="isAuthenticated()" id="authenticated-navbar" class="navbar-collapse collapse"> <form th:action="@{/logout}" method="post" class="navbar-form navbar-right"> <button type="submit" class="btn btn-success" value="logout">Log out</button> </form> </div><!--/.navbar-collapse --> </div> </nav> <div class="container"> <div th:class="${messageStyle}"> <p th:text="${systemMessage}" /> </div> </div> <div class="container" sec:authorize="isAnonymous()"> <div class="row"> <div class="span12"> <div class="hero-unit"> <h1>Welcome to Personal Finance System!</h1> <p>Please sign up or log in to use Personal Finance System</p> <a href="signup" class="btn btn-primary btn-large">Sign up</a> </div> </div> </div> </div> <div sec:authorize="isAnonymous()" class="container"> <div class="row"> <div class="span12"> <h2>Our customers</h2> <div class="col-xs-3" > <div class="well"> <img th:src="@{/images/harrypotter.jpg}" width="75" height="75" alt="harry_pic" class="img-circle"/> <p><em>It's just a magical service!</em></p> <p>- Harry J. Potter</p> </div> </div> <div class="col-xs-3"> <div class="well"> <img th:src="@{/images/groot.jpg}" width="75" height="75" alt="groot_pic" class="img-circle"/> <p><em>I am Groot!</em></p> <p>- Groot</p> </div> </div> </div> </div> </div> <div sec:authorize="isAuthenticated()" class="container"> <ul class="nav nav-tabs" id="tabs"> <li class="active"><a data-target="#personal" data-toggle="tab">Personal</a></li> <li><a data-target="#overall" data-toggle="tab">Overall</a></li> </ul> <div class="tab-content"> <div class="tab-pane active" id="personal"> <div class="container"> <div class="row"> <div class="span8 offset2"> <h3>Balance</h3> <table id="balance_table" class="table table-bordered table-striped"> <thead> <tr> <th>Date</th> <th>Category</th> <th>Title</th> <th>Type</th> <th>Value</th> <th>&nbsp;</th> </tr> </thead> <thead> <tr> <form id="balance_record_add_form" action="#" method="post" th:action="@{/add}" th:object="${balanceRecord}" class="form-vertical"> <td><input type="date" required = "true" th:field="*{date}" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" /></td> <td><input type="text" data-parsley-maxlength="500" th:field="*{category}" /></td> <td><input type="text" required = "true" data-parsley-maxlength="500" th:field="*{title}" /></td> <td> <select th:field="*{sign}"> <option value="COST">COST</option> <option value="INCOME">INCOME</option> </select> </td> <td><input type="number" required = "true" th:field="*{value}" /></td> <td><input type="submit" value="Add balance record" class="btn"/></td> </form> </tr> </thead> <tbody> <if th:if="${not #lists.isEmpty(balanceRecordList)}"> <tr th:each="balanceRecord : ${balanceRecordList}"> <td type="text" th:text="${balanceRecord.date != null} ? ${#calendars.format(balanceRecord.date, 'dd.MM.yyyy')} : null"></td> <td th:text="${balanceRecord.category}"></td> <td th:text="${balanceRecord.title}"></td> <td th:text="${balanceRecord.sign}"></td> <td type="number" th:text="${balanceRecord.value}"></td> <td> <div style="float: left; margin-right: 5px;"> <a th:href="@{/edit/__${balanceRecord.id}__}" class="btn btn-default btn-mini">Edit</a> </div> <div style="float: left;"> <form action="#" method="post" th:action="@{/delete/__${balanceRecord.id}__}"> <input type="submit" class="btn btn-danger btn-mini" value="Delete"/> </form> </div> </td> </tr> </if> </tbody> </table> </div> </div> </div> </div> <div class="tab-pane" id="overall"> <div class="container"> <div class="row"> <div class="span8 offset2"> <h3>Balance</h3> <table id="full_balance_table" class="table table-bordered table-striped" style="width: 100%"> <thead> <tr> <th>User</th> <th>Date</th> <th>Category</th> <th>Title</th> <th>Type</th> <th>Value</th> </tr> </thead> </table> </div> </div> </div> </div> </div> </div> <script th:src="@{/js/jquery-3.0.0.min.js}"></script> <script th:src="@{/js/bootstrap.min.js}"></script> <script th:src="@{/js/prettify.min.js}"></script> <script th:src="@{/js/parsley.min.js}"></script> <script type="text/javascript" charset="utf8" th:src="@{/js/jquery.dataTables.js}"></script> <script type="text/javascript"> $(document).ready( function () { $('#balance_table').DataTable(); } ); var table; $(document).ready(function() { table = $('#full_balance_table').DataTable( { "ajax": '/PersonalFinance/refresh', "sAjaxDataProp": "data" } ); } ); setInterval( function () { table.ajax.reload(); }, 30000 ); var formInstance = $('balance_record_add_form').parsley(); console.log(field.options.maxlength); </script> </body> </html>
// @flow import * as React from 'react' import MenuItem from '@material-ui/core/MenuItem' import TextField from '@material-ui/core/TextField' type Props = { value: string, name: string, onChange: Function, } class CharmTimingSelect extends React.PureComponent<Props> { render() { const { name, value, onChange } = this.props return ( <TextField select name={name} value={value} label="Type" margin="dense" onChange={onChange} > <MenuItem value="simple">Simple</MenuItem> <MenuItem value="supplemental">Supplemental</MenuItem> <MenuItem value="reflexive">Reflexive</MenuItem> <MenuItem value="supplemental/reflexive"> Supplemental or Reflexive </MenuItem> <MenuItem value="permanent">Permanent</MenuItem> </TextField> ) } } export default CharmTimingSelect
package au.com.dardle.sample.badgelayout; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import au.com.dardle.widget.BadgeLayout; public class BadgeLayoutActivity extends AppCompatActivity { private static final String LOG_TAG = BadgeLayoutActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_badge_layout); setupView(); } private void setupView() { int from = getIntent().getIntExtra(BadgeLayoutApplication.EXTRA_FROM, BadgeLayoutApplication.FROM_XML); Fragment fragment; if (from == BadgeLayoutApplication.FROM_XML) { fragment = new BadgeLayoutFromXMLFragment(); } else { fragment = new BadgeLayoutFromCodeFragment(); } FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction .add(R.id.content_container, fragment) .commit(); } public static class BadgeLayoutFromXMLFragment extends BadgeLayoutFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_badge_layout_from_xml, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); BadgeLayout badgeLayout = (BadgeLayout) getActivity().findViewById(R.id.badge_layout); badgeLayout.addOnBadgeClickedListener(this); BadgeLayout appBadgeLayout = (BadgeLayout) getActivity().findViewById(R.id.app_badge_layout); appBadgeLayout.addOnBadgeClickedListener(this); BadgeLayout soBadgeLayout = (BadgeLayout) getActivity().findViewById(R.id.so_badge_layout); soBadgeLayout.addOnBadgeClickedListener(this); } @Override public void onStop() { super.onStop(); BadgeLayout badgeLayout = (BadgeLayout) getActivity().findViewById(R.id.badge_layout); badgeLayout.removeOnBadgeClickedListener(this); } } public static class BadgeLayoutFromCodeFragment extends BadgeLayoutFragment { @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_badge_layout_from_code, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setupDefaultBadgeLayout(); setupAppBadgeLayout(); setupSoBadgeLayout(); } @Override public void onStop() { super.onStop(); BadgeLayout badgeLayout = (BadgeLayout) getActivity().findViewById(R.id.badge_layout); badgeLayout.removeOnBadgeClickedListener(this); } private void setupDefaultBadgeLayout() { BadgeLayout badgeLayout = (BadgeLayout) getActivity().findViewById(R.id.badge_layout); // Add badges badgeLayout.addBadge(badgeLayout .newBadge() .setText("Badge") .setIcon(ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_launcher, getContext().getTheme()))); badgeLayout.addBadge(badgeLayout .newBadge() .setText("Badge")); badgeLayout.addBadge(badgeLayout .newBadge() .setIcon(ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_launcher, getContext().getTheme()))); // Set item spacing badgeLayout.setSpacing((int) (getResources().getDisplayMetrics().density * 24)); badgeLayout.addOnBadgeClickedListener(this); } private void setupAppBadgeLayout() { BadgeLayout appBadgeLayout = (BadgeLayout) getActivity().findViewById(R.id.app_badge_layout); appBadgeLayout.addOnBadgeClickedListener(this); appBadgeLayout.setBadgeBackground(R.drawable.background_app_badge); appBadgeLayout.setSpacing((int) (getResources().getDisplayMetrics().density * 8)); appBadgeLayout.setBadgeTextColor(ResourcesCompat.getColorStateList(getResources(), android.R.color.white, getContext().getTheme())); // Add badges appBadgeLayout.addBadge(appBadgeLayout .newBadge() .setText("TOP CHARTS")); appBadgeLayout.addBadge(appBadgeLayout .newBadge() .setText("GAMES")); appBadgeLayout.addBadge(appBadgeLayout .newBadge() .setText("CATEGORIES")); appBadgeLayout.addBadge(appBadgeLayout .newBadge() .setText("EARLY ACCESS")); appBadgeLayout.addBadge(appBadgeLayout .newBadge() .setText("FAMILY")); appBadgeLayout.addBadge(appBadgeLayout .newBadge() .setText("EDITORS' CHOICE")); } private void setupSoBadgeLayout() { BadgeLayout soBadgeLayout = (BadgeLayout) getActivity().findViewById(R.id.so_badge_layout); soBadgeLayout.addOnBadgeClickedListener(this); soBadgeLayout.setBadgeBackground(R.drawable.background_so_badge); soBadgeLayout.setBadgeContentSpacing((int) (getResources().getDisplayMetrics().density * 10)); soBadgeLayout.setSpacing((int) (getResources().getDisplayMetrics().density * 8)); soBadgeLayout.setBadgeTextColor(ResourcesCompat.getColorStateList(getResources(), android.R.color.white, getContext().getTheme())); soBadgeLayout.setBadgeTextPosition(BadgeLayout.BadgeTextPosition.RIGHT); // Add badges soBadgeLayout.addBadge(soBadgeLayout .newBadge() .setText("Teacher") .setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_so_badge_bronze, getContext().getTheme()))); soBadgeLayout.addBadge(soBadgeLayout .newBadge() .setText("Guru") .setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_so_badge_silver, getContext().getTheme()))); soBadgeLayout.addBadge(soBadgeLayout .newBadge() .setText("Great Answer") .setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.ic_so_badge_gold, getContext().getTheme()))); } } public static class BadgeLayoutFragment extends Fragment implements BadgeLayout.OnBadgeClickedListener { @Override public void onBadgeClicked(BadgeLayout.Badge badge) { Toast.makeText(getActivity(), (badge.getText() != null ? badge.getText() : "") + " is clicked", Toast.LENGTH_SHORT) .show(); } } }
using KiddyCheckApi.Core.Requests; using KiddyCheckApi.Core.Services; using Microsoft.AspNetCore.Mvc; using KiddyCheckApi.Core.Helpers; using System.Reflection; namespace KiddyCheckApi_v1._0._0.Controllers { [Route("api/v1/[controller]")] [ApiController] public class PersonasController : Controller { #region <--- Variables ---> private readonly PersonasService _personasService; private ILogger<PersonasController> _logger; #endregion #region <--- Constructor ---> public PersonasController(PersonasService personasService, ILogger<PersonasController> logger ) { _personasService = personasService; _logger = logger; } #endregion #region <--- Metodos ---> [HttpPost("AgregarPersona")] public async Task<IActionResult> AgregarPersona(PersonaRequest request) { try { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Started Success"); var idUserLogin = HttpContext.User.Claims.Where(x => x.Type == "Id").FirstOrDefault().Value; var response = await _personasService.AgregarPersona(request, int.Parse(idUserLogin)); if (response.Success) { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return Ok(response); } _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return BadRequest(response); } catch (Exception ex) { _logger.LogError(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + ex.Message); throw; } } //Actualizar usuario [HttpPost("ActualizarPersona")] public async Task<IActionResult> ActualizarUsuario(PersonaRequest request) { try { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Started Success"); var idUserLogin = HttpContext.User.Claims.Where(x => x.Type == "Id").FirstOrDefault().Value; var response = await _personasService.ActualizarPersona(request, int.Parse(idUserLogin)); if (response.Success) { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return Ok(response); } _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return BadRequest(response); } catch (Exception ex) { _logger.LogError(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + ex.Message); throw; } } //Obtener usuarios [HttpGet("ObtenerPersonas")] public async Task<IActionResult> ObtenerPersonas() { try { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Started Success"); var response = await _personasService.ObtenerPersonas(); if (response != null) { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return Ok(response); } _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return NotFound(); } catch (Exception ex) { _logger.LogError(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + ex.Message); throw; } } //Eliminar persona [HttpDelete("EliminarPersona")] public async Task<IActionResult> EliminarPersona(int id) { try { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Started Success"); var response = await _personasService.EliminarPersona(id, 1); if (response.Success) { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return Ok(response); } _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return BadRequest(response); } catch (Exception ex) { _logger.LogError(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + ex.Message); throw; } } //Obtener por tipo [HttpGet("ObtenerPersonaPorTipo")] public async Task<IActionResult> ObtenerPersonaPorTipo(int id) { try { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Started Success"); var response = await _personasService.ObtenerPersonaPorTipo(id); if (response != null) { _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return Ok(response); } _logger.LogInformation(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + "Finished Success"); return NotFound(); } catch (Exception ex) { _logger.LogError(MethodBase.GetCurrentMethod().DeclaringType.DeclaringType.Name + ex.Message); throw; } } #endregion } }
<template> <b-collapse class="sidebar-collapse" id="sidebar-collapse" :visible="sidebarOpened"> <nav :class="{sidebar: true}" > <header class="logo"> <router-link to="/dashboard"><img src="../../assets/pic/MLOPS.png" width="150" height="150"/></router-link> </header> <ul class="nav"> <h5 class="navTitle"></h5> <NavLink :activeItem="activeItem" header="Email Marketing" link="/Email_Marketing" iconName="flaticon-email" index="Email_Marketing" isHeader /> <NavLink header="Facebook Ads" link="/Facebook_Ads" iconName="flaticon-shopping-bag" index="Facebook Ads" isHeader /> <!-- <NavLink header="Email Marketing" link="/Email_Marketing" iconName="flaticon-email" index="Email Marketing" isHeader /> --> <NavLink header="Google Adwords" link="/Google_Ads" iconName="flaticon-charts" index="Google Ads" isHeader /> <NavLink header="Customer Satisfaction" link="/Reviews" iconName="flaticon-message-circle" index="Reviews" isHeader /> <!-- <NavLink header="Iot" link="/Iot" iconName="flaticon-core" index="Iot" isHeader /> --> <!-- <NavLink header="Monitoring" link="/Monitoring" iconName="flaticon-equal-3" index="Monitoring" isHeader /> --> <NavLink header="To Do" link="/todo" iconName="flaticon-documentation" index="To Do" isHeader /> <NavLink header="Profile" link="/Profile" iconName="flaticon-person" index="Profile" isHeader /> <NavLink header="Upload" link="/Upload" iconName="flaticon-extra" index="Upload" isHeader /> </ul> </nav> </b-collapse> </template> <script> import { mapState, mapActions } from 'vuex'; import NavLink from './NavLink/NavLink'; export default { name: 'Sidebar', components: { NavLink }, data() { return { alerts: [ { id: 0, title: 'Sales Report', value: 15, footer: 'Calculating x-axis bias... 65%', color: 'primary', }, { id: 1, title: 'Personal Responsibility', value: 20, footer: 'Provide required notes', color: 'danger', }, ], }; }, methods: { ...mapActions('layout', ['changeSidebarActive', 'switchSidebar']), setActiveByRoute() { const paths = this.$route.fullPath.split('/'); paths.pop(); this.changeSidebarActive(paths.join('/')); }, }, created() { this.setActiveByRoute(); }, computed: { ...mapState('layout', { sidebarOpened: state => !state.sidebarClose, activeItem: state => state.sidebarActiveElement, }), }, }; </script> <!-- Sidebar styles should be scoped --> <style src="./Sidebar.scss" lang="scss" scoped/>
import React from 'react'; import { SplashScreen, Login, Register, ForgotPassword, ResetPassword, Home, Profile, DetailEvent, Booking, Payment, ProfileEdit, ChangePassword, MyBooking, MyWishlist, ManageEvent, DetailTransaction, CreateEvent, UpdateEvent, SearchEvent, } from './index'; import {NavigationContainer} from '@react-navigation/native'; import {createNativeStackNavigator} from '@react-navigation/native-stack'; import { createDrawerNavigator, DrawerContentScrollView, DrawerItemList, DrawerItem, } from '@react-navigation/drawer'; import FontAwesome5Icon from 'react-native-vector-icons/FontAwesome5'; import FeatherIcon from 'react-native-vector-icons/Feather'; import {useSelector} from 'react-redux'; const Stack = createNativeStackNavigator(); const AuthStack = createNativeStackNavigator(); const Drawer = createDrawerNavigator(); import {useDispatch} from 'react-redux'; import {logout} from '../redux/reducers/auth'; import {StyleSheet, Text, View} from 'react-native'; import http from '../helpers/http'; import {ImageTemplate} from '../components'; import {picDefProfile} from '../assets'; function CustomDrawerContent(props) { const dispatch = useDispatch(); const token = useSelector(state => state.auth.token); const [profile, setProfile] = React.useState({}); React.useEffect(() => { if (token) { const getProfile = async () => { const {data} = await http(token).get('/profile'); setProfile(data.results); }; getProfile(); } }, [token]); return ( <DrawerContentScrollView {...props}> <View style={style.containerProfile}> <View style={style.foto}> <View style={style.fotoIcon}> <ImageTemplate src={profile?.picture || null} defaultImg={picDefProfile} style={style.IMGProfiles} /> </View> </View> <View> <Text style={style.textFullname}> {profile?.fullName?.length < 25 && profile?.fullName} {profile?.fullName?.length >= 25 && profile?.fullName?.slice(0, 20) + ' ...'} </Text> <Text style={style.textProfession}> {profile.profession ? profile.profession : 'profession: -'} </Text> </View> </View> <DrawerItemList {...props} /> <DrawerItem label="Logout" onPress={() => dispatch(logout())} icon={({focused, color, size}) => ( <FeatherIcon name="log-out" color={color} size={size} /> )} /> </DrawerContentScrollView> ); } function MyDrawer() { return ( <Drawer.Navigator screenOptions={{ headerShown: false, drawerStyle: { backgroundColor: '#eaeaea', width: 340, }, }} drawerContent={props => <CustomDrawerContent {...props} />}> <Drawer.Screen name="SplashScreen" component={SplashScreen} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="Booking" component={Booking} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="Payment" component={Payment} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="DetailEvent" component={DetailEvent} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="ProfileEdit" component={ProfileEdit} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="ChangePassword" component={ChangePassword} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="DetailTransaction" component={DetailTransaction} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="CreateEvent" component={CreateEvent} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="UpdateEvent" component={UpdateEvent} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="SearchEvent" component={SearchEvent} options={({drawerLabel: () => null}, {drawerItemStyle: {height: 0}})} /> <Drawer.Screen name="Home" component={Home} options={{ drawerActiveTintColor: '#fff', drawerActiveBackgroundColor: '#F0592C', drawerIcon: ({size}) => <FontAwesome5Icon name="home" size={20} />, drawerLabel: 'Home', }} /> <Drawer.Screen name="Profile" component={Profile} options={{ drawerActiveTintColor: '#fff', drawerActiveBackgroundColor: '#F0592C', drawerIcon: ({size}) => <FeatherIcon name="user" size={20} />, drawerLabel: 'Profile', }} /> <Drawer.Screen name="ManageEvent" component={ManageEvent} options={{ drawerActiveTintColor: '#fff', drawerActiveBackgroundColor: '#F0592C', drawerIcon: ({size}) => <FeatherIcon name="plus-circle" size={20} />, drawerLabel: 'Manage Event', }} /> <Drawer.Screen name="MyBooking" component={MyBooking} options={{ drawerActiveTintColor: '#fff', drawerActiveBackgroundColor: '#F0592C', drawerIcon: ({size}) => <FeatherIcon name="clipboard" size={20} />, drawerLabel: 'My Booking', }} /> <Drawer.Screen name="MyWishlist" component={MyWishlist} options={{ drawerActiveTintColor: '#fff', drawerActiveBackgroundColor: '#F0592C', drawerIcon: ({size}) => <FeatherIcon name="heart" size={20} />, drawerLabel: 'My Wishlist', }} /> </Drawer.Navigator> ); } const style = StyleSheet.create({ icon: { width: 24, height: 24, }, containerProfile: { paddingTop: 40, paddingHorizontal: 20, flexDirection: 'row', gap: 10, justifyContent: 'flex-start', alignItems: 'center', }, foto: { width: 70, height: 70, borderRadius: 35, borderWidth: 3, borderColor: '#F0592C', justifyContent: 'center', alignItems: 'center', padding: 30, }, fotoIcon: { width: 55, height: 55, backgroundColor: 'gray', borderRadius: 60, justifyContent: 'center', alignItems: 'center', overflow: 'hidden', }, IMGProfiles: { objectFit: 'cover', width: 60, height: 60, }, textFullname: { fontSize: 16, fontFamily: 'Poppins-SemiBold', textTransform: 'capitalize', color: 'black', width: 240, }, textProfession: { fontSize: 12, fontFamily: 'Poppins-SemiBold', textTransform: 'capitalize', color: 'grey', }, }); const Main = () => { const token = useSelector(state => state.auth.token); return ( <NavigationContainer> {!token && ( <AuthStack.Navigator screenOptions={{headerShown: false}}> <Stack.Screen name="SplashScreen" component={SplashScreen} /> <Stack.Screen name="Login" component={Login} /> <Stack.Screen name="Register" component={Register} /> <Stack.Screen name="ForgotPassword" component={ForgotPassword} /> <Stack.Screen name="ResetPassword" component={ResetPassword} /> </AuthStack.Navigator> )} {token && ( <> <MyDrawer /> </> )} </NavigationContainer> ); }; export default Main;
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm'; enum STATUS { ACTIVE = 'Active', INACTIVE = 'Inactive', } @Entity('user') export class UserEntity { @PrimaryGeneratedColumn({ type: 'int', unsigned: true }) iUserId: number; @Column({ type: 'varchar', nullable: true, length: 255 }) vProfileImage: string; @Column({ type: 'varchar', nullable: true, length: 255 }) vFirstName: string; @Column({ type: 'varchar', nullable: true, length: 255 }) vLastName: string; @Column({ type: 'varchar', nullable: true, length: 255 }) vEmail: string; @Column({ type: 'varchar', nullable: true, length: 255 }) vPassword: string; @Column({ type: 'varchar', nullable: true, length: 20 }) vPhoneNumber: string; @Column({ type: 'varchar', nullable: true, length: 10 }) vOtpCode: string; @Column({ type: 'varchar', nullable: true, length: 10 }) vDialCode: string; @Column({ type: 'enum', nullable: true, enum: STATUS }) eStatus: STATUS; @CreateDateColumn({ type: 'timestamp', nullable: true, default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date; @UpdateDateColumn({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP', onUpdate: 'CURRENT_TIMESTAMP' }) updatedAt: Date; }
import { createAsyncThunk } from "@reduxjs/toolkit"; import axios from "../../AxiosConfig"; import { LoadingEvent } from "../../components/Loading"; import { localstoragetext } from "../../constants/localstorage-text"; export type UserType = { id: number; access_token: string; email: string; hash_key: string; refresh_token: string; modified_datetime: string; }; export const googlelogin = createAsyncThunk< // Return type of the payload creator Pick<UserType, "email" | "id">, // First argument to the payload creator Pick<UserType, "email" | "access_token"> >("user/googlelogin", async (user) => { try { LoadingEvent.fire(true); let resp = await axios.post( process.env.REACT_APP_API_URL + "/token/googlelogin", { email: user.email, access_token: user.access_token, } ); let loginuser = resp.data as UserType; localStorage.setItem(localstoragetext.accesstoken, loginuser.access_token); localStorage.setItem( localstoragetext.refreshtoken, loginuser.refresh_token ); localStorage.setItem(localstoragetext.useremail, loginuser.email); localStorage.setItem(localstoragetext.userid, loginuser.id.toString()); return { email: loginuser.email, id: loginuser.id }; } finally { LoadingEvent.fire(false); } }); export const login = createAsyncThunk< // Return type of the payload creator Pick<UserType, "email" | "id">, // First argument to the payload creator Pick<UserType, "email" | "hash_key"> & { errCallback: () => void } >("user/login", async (user) => { try { LoadingEvent.fire(true); let resp = await axios.post( process.env.REACT_APP_API_URL + "/token/login", { email: user.email, hash_key: user.hash_key, } ); let loginuser = resp.data as UserType; localStorage.setItem(localstoragetext.accesstoken, loginuser.access_token); localStorage.setItem( localstoragetext.refreshtoken, loginuser.refresh_token ); localStorage.setItem(localstoragetext.useremail, loginuser.email); localStorage.setItem(localstoragetext.userid, loginuser.id.toString()); return { email: loginuser.email, id: loginuser.id }; } catch (err) { user.errCallback(); return Promise.reject(err); } finally { LoadingEvent.fire(false); } }); export const userListing = createAsyncThunk< // Return type of the payload creator Array<UserType> // First argument to the payload creator >("user/userListing", async () => { try { LoadingEvent.fire(true); let resp = await axios.get( process.env.REACT_APP_API_URL + "/auth-user/list" ); let users = resp.data as Array<UserType>; return users; } finally { LoadingEvent.fire(false); } }); export const userDelete = createAsyncThunk< // Return type of the payload creator number, // First argument to the payload creator number >("user/delete", async (userid) => { try { LoadingEvent.fire(true); await axios.get( process.env.REACT_APP_API_URL + "/auth-user/delete?userid=" + userid ); return userid; } finally { LoadingEvent.fire(false); } }); export const userEdit = createAsyncThunk< // Return type of the payload creator UserType, // First argument to the payload creator UserType >("user/edit", async (user) => { try { LoadingEvent.fire(true); let resp = await axios.post( process.env.REACT_APP_API_URL + "/auth-user/update", user ); return resp.data as UserType; } finally { LoadingEvent.fire(false); } }); export const userAdd = createAsyncThunk< // Return type of the payload creator UserType, // First argument to the payload creator UserType >("user/add", async (user) => { try { LoadingEvent.fire(true); let resp = await axios.post( process.env.REACT_APP_API_URL + "/auth-user/add", user ); return resp.data as UserType; } finally { LoadingEvent.fire(false); } });
class Particle{ /** * Each particle will have random velocity * vx between -1 and 1 (left or right directions) * vy between -1 and -6 (some particles are slower, others are faster) */ constructor(){ this.x = canvas.width / 2; this.y = canvas.height - 200; this.vx = Math.random() * 2 - 1; this.vy = Math.random() * -5 - 1; this.alpha = 1; } /** * Draw a white circle, with variable alpha property (transparency) */ draw(){ ctx.fillStyle = ctx.fillStyle = `rgba(255, 255, 255, ${this.alpha})`; ctx.beginPath(); ctx.arc(this.x, this.y, 8, 0, Math.PI * 2); ctx.fill(); } /** * Update x and y position using velocities * At each update, the particle becomes a little more transparent * After updating properties, it is time to draw the particle again */ update(){ this.x += this.vx; this.y += this.vy; this.alpha -= 0.01; this.draw(); } }
import httpMocks, { MockRequest, MockResponse } from 'node-mocks-http'; import axios from 'axios'; import { feedbackHandler } from '../../pages/api/createFeedback'; import { NextApiRequest, NextApiResponse } from 'next'; jest.mock('axios'); // Mock the axios module describe('feedbackHandler', () => { let mockRequest: MockRequest<NextApiRequest>; let mockResponse: MockResponse<NextApiResponse>; beforeEach(() => { mockRequest = httpMocks.createRequest({ method: 'POST', url: '/api/createFeedback', body: { stars: 5, slug: 'test-slug', title: 'Test title', }, }); mockResponse = httpMocks.createResponse(); }); it('should return 405 for non-POST requests', async () => { mockRequest.method = 'GET'; await feedbackHandler(mockRequest, mockResponse); expect(mockResponse.statusCode).toBe(405); expect(mockResponse._getJSONData().message).toEqual( 'This is a POST-only endpoint.' ); }); it('should return 400 for invalid POST body', async () => { mockRequest.body = { invalid: 'body' }; await feedbackHandler(mockRequest, mockResponse); expect(mockResponse.statusCode).toBe(400); expect(mockResponse._getJSONData().message).toEqual( 'Invalid POST body.' ); }); it('should handle successful axios post', async () => { const mockData = { _id: 123 }; (axios.post as jest.Mock).mockResolvedValueOnce({ data: mockData }); await feedbackHandler(mockRequest, mockResponse); expect(mockResponse.statusCode).toBe(200); expect(mockResponse._getJSONData()).toEqual(mockData); }); });
"use strict"; var _react = _interopRequireDefault(require("react")); var _enzyme = require("enzyme"); var _IncrementSlider = _interopRequireDefault(require("../IncrementSlider")); var _IncrementSliderModule = _interopRequireDefault(require("../IncrementSlider.module.css")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var tap = function tap(node) { node.simulate('mousedown'); node.simulate('mouseup'); }; var decrement = function decrement(slider) { return tap(slider.find('IconButton').first()); }; var increment = function increment(slider) { return tap(slider.find('IconButton').last()); }; var keyDown = function keyDown(keyCode) { return function (node) { return node.simulate('keydown', { keyCode: keyCode }); }; }; var leftKeyDown = keyDown(37); var rightKeyDown = keyDown(39); var upKeyDown = keyDown(38); var downKeyDown = keyDown(40); var callCount = function callCount(spy) { switch (spy.mock.calls.length) { case 0: return 'not called'; case 1: return 'called once'; default: return "called ".concat(spy.mock.calls.length, " times"); } }; describe('IncrementSlider Specs', function () { test('should decrement value', function () { var handleChange = jest.fn(); var value = 50; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onChange: handleChange, value: value })); decrement(incrementSlider); var expected = value - 1; var actual = handleChange.mock.calls[0][0].value; expect(actual).toBe(expected); }); test('should increment value', function () { var handleChange = jest.fn(); var value = 50; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onChange: handleChange, value: value })); increment(incrementSlider); var expected = value + 1; var actual = handleChange.mock.calls[0][0].value; expect(actual).toBe(expected); }); test('should only call onChange once', function () { var handleChange = jest.fn(); var value = 50; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onChange: handleChange, value: value })); increment(incrementSlider); var expected = 1; var actual = handleChange.mock.calls.length; expect(actual).toBe(expected); }); test('should not call onChange on prop change', function () { var handleChange = jest.fn(); var value = 50; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onChange: handleChange, value: value })); incrementSlider.setProps({ onChange: handleChange, value: value + 1 }); var expected = 0; var actual = handleChange.mock.calls.length; expect(actual).toBe(expected); }); test('should disable decrement button when value === min', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { value: 0, min: 0 })); var expected = true; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton)).prop('disabled'); expect(actual).toBe(expected); }); test('should disable increment button when value === max', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { value: 10, max: 10 })); var expected = true; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton)).prop('disabled'); expect(actual).toBe(expected); }); test('should use custom incrementIcon', function () { var icon = 'plus'; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { incrementIcon: icon })); var expected = icon; var actual = incrementSlider.find(".".concat(_IncrementSliderModule["default"].incrementButton, " Icon")).prop('children'); expect(actual).toBe(expected); }); test('should use custom decrementIcon', function () { var icon = 'minus'; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { decrementIcon: icon })); var expected = icon; var actual = incrementSlider.find(".".concat(_IncrementSliderModule["default"].decrementButton, " Icon")).prop('children'); expect(actual).toBe(expected); }); test('should set decrementButton "aria-label" to value and hint string', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { value: 10 })); var expected = '10 press ok button to decrease the value'; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton)).prop('aria-label'); expect(actual).toBe(expected); }); test('should set decrementButton "aria-label" to decrementAriaLabel', function () { var label = 'decrement aria label'; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { value: 10, decrementAriaLabel: label })); var expected = "10 ".concat(label); var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton)).prop('aria-label'); expect(actual).toBe(expected); }); test('should not set decrementButton "aria-label" when decrementButton is disabled', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { disabled: true, value: 10 })); var expected = null; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton)).prop('aria-label'); expect(actual).toBe(expected); }); test('should set incrementButton "aria-label" to value and hint string', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { value: 10 })); var expected = '10 press ok button to increase the value'; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton)).prop('aria-label'); expect(actual).toBe(expected); }); test('should set incrementButton "aria-label" to incrementAriaLabel', function () { var label = 'increment aria label'; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { value: 10, incrementAriaLabel: label })); var expected = "10 ".concat(label); var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton)).prop('aria-label'); expect(actual).toBe(expected); }); test('should not set incrementButton "aria-label" when incrementButton is disabled', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { disabled: true, value: 10 })); var expected = null; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton)).prop('aria-label'); expect(actual).toBe(expected); }); // test directional events from IncrementSliderButtons test('should call onSpotlightLeft from the decrement button of horizontal IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onSpotlightLeft: handleSpotlight })); leftKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightLeft from the decrement button of vertical IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { orientation: "vertical", onSpotlightLeft: handleSpotlight })); leftKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightLeft from the increment button of vertical IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { orientation: "vertical", onSpotlightLeft: handleSpotlight })); leftKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightRight from the increment button of horizontal IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onSpotlightRight: handleSpotlight })); rightKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightRight from the increment button of vertical IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { orientation: "vertical", onSpotlightRight: handleSpotlight })); rightKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightRight from the decrement button of vertical IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { orientation: "vertical", onSpotlightRight: handleSpotlight })); rightKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightUp from the decrement button of horizontal IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onSpotlightUp: handleSpotlight })); upKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightUp from the increment button of horizontal IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onSpotlightUp: handleSpotlight })); upKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightUp from the increment button of vertical IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { orientation: "vertical", onSpotlightUp: handleSpotlight })); upKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightDown from the increment button of horizontal IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { onSpotlightDown: handleSpotlight })); downKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightDown from the decrement button of horizontal IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { orientation: "vertical", onSpotlightDown: handleSpotlight })); downKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightDown from the decrement button of vertical IncrementSlider', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { orientation: "vertical", onSpotlightDown: handleSpotlight })); downKeyDown(incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); // test directional events at bounds of slider test('should call onSpotlightLeft from slider of horizontal IncrementSlider when value is at min', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { min: 0, value: 0, onSpotlightLeft: handleSpotlight })); leftKeyDown(incrementSlider.find("Slider.".concat(_IncrementSliderModule["default"].slider))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightRight from slider of horizontal IncrementSlider when value is at max', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { max: 100, value: 100, onSpotlightRight: handleSpotlight })); rightKeyDown(incrementSlider.find("Slider.".concat(_IncrementSliderModule["default"].slider))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightDown from slider of vertical IncrementSlider when value is at min', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { min: 0, value: 0, orientation: "vertical", onSpotlightDown: handleSpotlight })); downKeyDown(incrementSlider.find("Slider.".concat(_IncrementSliderModule["default"].slider))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should call onSpotlightUp from slider of horizontal IncrementSlider when value is at max', function () { var handleSpotlight = jest.fn(); var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { max: 100, value: 100, orientation: "vertical", onSpotlightUp: handleSpotlight })); upKeyDown(incrementSlider.find("Slider.".concat(_IncrementSliderModule["default"].slider))); var expected = 'called once'; var actual = callCount(handleSpotlight); expect(actual).toBe(expected); }); test('should set "data-webos-voice-disabled" to increment button when voice control is disabled', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { "data-webos-voice-disabled": true, value: 10 })); var expected = true; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton)).prop('data-webos-voice-disabled'); expect(actual).toBe(expected); }); test('should set "data-webos-voice-disabled" to decrement button when voice control is disabled', function () { var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { "data-webos-voice-disabled": true, value: 10 })); var expected = true; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton)).prop('data-webos-voice-disabled'); expect(actual).toBe(expected); }); test('should set "data-webos-voice-group-label" to increment button when voice group label is set', function () { var label = 'voice control group label'; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { "data-webos-voice-group-label": label, value: 10 })); var expected = label; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].incrementButton)).prop('data-webos-voice-group-label'); expect(actual).toBe(expected); }); test('should set "data-webos-voice-group-label" to decrement button when voice group label is set', function () { var label = 'voice control group label'; var incrementSlider = (0, _enzyme.mount)(_react["default"].createElement(_IncrementSlider["default"], { "data-webos-voice-group-label": label, value: 10 })); var expected = label; var actual = incrementSlider.find("IconButton.".concat(_IncrementSliderModule["default"].decrementButton)).prop('data-webos-voice-group-label'); expect(actual).toBe(expected); }); });
import RxSwift import RxMVVM import AuthenticationServices class LoginViewController: ViewController<LoginViewModel>, ASAuthorizationControllerDelegate { @IBOutlet weak var signInWithAppleButtonStack: UIStackView! @IBOutlet weak var signInWithEmailButton: UIButton! @IBOutlet weak var signUpNowButton: UIButton! let signInWithAppleButton = ASAuthorizationAppleIDButton(type: .signIn, style: .black) lazy var loaderInteractor = LoaderInteractor(superview: view) override func viewDidLoad() { super.viewDidLoad() signInWithAppleButton.cornerRadius = 12.0 signInWithAppleButtonStack.addArrangedSubview(signInWithAppleButton) } override func bind(viewModel: ViewController<LoginViewModel>.ViewModel) { viewModel.isLoading.bind(to: loaderInteractor.rx.isLoading).disposed(by: disposeBag) signInWithEmailButton.rx.tap.bind(to: viewModel.signInWithEmail).disposed(by: disposeBag) signUpNowButton.rx.tap.bind(to: viewModel.signUp).disposed(by: disposeBag) signInWithAppleButton.rx.controlEvent(.touchUpInside).bind { [weak self] in self?.signInWithAppleAction() } .disposed(by: disposeBag) super.bind(viewModel: viewModel) } private func signInWithAppleAction() { let appleIDProvider = ASAuthorizationAppleIDProvider() let request = appleIDProvider.createRequest() request.requestedScopes = [.fullName, .email] let authorizationController = ASAuthorizationController(authorizationRequests: [request]) authorizationController.delegate = self authorizationController.performRequests() } // MARK: - ASAuthorizationControllerDelegate func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { guard let credential = authorization.credential as? ASAuthorizationAppleIDCredential, let tokenData = credential.authorizationCode, let token = String(data: tokenData, encoding: .utf8) else { return } let firstName = credential.fullName?.givenName let lastName = credential.fullName?.familyName #if DEBUG print("token:", token) #endif viewModel.handleAppleID(code: token, firstName: firstName, lastName: lastName) } }
// // MKBluetoothCenter.m // BlueTooth // // Created by mikazheng on 2021/10/28. // #import "MKBluetoothCenter.h" @interface MKBluetoothCenter () <CBCentralManagerDelegate, CBPeripheralDelegate> @property (nonatomic, weak) id <MKBluetoothCenterDelegate> delegate; @property (nonatomic, strong) CBCentralManager* cbCentralMgr; @property (nonatomic, strong) CBPeripheral* cbPeripheral; /// 供蓝牙打印使用 @property (nonatomic, strong) CBCharacteristic* cbCharacterWriter; @property (nonatomic, strong) NSMutableArray* services; @property (nonatomic, strong) NSMutableArray* characteristics; @property (nonatomic, strong) NSMutableArray* descriptors; @property (nonatomic, strong) NSArray* serviceUUIDs; @property (nonatomic, strong) NSArray* characteristicUUIDs; @property (nonatomic, assign) BOOL stopScanAfterConnected; @property (nonatomic, assign) NSInteger writeCount; @property (nonatomic, assign) NSInteger didWriteCount; @end @implementation MKBluetoothCenter + (MKBluetoothCenter *)sharedInstance { static MKBluetoothCenter* bluetoothMgr = nil; static dispatch_once_t once; dispatch_once(&once, ^{ bluetoothMgr = [[self alloc] init]; }); return bluetoothMgr; } - (void)initializeConfigWithDelegate:(id <MKBluetoothCenterDelegate>)delegate { self.delegate = delegate; /* 蓝牙没打开时,alert弹窗提示 */ NSDictionary *options = @{CBCentralManagerOptionShowPowerAlertKey: @(YES)}; self.cbCentralMgr = [[CBCentralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue() options:options]; self.discoverPeripherals = [NSMutableArray array]; self.services = [NSMutableArray array]; self.characteristics = [NSMutableArray array]; self.descriptors = [NSMutableArray array]; } - (void)_destroyCache { self.cbCharacterWriter = nil; [_services removeAllObjects]; [_characteristics removeAllObjects]; [_descriptors removeAllObjects]; } - (void)scanForPeripheralsWithServices:(NSArray *)serviceUUIDs stopScanAfterConnected:(BOOL)stopScanAfterConnected { self.stopScanAfterConnected = stopScanAfterConnected; [self stopScan]; [_discoverPeripherals removeAllObjects]; /* CBCentralManagerScanOptionAllowDuplicatesKey: NO 不重复扫描,设置为YES是在前台运行会一直扫描,除非主动stopScan */ [self.cbCentralMgr scanForPeripheralsWithServices:serviceUUIDs options: @{CBCentralManagerScanOptionAllowDuplicatesKey:@(NO)}]; if (_delegate && [_delegate respondsToSelector:@selector(startScan)]) { [_delegate startScan]; } } - (void)stopScan { if (self.cbCentralMgr.isScanning) { [self.cbCentralMgr stopScan]; if (_delegate && [_delegate respondsToSelector:@selector(stopScan)]) { [_delegate stopScan]; } } } - (void)connectPeripheral:(CBPeripheral*)peripheral serviceUUIDs:(NSArray *)serviceUUIDs characteristicUUIDs:(NSArray *)characteristicUUIDs { [self _destroyCache]; self.serviceUUIDs = serviceUUIDs; self.characteristicUUIDs = characteristicUUIDs; if (peripheral) { if (peripheral.state != CBPeripheralStateDisconnected) { NSLog(@"peripheral is not disconnected state"); return; } self.cbPeripheral = peripheral; self.cbPeripheral.delegate = self; } else { if (!self.cbPeripheral) { NSLog(@"peripheral can not be nil !!!"); return; } } /* options配置 CBConnectPeripheralOptionNotifyOnConnectionKey 在程序被挂起时,连接成功显示Alert提醒框 CBConnectPeripheralOptionNotifyOnDisconnectionKey 在程序被挂起时,断开连接显示Alert提醒框 CBConnectPeripheralOptionNotifyOnNotificationKey 在程序被挂起时,显示所有的提醒消息 */ [self.cbCentralMgr connectPeripheral:self.cbPeripheral options:nil]; if (_delegate && [_delegate respondsToSelector:@selector(connectingPeripheral:)]) { [_delegate connectingPeripheral:peripheral]; } } - (void)disconnect { if (self.cbPeripheral && self.cbPeripheral.state == CBPeripheralStateConnected) { self.cbPeripheral.delegate = self; [self.cbCentralMgr cancelPeripheralConnection:self.cbPeripheral]; self.cbPeripheral = nil; } } - (BOOL)isConnected { return (self.cbPeripheral.state == CBPeripheralStateConnected ? YES : NO); } - (BOOL)isConnectedWithIdentify:(NSString *)identify { if ([[self.cbPeripheral.identifier UUIDString] isEqualToString:identify]) { return (self.cbPeripheral.state == CBPeripheralStateConnected ? YES : NO); } else { return NO; } } #pragma mark - 蓝牙打印 - - (void)writeData:(NSData *)data { [self writeValue:data forCharacteristic:self.cbCharacterWriter type:CBCharacteristicWriteWithResponse]; } #pragma mark - 扩展 - - (NSArray *)currentCharacteristics { return [_characteristics copy]; } - (NSArray *)currentDescriptors { return [_descriptors copy]; } - (void)writeValue:(NSData *)data forCharacteristic:(CBCharacteristic *)characteristic type:(CBCharacteristicWriteType)type { if (!characteristic) { NSLog(@"characteristic can not be nil !!!"); if ([self isConnected]) { [_cbPeripheral discoverServices:_serviceUUIDs]; } if (_delegate && [_delegate respondsToSelector:@selector(writeResult:characteristic:)]) { [_delegate writeResult:NO characteristic:nil]; } } else { _writeCount = 0; _didWriteCount = 0; /* iOS9之后提供了查询蓝牙写入最大长度,目前测试的蓝牙设备,data长度超过maxLength也可以正常输出 */ NSInteger maxLength = [_cbPeripheral maximumWriteValueLengthForType:CBCharacteristicWriteWithResponse]; /// 防止个别设备出现传输异常,数据大于maxLength时使用分节传输 if ((maxLength <= 0) || (maxLength >= data.length)) { [self.cbPeripheral writeValue:data forCharacteristic:characteristic type:type]; _writeCount++; } else { NSInteger location = 0; /// 先取出maxLength大小的subData逐个写入 for (location = 0; location < data.length - maxLength; location += maxLength) { NSData *subData = [data subdataWithRange:NSMakeRange(location, maxLength)]; [_cbPeripheral writeValue:subData forCharacteristic:characteristic type:type]; _writeCount++; } /// 再取出小于maxLength的lastData写入 NSData *lastData = [data subdataWithRange:NSMakeRange(location, data.length - location)]; if (lastData) { [_cbPeripheral writeValue:lastData forCharacteristic:characteristic type:type]; _writeCount++; } } } } - (void)setNotifyValue:(BOOL)enabled forCharacteristic:(CBCharacteristic *)characteristic { [self.cbPeripheral setNotifyValue:enabled forCharacteristic:characteristic]; } - (void)readValueForCharacteristic:(CBCharacteristic *)characteristic { [self.cbPeripheral readValueForCharacteristic:characteristic]; } - (void)writeValue:(NSData *)data forDescriptor:(CBDescriptor *)descriptor { [self.cbPeripheral writeValue:data forDescriptor:descriptor]; } - (void)readValueForDescriptor:(CBDescriptor *)descriptor { [self.cbPeripheral readValueForDescriptor:descriptor]; } #pragma mark - CBCentralManagerDelegate - /// 收到了一个周围的蓝牙发来的广播信息 - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI { if (peripheral.name) { __block BOOL exist = NO; [_discoverPeripherals enumerateObjectsUsingBlock:^(CBPeripheral* _Nonnull tmpPeripheral, NSUInteger index, BOOL * _Nonnull stop) { if ([tmpPeripheral.identifier isEqual:peripheral.identifier]) { exist = YES; *stop = YES; } }]; if (exist == NO) { [_discoverPeripherals addObject:peripheral]; if (_delegate && [_delegate respondsToSelector:@selector(discoverPeripheral:)]) { [_delegate discoverPeripheral:peripheral]; } } } } /// 连接上当前蓝牙设备 - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral { if (_stopScanAfterConnected) { [self stopScan]; } [self.cbPeripheral discoverServices:_serviceUUIDs]; if (_delegate && [_delegate respondsToSelector:@selector(connectedPeripheral:error:)]) { [_delegate connectedPeripheral:peripheral error:nil]; } } /// 当前设备蓝牙断开 - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { if (_delegate && [_delegate respondsToSelector:@selector(disconnectPeripheral:)]) { [_delegate disconnectPeripheral:peripheral]; } [self _destroyCache]; } /// 蓝牙连接失败 - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error { if (_delegate && [_delegate respondsToSelector:@selector(connectedPeripheral:error:)]) { [_delegate connectedPeripheral:peripheral error:error]; } } /// 蓝牙中心状态更新 - (void)centralManagerDidUpdateState:(CBCentralManager *)central { NSMutableString* updateInfo=[NSMutableString stringWithString:@"UpdateState:"]; BOOL isAvailable = NO; switch (self.cbCentralMgr.state) { case CBManagerStateUnknown: [updateInfo appendString:@"Unknown\n"]; break; case CBManagerStateUnsupported: [updateInfo appendString:@"Unsupported\n"]; break; case CBManagerStateUnauthorized: [updateInfo appendString:@"Unauthorized\n"]; break; case CBManagerStateResetting: [updateInfo appendString:@"Resetting\n"]; break; case CBManagerStatePoweredOff: [updateInfo appendString:@"PoweredOff\n"]; if (self.cbPeripheral){ [self.cbCentralMgr cancelPeripheralConnection:self.cbPeripheral]; } break; case CBManagerStatePoweredOn: [updateInfo appendString:@"PoweredOn\n"]; isAvailable = YES; break; default: [updateInfo appendString:@"none\n"]; break; } NSLog(@"%@", updateInfo); if (_delegate && [_delegate respondsToSelector:@selector(centralManagerDidUpdateState:message:getStatus:)]) { [_delegate centralManagerDidUpdateState:isAvailable message:updateInfo getStatus:self.cbCentralMgr.state]; } } #pragma mark - CBPeripheralDelegate - /// 查询蓝牙服务 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error { if (error) { NSLog(@"DidDiscoverServicesFailed: %@", error.localizedDescription); [peripheral discoverServices:_serviceUUIDs]; } else { for (CBService *service in peripheral.services) { if (service.UUID.UUIDString.length == 36) { [_services addObject:service]; [peripheral discoverCharacteristics:_characteristicUUIDs forService:service]; } } } } /// 查询服务所带的特征值 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { if (error) { NSLog(@"DidDiscoverCharacteristicsFailed: %@", error.localizedDescription); [peripheral discoverCharacteristics:_characteristicUUIDs forService:service]; } else { for (CBCharacteristic *characteristic in [service characteristics]) { if (characteristic.UUID.UUIDString.length == 36) { if (!self.cbCharacterWriter && (characteristic.properties & CBCharacteristicPropertyWrite)) { self.cbCharacterWriter = characteristic; if (_delegate && [_delegate respondsToSelector:@selector(discoverCharacterWriter:)]) { [_delegate discoverCharacterWriter:characteristic]; } } [_characteristics addObject:characteristic]; [peripheral discoverDescriptorsForCharacteristic:characteristic]; } } } } /// 向蓝牙发送数据后的回调(Characteristic) - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (!error) { NSLog(@"DidWriteValueForCharacteristic"); } else{ NSLog(@"DidWriteValueForCharacteristicFail: %@", [error description]); } _didWriteCount++; if (_writeCount == _didWriteCount) { if (_delegate && [_delegate respondsToSelector:@selector(writeResult:characteristic:)]) { [_delegate writeResult:!error characteristic:characteristic]; } } } /// 处理蓝牙发过来的数据(Characteristic) - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (!error) { NSData* data = characteristic.value; if (_delegate && [_delegate respondsToSelector:@selector(receiveData:characteristic:source:)]) { [_delegate receiveData:data characteristic:characteristic source:BTReceiveSourceReadData]; } NSLog(@"DidUpdateValueForCharacteristic: %@", data); } else { NSLog(@"DidUpdateValueForCharacteristicFail: %@", [error description]); } } /// 已订阅特性的value更新回调 - (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (!error) { NSData* data = characteristic.value; if (_delegate && [_delegate respondsToSelector:@selector(receiveData:characteristic:source:)]) { [_delegate receiveData:data characteristic:characteristic source:BTReceiveSourceNotify]; } NSLog(@"didUpdateNotificationStateForCharacteristic: %@", data); } else { NSLog(@"DidUpdateNotificationStateForCharacteristicFail: %@", [error description]); } } /// 查询特性所带的描述 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error { if (error) { NSLog(@"DidDiscoverDescriptorsFailed: %@", error.localizedDescription); [peripheral discoverDescriptorsForCharacteristic:characteristic]; } else { for (CBDescriptor* descriptor in characteristic.descriptors) { if (descriptor.UUID.UUIDString.length == 36) { [_descriptors addObject:descriptor]; } } } } /// 向蓝牙发送数据后的回调(Descriptor) - (void)peripheral:(CBPeripheral *)peripheral didWriteValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error { if (!error) { NSLog(@"DidWriteValueForDescriptor"); } else { NSLog(@"DidWriteValueForDescriptorFail: %@", [error description]); } if (_delegate && [_delegate respondsToSelector:@selector(writeResult:descriptor:)]) { [_delegate writeResult:!error descriptor:descriptor]; } } /// 向蓝牙发送数据后的回调(Descriptor) - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(nullable NSError *)error { if (!error) { NSData* data = descriptor.value; if (_delegate && [_delegate respondsToSelector:@selector(receiveData:descriptor:)]) { [_delegate receiveData:data descriptor:descriptor]; } NSLog(@"DidUpdateValueForDescriptor: %@", data); } else { NSLog(@"DidUpdateValueForDescriptorFail: %@", [error description]); } } @end
import { useState } from 'react' import { Dialog } from '@headlessui/react' import { Bars3Icon, XMarkIcon } from '@heroicons/react/24/outline'; import { MdDownloadForOffline } from "react-icons/md"; import resumePdf from '../../../../assets/Resume of Akas Datta.pdf'; const navigation = [ { name: 'Home', href: '/' }, { name: 'About', href: '#about' }, { name: 'Projects', href: '#projects' }, { name: 'Experience', href: '#experience' }, { name: 'Contact', href: '#contact' }, ] const Navbar = () => { const handleDownload = () => { const link = document.createElement('a'); link.href = resumePdf; link.download = 'Resume of Akas Datta.pdf'; link.click(); }; const [mobileMenuOpen, setMobileMenuOpen] = useState(false) return ( <div className="px-12"> <header className="inset-x-0 top-0 z-50"> <nav className="flex items-center justify-between sm:pt-6 md:pt-6 lg:pt-6 sm:pb-0 md:pb-0 lg:pb-6" aria-label="Global"> <div className="flex lg:flex-1"> <a href="/" className="-m-1.5 p-1.5"> <h2 className="font-bold text-white text-4xl">Akas Datta</h2> </a> </div> <div className="flex lg:hidden"> <button type="button" className="-m-2.5 inline-flex items-center justify-center rounded-md p-2.5 text-gray-300" onClick={() => setMobileMenuOpen(true)} > <span className="sr-only">Open main menu</span> <Bars3Icon className="h-6 w-6" aria-hidden="true" /> </button> </div> <div className="hidden lg:flex lg:gap-x-8 bg-[#0F0F0F]"> {navigation.map((item) => ( <a key={item.name} href={item.href} className="font-semibold leading-6 text-gray-700 transition hover:text-gray-700/75 dark:text-white dark:hover:text-white/75 text-xl"> {item.name} </a> ))} </div> <div className="hidden lg:flex lg:flex-1 lg:justify-end"> <button onClick={handleDownload} className="text-sm font-semibold leading-6 text-gray-300 btn btn-outline rounded-lg px-10"> Resume <MdDownloadForOffline/> </button> </div> </nav> <Dialog as="div" className="lg:hidden" open={mobileMenuOpen} onClose={setMobileMenuOpen}> <div className="fixed inset-0 z-50" /> <Dialog.Panel className="fixed inset-y-0 right-0 z-50 w-full overflow-y-auto bg-black text-white px-6 py-6 sm:max-w-sm sm:ring-1 sm:ring-gray-900/10"> <div className="flex items-center justify-between"> <a href="#" className="-m-1.5 p-1.5"> </a> <button type="button" className="-m-2.5 rounded-md p-2.5 text-gray-300" onClick={() => setMobileMenuOpen(false)} > <span className="sr-only">Close menu</span> <XMarkIcon className="h-6 w-6" aria-hidden="true" /> </button> </div> <div className="mt-6 flow-root"> <div className="-my-6 divide-y divide-gray-500/10"> <div className="space-y-2 py-6"> {navigation.map((item) => ( <a key={item.name} href={item.href} className="-mx-3 block rounded-lg px-3 py-2 text-base font-semibold leading-7 text-gray-700 transition hover:text-gray-700/75 dark:text-white dark:hover:text-white/75 hover:bg-gray-900" > {item.name} </a> ))} </div> <div className="py-6"> <button onClick={handleDownload} className="text-sm font-semibold leading-6 text-gray-300 btn btn-outline rounded-lg px-10"> Resume <MdDownloadForOffline/> </button> </div> </div> </div> </Dialog.Panel> </Dialog> </header> </div> ); }; export default Navbar;
import * as React from "react"; import Box from "@mui/material/Box"; import Button from "@mui/material/Button"; import Typography from "@mui/material/Typography"; import Modal from "@mui/material/Modal"; import Image from "next/image"; import YouTube from "react-youtube"; import Carousel from "./Carousel/CarouselComponent"; const style = { position: "absolute", top: "50%", left: "50%", transform: "translate(-50%, -50%)", width:"50%", bgcolor: "black", color: "black", border: "2px solid #000", boxShadow: 24, p: 4, '@media (max-width: 700px)': { width:"100%", }, }; export default function BasicModal({ movie_img, movie_name, movie_overview,is_open,trailer_id,playTrailer,media_type,movie_id,modal_close}) { const [open, setOpen] = React.useState(false); const handleOpen = () => setOpen(true); const handleClose = () => { setOpen(false); modal_close(); } React.useEffect(()=>{ setOpen(is_open); },[is_open,playTrailer]) const render_trailer = () => { return ( <YouTube videoId={trailer_id} opts={{ width: '100%', height: '500', playerVars: { autoplay: 1, }, }} className = "flex flex-row justify-center items-center " /> ) } return ( <div> <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style} > <Typography id="modal-modal-description" sx={{ mt: 2 }}> {trailer_id && playTrailer ? render_trailer() : <Carousel media_type = {media_type} movie_id = {movie_id}/>} </Typography> </Box> </Modal> </div> ); }
import React from 'react'; import './App.css'; import Info from './info01'; import Friends from './address'; // 문제 1) 컴포넌트 info.01.js 파일을 생성 // → 자신의 간단한 정보를 출력하는 페이지 화면에 출력 // 참고 1) src 폴더 아래에 components01.js 생성 // 참고 2) 이름, 성별, 나이, 이메일, 주소 출력 // 참고 3) UI 구성은 원하는 방식대로 사용 // 문제 2) 친구의 정보를 출력하는 컴포넌트 address.js 파일을 생성 // → 친구의 간단한 정보를 화면에 출력 // 참고 1) src 폴더 아래에 컴포넌트 생성, address.js // 참고 2) 이름, 성별, 이메일 출력 // 참고 3) UI 구성은 자유롭게 // 참고 4) 2명 이상 출력 // 참고 5) 친구의 정보를 props를 통해서 하위 컴포넌트로 전달해 출력 function App() { return ( <div> <h1>Profile</h1> <hr></hr> <Info /> <hr></hr> <Friends name = "Cheolsoo" gender = "MALE" email = "FEH2O @ BSN.CO.KR" /> <hr></hr> <Friends name = "Yoory" gender = "FEMALE" email = "GLASSLEE @ BSN.CO.KR" /> {/* 여기에 출력하도록 컴포넌트 출력 */} </div> ); } export default App;
require("dotenv").config() const fs = require('fs'); const Booru = require('booru'); const blacklist = new Set(JSON.parse(fs.readFileSync('./blacklist').toString())); const { MessageEmbed } = require('discord.js') const gb = Booru.forSite('gb', { api_key: process.env.GELBOORU_API_KEY, user_id: process.env.GELBOORU_USER_ID }) const kn = Booru.forSite('kn') const dp = Booru.forSite('dp') async function gelbooru(channel, tags) { if(!channel.nsfw) tags.push("-rating:explicit", "-rating:questionable") let tagString = tags.join(', ') let tagArray = tags.concat(Array.from(blacklist).map(i=>'-'+i)) const posts = await gb.search(tagArray, {limit: 1, random: true}) console.log(gb.getSearchUrl({tags: tagArray, limit: 1})) if(posts.length == 0) return { errorMessage: `No posts found for tags ${tagString}` } const post = posts[0] let postUrl = post.postView if(tags.length > 0) postUrl += '&tags=' + tags.join('+') const embed = new MessageEmbed() .setColor("#337ab7") .setTitle("Gelbooru: " + post.id) .setURL(postUrl) .setImage(post.fileUrl) .setFooter({ text: `Size: ${post.width}x${post.height} | Posted: ${post.createdAt.toISOString().split('.')[0].replace("T", " ")}` }) return { embed } } async function konachan(channel, tags) { if(!channel.nsfw) tags.push("rating:safe") let tagString = tags.join(', ') let tagArray = tags.concat(Array.from(blacklist).map(i=>'-'+i)) const posts = await kn.search(tagArray, {limit: 1, random: true}) console.log(kn.getSearchUrl({tags: tagArray, limit: 1})) if(posts.length == 0) return { errorMessage: `No posts found for tags ${tagString}` } const post = posts[0] let postUrl = post.postView const embed = new MessageEmbed() .setColor("#337ab7") .setTitle("Konachan: " + post.id) .setURL(postUrl) .setImage(post.fileUrl) .setFooter({ text: `Size: ${post.width}x${post.height} | Posted: ${post.createdAt.toISOString().split('.')[0].replace("T", " ")}` }) return { embed } } async function derpi(tags) { let tagString = tags.join(', ') let tagArray = tags.concat(Array.from(blacklist).map(i=>'-'+i)) const posts = await dp.search(tagArray, {limit: 1, random: true}) console.log(dp.getSearchUrl({tags: tagArray, limit: 1})) if(posts.length == 0) return { errorMessage: `No posts found for tags ${tagString}` } const post = posts[0] let postUrl = post.postView if(tags.length > 0) postUrl += '&tags=' + tags.join('+') const embed = new MessageEmbed() .setColor("#337ab7") .setTitle("Derpibooru: " + post.id) .setURL(postUrl) .setImage(post.fileUrl) .setFooter({ text: `Size: ${post.width}x${post.height} | Posted: ${post.createdAt.toISOString().split('.')[0].replace("T", " ")}` }) return { embed } } module.exports = { gelbooru, konachan, derpi }