问:
Neo4jClient returns 403 FORBIDDEN: Request forbidden by administrative rules
When trying to add a relationship between two nodes in a neo4j instance using Neo4jClient, I get the following error: Request forbidden by administrative rules.

```<code>public async Task CreateFollowship(Guid followerId, Guid followedId)
    {
        await _neo4jClient.ConnectAsync();

        await _neo4jClient.Cypher
            .Match("(follower:User)", "(followed:User)")
            .Where($"(User follower) => follower.Id == {followerId}")
            .AndWhere($"(User followed) => followed.Id == {followedId}")
            .Create("follower-[:FOLLOWS]->followed")
            .ExecuteWithoutResultsAsync();
    }
</code>```

I've been following this documentation, isn't it outdated, is it? What am i doing wrong?

The query generated is (by example):

```<code>MATCH (follower:User), (followed:User) WHERE (User follower) => follower.Id == "970486dc-5430-4532-8ed3-e30efa930105" AND (User followed) => followed.Id == "f6a15b31-e328-4113-8541-3de8108b116d" CREATE follower-[:FOLLOWS]->followed
</code>```

I tried in other ways:

```<code>MATCH (follower:User), (followed:User) WHERE follower.Id == "970486dc-5430-4532-8ed3-e30efa930105" AND followed.Id == "f6a15b31-e328-4113-8541-3de8108b116d" CREATE follower-[:FOLLOWS]->followed
</code>```
```<code>MATCH (follower:User), (followed:User) WHERE follower.Id IS "970486dc-5430-4532-8ed3-e30efa930105" AND followed.Id IS "f6a15b31-e328-4113-8541-3de8108b116d" CREATE follower-[:FOLLOWS]->followed
</code>```

...

When running the command on the Neo4j Console using Cypher, i get different syntax errors with every attempt to fix. What is the correct syntax? An incorrect syntax is really the reason for the 403 error?

Body:
When trying to add a relationship between two nodes in a neo4j instance using Neo4jClient, I get the following error: Request forbidden by administrative rules.

public async Task CreateFollowship(Guid followerId, Guid followedId)
    {
        await _neo4jClient.ConnectAsync();

        await _neo4jClient.Cypher
            .Match("(follower:User)", "(followed:User)")
            .Where($"(User follower) => follower.Id == {followerId}")
            .AndWhere($"(User followed) => followed.Id == {followedId}")
            .Create("follower-[:FOLLOWS]->followed")
            .ExecuteWithoutResultsAsync();
    }

I've been following this documentation, isn't it outdated, is it? What am i doing wrong?

The query generated is (by example):

MATCH (follower:User), (followed:User) WHERE (User follower) => follower.Id == "970486dc-5430-4532-8ed3-e30efa930105" AND (User followed) => followed.Id == "f6a15b31-e328-4113-8541-3de8108b116d" CREATE follower-[:FOLLOWS]->followed

I tried in other ways:

MATCH (follower:User), (followed:User) WHERE follower.Id == "970486dc-5430-4532-8ed3-e30efa930105" AND followed.Id == "f6a15b31-e328-4113-8541-3de8108b116d" CREATE follower-[:FOLLOWS]->followed

MATCH (follower:User), (followed:User) WHERE follower.Id IS "970486dc-5430-4532-8ed3-e30efa930105" AND followed.Id IS "f6a15b31-e328-4113-8541-3de8108b116d" CREATE follower-[:FOLLOWS]->followed

...

When running the command on the Neo4j Console using Cypher, i get different syntax errors with every attempt to fix. What is the correct syntax? An incorrect syntax is really the reason for the 403 error?


来源: stackexchange

问:
unable to use `torch.gather` with 3D index and 3D input
I have an idx tensor with shape torch.Size([2, 80000, 3]), which corresponds to batch, points, and indices of 3 elements (from 0 to 512) from the feat tensor  with shape torch.Size([2, 513, 2]).

I cant seem to find a way to use torch.gather to index feat with idx with a resulting tensor with shape [2,8000,3,2].

ContentLicense: CC BY-SA 4.0


问:
Calculated Values of Mass and Area in Simple CAD Program are Very Incorrect
```<code># NG
import tkinter as tk

# Create the main window
window = tk.Tk()
window.title("Simple CAD")

# Define the size of the canvas inches
CANVAS_WIDTH = 5
CANVAS_HEIGHT = 5

# Define the size of the window pixels
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500

# Conversion factor to convert inches to pixels
INCHES_TO_PIXELS = 100

# Canvas for user to draw shape
canvas = tk.Canvas(window, width=CANVAS_WIDTH * INCHES_TO_PIXELS, height=CANVAS_HEIGHT * INCHES_TO_PIXELS)
canvas.pack()

# Create a list to store the coordinates of shape
shape_points = []

# Define function for mouse movement on the canvas
def handle_mouse_event(event):
    # Check if the mouse pointer is within bounds of canvas
    if 0 <= event.x <= CANVAS_WIDTH * INCHES_TO_PIXELS and 0 <= event.y <= CANVAS_HEIGHT * INCHES_TO_PIXELS:
        # Add the coordinates of the mouse event to the list of shape points
        shape_points.append((event.x, event.y))

        # Draw traced shape on the canvas
        if len(shape_points) > 1:
            canvas.create_line(shape_points[-2], shape_points[-1])

# Bind mouse inputs to the canvas
canvas.bind("<Button-1>", handle_mouse_event)
canvas.bind("<B1-Motion>", handle_mouse_event)
canvas.bind("<ButtonRelease-1>", handle_mouse_event)

# Define function to calculate area and volume of shape
def calculate_area_and_volume():
    # Check if the shape is closed
    if shape_points[0] != shape_points[-1]:
        # Add the first point to the end of the list to close the shape
        shape_points.append(shape_points[0])

    # User inputted extrude value
    extrude_length = float(input("Enter the extrude length in inches: "))

    # Calculate area of the shape in in^2
    area = 0
    for i in range(len(shape_points) - 1):
        x1, y1 = shape_points[i]
        x2, y2 = shape_points[i + 1]
        area += (x1 * y2) - (x2 * y1)
    area = abs(area) / 2

    # Vol calculation of object  in in^3
    volume = area * extrude_length

    # Output values
    print("Area:", area, "in^2")
    print("Volume:", volume, "in^3")

# Create button to close (fully define SolidWorks :/ traced shape
close_button = tk.Button(window, text="Close Shape", command=calculate_area_and_volume)
close_button.pack()
# Create button to calculate the area and volume
calculate_button = tk.Button(window, text="Calculate Area and Volume",
command=calculate_area_and_volume)
calculate_button.pack()

window.mainloop()
</code>```

Basically, this is a passion project of mine as a MechE student. I wanted to make a VERY simple CAD program with Python (the only language I know) in which a user can sketch an object, and then define a value for its thickness (extrude in CAD). To my knowledge, I have done the shoestring formula correctly for calculating area--basically just a derivation of Herons' Formula right?

Unfortunately, something is wrong because the canvas is set to 5x5 inches and this should theoretically mean absolute maximum area would be 25in^2, but when I tried drawing a square, it came out to be around 20,000 in^2. It was definitely not a perfect square, but if anything the area should have been less than 25 in^2.

I thought this was maybe an issue of the shape not being fully defined and therefore having near infinite area, but I implemented two different ways to make sure this doesn't happen. The first is a GUI button on the canvas that the user can click and it will close the shape for them. Even if they do not end up clicking this button, there is a second checker before the calculations to make sure that the shape is closed.
There's also a possibility I messed up the Shoestring formula like I alluded to above but that doesn't seem very likely.
I'm at a complete loss for why the calculations are this off and any help at all would be greatly appreciated!

Body:
# NG
import tkinter as tk

# Create the main window
window = tk.Tk()
window.title("Simple CAD")

# Define the size of the canvas inches
CANVAS_WIDTH = 5
CANVAS_HEIGHT = 5

# Define the size of the window pixels
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500

# Conversion factor to convert inches to pixels
INCHES_TO_PIXELS = 100

# Canvas for user to draw shape
canvas = tk.Canvas(window, width=CANVAS_WIDTH * INCHES_TO_PIXELS, height=CANVAS_HEIGHT * INCHES_TO_PIXELS)
canvas.pack()

# Create a list to store the coordinates of shape
shape_points = []

# Define function for mouse movement on the canvas
def handle_mouse_event(event):
    # Check if the mouse pointer is within bounds of canvas
    if 0 <= event.x <= CANVAS_WIDTH * INCHES_TO_PIXELS and 0 <= event.y <= CANVAS_HEIGHT * INCHES_TO_PIXELS:
        # Add the coordinates of the mouse event to the list of shape points
        shape_points.append((event.x, event.y))

        # Draw traced shape on the canvas
        if len(shape_points) > 1:
            canvas.create_line(shape_points[-2], shape_points[-1])

# Bind mouse inputs to the canvas
canvas.bind("<Button-1>", handle_mouse_event)
canvas.bind("<B1-Motion>", handle_mouse_event)
canvas.bind("<ButtonRelease-1>", handle_mouse_event)

# Define function to calculate area and volume of shape
def calculate_area_and_volume():
    # Check if the shape is closed
    if shape_points[0] != shape_points[-1]:
        # Add the first point to the end of the list to close the shape
        shape_points.append(shape_points[0])

    # User inputted extrude value
    extrude_length = float(input("Enter the extrude length in inches: "))

    # Calculate area of the shape in in^2
    area = 0
    for i in range(len(shape_points) - 1):
        x1, y1 = shape_points[i]
        x2, y2 = shape_points[i + 1]
        area += (x1 * y2) - (x2 * y1)
    area = abs(area) / 2

    # Vol calculation of object  in in^3
    volume = area * extrude_length

    # Output values
    print("Area:", area, "in^2")
    print("Volume:", volume, "in^3")

# Create button to close (fully define SolidWorks :/ traced shape
close_button = tk.Button(window, text="Close Shape", command=calculate_area_and_volume)
close_button.pack()
# Create button to calculate the area and volume
calculate_button = tk.Button(window, text="Calculate Area and Volume",
command=calculate_area_and_volume)
calculate_button.pack()

window.mainloop()

Basically, this is a passion project of mine as a MechE student. I wanted to make a VERY simple CAD program with Python (the only language I know) in which a user can sketch an object, and then define a value for its thickness (extrude in CAD). To my knowledge, I have done the shoestring formula correctly for calculating area--basically just a derivation of Herons' Formula right?

Unfortunately, something is wrong because the canvas is set to 5x5 inches and this should theoretically mean absolute maximum area would be 25in^2, but when I tried drawing a square, it came out to be around 20,000 in^2. It was definitely not a perfect square, but if anything the area should have been less than 25 in^2.

I thought this was maybe an issue of the shape not being fully defined and therefore having near infinite area, but I implemented two different ways to make sure this doesn't happen. The first is a GUI button on the canvas that the user can click and it will close the shape for them. Even if they do not end up clicking this button, there is a second checker before the calculations to make sure that the shape is closed.
There's also a possibility I messed up the Shoestring formula like I alluded to above but that doesn't seem very likely.
I'm at a complete loss for why the calculations are this off and any help at all would be greatly appreciated!


问:
Creating a new file in aws s3 (parquet/csv) via queries in aws Athena
Goal/Help Requested:
Given a bunch of tables in Athena, write an sql query that writes a scheduled new file into s3 to be used for other purposes.

Limited aws background - currently teaching myself but could use some help if possible.

Background
I have a very large number  of Athena tables that draw upon a very large  number of s3 folders with extensive nesting.

For example a 'sales' Athena table that draws upon a 'sales' s3 bucket that has depth of countries>regions>states>cities>stores>week>day.   I have similar other types of information.

I want to write various sql queries that take this information and apply some logic that writes back single files into s3 to be used for various other purposes I have.

What I'm looking for
Any sort of links/direction on how to do this.  Again I'm pretty new to aws and maybe this is a simple ask, I just can't articulate it properly.


问:
How to Prevent R from trying to open a file while knitting the document
I am trying to knit a Notebook in RStudio but am running into an issue with a very large zipped file. I do not want R to read or open the file when I knit the document. Every time I go to knit the document an error pops up saying 'No such file or directory.' The file path is correct but I am trying to work around this import.

I have tried using the following code to prevent R from running this code, but am still running into the same problem.

```<code>{r import-data, cache=FALSE}
{r, eval=FALSE}
</code>```

Body:
I am trying to knit a Notebook in RStudio but am running into an issue with a very large zipped file. I do not want R to read or open the file when I knit the document. Every time I go to knit the document an error pops up saying 'No such file or directory.' The file path is correct but I am trying to work around this import.

I have tried using the following code to prevent R from running this code, but am still running into the same problem.

{r import-data, cache=FALSE}
{r, eval=FALSE}


问:
p-Value for F-Statistics, pooled multiple linear Regression
I calculated the F-Value for pooled linear regression using miceadds::mi.anova.

I used the code from the post How to get R^2, F-statistics, and p-value for pooled models with imputed data? from @lanmi answered by jay.sf.

```<code>library('miceadds')
nul <- capture.output(
  aov_fit <- miceadds::mi.anova(mi.res=imp, formula="Y ~ A + B" )

(fval <- mean(round(aov_fit$anova.table$`F value`, 2), na.rm=TRUE) )

</code>```

This works fine

I want to calculate the p-Value as follwing:

```<code>df_mod <- aov_fit$anova.table$df1[- nrow(aov_fit$anova.table)]
df_res <- el(fit$analyses)$df.residual
c(df_mod, df_res)

pf(q=fval, df1=sum(df_mod), df_2=df_res, lower.tail=FALSE)
</code>```

But the result is:

```<code>df_res <- el(fit$analyses)$df.residual
Error in el(fit$analyses) : object 'fit' not found
</code>```

Has anyone the same problem? What am I doing wrong?

Thank you!

Body:
I calculated the F-Value for pooled linear regression using miceadds::mi.anova.

I used the code from the post How to get R^2, F-statistics, and p-value for pooled models with imputed data? from @lanmi answered by jay.sf.

library('miceadds')
nul <- capture.output(
  aov_fit <- miceadds::mi.anova(mi.res=imp, formula="Y ~ A + B" )

(fval <- mean(round(aov_fit$anova.table$`F value`, 2), na.rm=TRUE) )

This works fine

I want to calculate the p-Value as follwing:

df_mod <- aov_fit$anova.table$df1[- nrow(aov_fit$anova.table)]
df_res <- el(fit$analyses)$df.residual
c(df_mod, df_res)

pf(q=fval, df1=sum(df_mod), df_2=df_res, lower.tail=FALSE)

But the result is:

df_res <- el(fit$analyses)$df.residual
Error in el(fit$analyses) : object 'fit' not found

Has anyone the same problem? What am I doing wrong?

Thank you!


问:
In MySQL Workbench, should forward engineering an ER Diagram's foreign keys update the foreign keys in the schema?
I created this ER diagram using the foreign keys GUI on the bottom:enter image description here
After forward engineering it using the default settings, It hasn't updated my table and there are no foreign keys added on any of the schema's tables when I added foreign keys/relationships to everything on the ER Diagram. Is this normal?
enter image description here

I created a couple of tables, then reverse engineered it and added relationships, for several times I tried forward engineering it and no new foreign keys where added on schema's tables.

```<code>    -- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `midterm` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci ;
USE `midterm` ;

-- -----------------------------------------------------
-- Table `midterm`.`department`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`department` (
  `DepartmentID` INT NOT NULL,
  `DepartmentName` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`DepartmentID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`course` (
  `CourseID` INT NOT NULL,
  `CourseName` VARCHAR(45) NOT NULL,
  `Credits` INT NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`CourseID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor` (
  `InstructorID` INT NOT NULL,
  `InstructorName` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`InstructorID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor_course` (
  `TeachingAssignmentID` INT NOT NULL,
  `InstructorID` INT NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`TeachingAssignmentID`),
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  INDEX `InstructorID_idx` (`InstructorID` ASC) VISIBLE,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `InstructorID`
    FOREIGN KEY (`InstructorID`)
    REFERENCES `midterm`.`instructor` (`InstructorID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student` (
  `StudentID` CHAR(5) NOT NULL,
  `StudentName` VARCHAR(45) NOT NULL,
  `hairColor` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`StudentID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student_course` (
  `EnrolmentID` INT NOT NULL,
  `StudentID` CHAR(5) NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`EnrolmentID`),
  INDEX `StudentID_idx` (`StudentID` ASC) VISIBLE,
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  CONSTRAINT `StudentID`
    FOREIGN KEY (`StudentID`)
    REFERENCES `midterm`.`student` (`StudentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

    -- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `midterm` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci ;
USE `midterm` ;

-- -----------------------------------------------------
-- Table `midterm`.`department`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`department` (
  `DepartmentID` INT NOT NULL,
  `DepartmentName` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`DepartmentID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`course` (
  `CourseID` INT NOT NULL,
  `CourseName` VARCHAR(45) NOT NULL,
  `Credits` INT NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`CourseID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor` (
  `InstructorID` INT NOT NULL,
  `InstructorName` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`InstructorID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor_course` (
  `TeachingAssignmentID` INT NOT NULL,
  `InstructorID` INT NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`TeachingAssignmentID`),
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  INDEX `InstructorID_idx` (`InstructorID` ASC) VISIBLE,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `InstructorID`
    FOREIGN KEY (`InstructorID`)
    REFERENCES `midterm`.`instructor` (`InstructorID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student` (
  `StudentID` CHAR(5) NOT NULL,
  `StudentName` VARCHAR(45) NOT NULL,
  `hairColor` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`StudentID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student_course` (
  `EnrolmentID` INT NOT NULL,
  `StudentID` CHAR(5) NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`EnrolmentID`),
  INDEX `StudentID_idx` (`StudentID` ASC) VISIBLE,
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  CONSTRAINT `StudentID`
    FOREIGN KEY (`StudentID`)
    REFERENCES `midterm`.`student` (`StudentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
</code>```

Body:
I created this ER diagram using the foreign keys GUI on the bottom:enter image description here
After forward engineering it using the default settings, It hasn't updated my table and there are no foreign keys added on any of the schema's tables when I added foreign keys/relationships to everything on the ER Diagram. Is this normal?
enter image description here

I created a couple of tables, then reverse engineered it and added relationships, for several times I tried forward engineering it and no new foreign keys where added on schema's tables.

    -- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `midterm` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci ;
USE `midterm` ;

-- -----------------------------------------------------
-- Table `midterm`.`department`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`department` (
  `DepartmentID` INT NOT NULL,
  `DepartmentName` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`DepartmentID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`course` (
  `CourseID` INT NOT NULL,
  `CourseName` VARCHAR(45) NOT NULL,
  `Credits` INT NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`CourseID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor` (
  `InstructorID` INT NOT NULL,
  `InstructorName` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`InstructorID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor_course` (
  `TeachingAssignmentID` INT NOT NULL,
  `InstructorID` INT NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`TeachingAssignmentID`),
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  INDEX `InstructorID_idx` (`InstructorID` ASC) VISIBLE,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `InstructorID`
    FOREIGN KEY (`InstructorID`)
    REFERENCES `midterm`.`instructor` (`InstructorID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student` (
  `StudentID` CHAR(5) NOT NULL,
  `StudentName` VARCHAR(45) NOT NULL,
  `hairColor` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`StudentID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student_course` (
  `EnrolmentID` INT NOT NULL,
  `StudentID` CHAR(5) NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`EnrolmentID`),
  INDEX `StudentID_idx` (`StudentID` ASC) VISIBLE,
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  CONSTRAINT `StudentID`
    FOREIGN KEY (`StudentID`)
    REFERENCES `midterm`.`student` (`StudentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

    -- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';

-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema midterm
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `midterm` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci ;
USE `midterm` ;

-- -----------------------------------------------------
-- Table `midterm`.`department`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`department` (
  `DepartmentID` INT NOT NULL,
  `DepartmentName` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`DepartmentID`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`course` (
  `CourseID` INT NOT NULL,
  `CourseName` VARCHAR(45) NOT NULL,
  `Credits` INT NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`CourseID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor` (
  `InstructorID` INT NOT NULL,
  `InstructorName` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`InstructorID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`instructor_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`instructor_course` (
  `TeachingAssignmentID` INT NOT NULL,
  `InstructorID` INT NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`TeachingAssignmentID`),
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  INDEX `InstructorID_idx` (`InstructorID` ASC) VISIBLE,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `InstructorID`
    FOREIGN KEY (`InstructorID`)
    REFERENCES `midterm`.`instructor` (`InstructorID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student` (
  `StudentID` CHAR(5) NOT NULL,
  `StudentName` VARCHAR(45) NOT NULL,
  `hairColor` VARCHAR(45) NOT NULL,
  `DepartmentID` INT NOT NULL,
  PRIMARY KEY (`StudentID`),
  INDEX `DepartmentID_idx` (`DepartmentID` ASC) VISIBLE,
  CONSTRAINT `DepartmentID`
    FOREIGN KEY (`DepartmentID`)
    REFERENCES `midterm`.`department` (`DepartmentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

-- -----------------------------------------------------
-- Table `midterm`.`student_course`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `midterm`.`student_course` (
  `EnrolmentID` INT NOT NULL,
  `StudentID` CHAR(5) NOT NULL,
  `CourseID` INT NOT NULL,
  PRIMARY KEY (`EnrolmentID`),
  INDEX `StudentID_idx` (`StudentID` ASC) VISIBLE,
  INDEX `CourseID_idx` (`CourseID` ASC) VISIBLE,
  CONSTRAINT `StudentID`
    FOREIGN KEY (`StudentID`)
    REFERENCES `midterm`.`student` (`StudentID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `CourseID`
    FOREIGN KEY (`CourseID`)
    REFERENCES `midterm`.`course` (`CourseID`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;


问:
How do I write a 32-bit ARM ASM program to activate a loop using input from a wiringPi?
So I am creating a program that will cause an LED to blink on and off when a button is being pressed and held down, however, when I run the program that I have written, pressing the button will not initiate the LED's "blnkr" loop, are there any things I can fix with my program so that the LED's "blnkr" loop will run while the button's (BTN) input is returning HIGH?

// to compile: g++ redLed.s -lwiringPi -g -o redLed
// Program will power an LED when button is pressed, and when button is not pressed, LED will remain off

.equ INPUT, 0
.equ OUTPUT, 1
.equ LOW, 0
.equ HIGH, 1
.equ LED, 29    // wiringPi 29 (bcm 21 / physical 40)
.equ BTN, 28   // wiringPi 28 (bcm 20)

.text
.global main
main:
// int main()
    push {lr} // {
    bl wiringPiSetup // wiringPiSetup(); // initialize the wiringPi library

    mov r0, #LED // pinMode(29,OUTPUT); // set the wpi 29 pin for output
    mov r1, #OUTPUT
    bl pinMode

    mov r2, #BTN
    mov r1, #INPUT
    bl pinMode    // initiate r2 as input for wpi pin 28

do_while:
    mov r0, #LED
    mov r1, #LOW
    bl digitalWrite // turn off LED when button is not pressed

    mov r2, #BTN
    bl digitalRead    // r2 = digitalRead(BTN);

    cmp r2, #HIGH
    bleq blnkr       // if BTN is HIGH then branch with link to the blnkr loop
    b do_while

blnkr:
    cmp r2, #HIGH
    beq do_while

    mov r0, #LED // digitalWrite(29,HIGH); // write high volt signal to pin 21 to turn rgb led to red
    mov r1, #HIGH
    bl digitalWrite

    ldr r0, =#350 // delay(500); // delay for 500 milliseconds or 0.5 seconds
    bl delay

    mov r0, #LED // digitalWrite(29,LOW); // write low voltage to wpi 21 to turn off the rgb led
    mov r1, #LOW
    bl digitalWrite

    ldr r0, =#350
    bl delay
    b blnkr

    mov r0, #0 // return 0;
    pop {pc} // }

```

When I first tried to write this code, I attempted to make use of a while and do while loop, so the do while loop is supposed to run over and over again until the exit condition (BTN = HIGH) is met, then it should have branched into the blnkr loop where as long as BTN = HIGH the loop will repeat itself over and over while constantly checking after each iteration whether BTN = HIGH, however, when I run the program, the LED will remain off even when I press the button.

Body:
So I am creating a program that will cause an LED to blink on and off when a button is being pressed and held down, however, when I run the program that I have written, pressing the button will not initiate the LED's "blnkr" loop, are there any things I can fix with my program so that the LED's "blnkr" loop will run while the button's (BTN) input is returning HIGH?

// to compile: g++ redLed.s -lwiringPi -g -o redLed
// Program will power an LED when button is pressed, and when button is not pressed, LED will remain off

.equ INPUT, 0
.equ OUTPUT, 1
.equ LOW, 0
.equ HIGH, 1
.equ LED, 29    // wiringPi 29 (bcm 21 / physical 40)
.equ BTN, 28   // wiringPi 28 (bcm 20)

.text
.global main
main:
// int main()
    push {lr} // {
    bl wiringPiSetup // wiringPiSetup(); // initialize the wiringPi library

    mov r0, #LED // pinMode(29,OUTPUT); // set the wpi 29 pin for output
    mov r1, #OUTPUT
    bl pinMode

    mov r2, #BTN
    mov r1, #INPUT
    bl pinMode    // initiate r2 as input for wpi pin 28

do_while:
    mov r0, #LED
    mov r1, #LOW
    bl digitalWrite // turn off LED when button is not pressed

    mov r2, #BTN
    bl digitalRead    // r2 = digitalRead(BTN);

    cmp r2, #HIGH
    bleq blnkr       // if BTN is HIGH then branch with link to the blnkr loop
    b do_while

blnkr:
    cmp r2, #HIGH
    beq do_while

    mov r0, #LED // digitalWrite(29,HIGH); // write high volt signal to pin 21 to turn rgb led to red
    mov r1, #HIGH
    bl digitalWrite

    ldr r0, =#350 // delay(500); // delay for 500 milliseconds or 0.5 seconds
    bl delay

    mov r0, #LED // digitalWrite(29,LOW); // write low voltage to wpi 21 to turn off the rgb led
    mov r1, #LOW
    bl digitalWrite

    ldr r0, =#350
    bl delay
    b blnkr

    mov r0, #0 // return 0;
    pop {pc} // }

When I first tried to write this code, I attempted to make use of a while and do while loop, so the do while loop is supposed to run over and over again until the exit condition (BTN = HIGH) is met, then it should have branched into the blnkr loop where as long as BTN = HIGH the loop will repeat itself over and over while constantly checking after each iteration whether BTN = HIGH, however, when I run the program, the LED will remain off even when I press the button.


问:
Uploading to aws presigned url leads to error "The body of your POST request is not well-formed multipart/form-data."
I'm using the following code to upload a file to a presigned url s3:

```<code>        const fetchResult = await fetch('https://filesamples.com/samples/document/txt/sample3.txt');
        const length = (await fetchResult.arrayBuffer()).byteLength;
        formData.append('file', fetchResult.body, js.url);

        const final = await fetch(js.url, {
            body: formData as any,
            headers: {
                'content-length': '100'
            },
            method: 'POST'
        })
</code>```

However this is getting an error:

<Error>MalformedPOSTRequest<Message>The body of your POST request is not well-formed multipart/form-data.</Message><RequestId>TAQZJWHZ1CMH70GX</RequestId><HostId>fy6gvUJ8mPotohsv/M9XPvfc+k7kdwwjC6n1wsbIx9P5FU+f7bUzAq1tckOtl7gbgo5ch+yYyU0=</HostId></Error>

If I was to upload a straight up string like:

formData.append('file', 'test data');

and that works without erroring out.

Body:
I'm using the following code to upload a file to a presigned url s3:

        const fetchResult = await fetch('https://filesamples.com/samples/document/txt/sample3.txt');
        const length = (await fetchResult.arrayBuffer()).byteLength;
        formData.append('file', fetchResult.body, js.url);

        const final = await fetch(js.url, {
            body: formData as any,
            headers: {
                'content-length': '100'
            },
            method: 'POST'
        })

However this is getting an error:

<Error>MalformedPOSTRequest<Message>The body of your POST request is not well-formed multipart/form-data.</Message><RequestId>TAQZJWHZ1CMH70GX</RequestId><HostId>fy6gvUJ8mPotohsv/M9XPvfc+k7kdwwjC6n1wsbIx9P5FU+f7bUzAq1tckOtl7gbgo5ch+yYyU0=</HostId></Error>

If I was to upload a straight up string like:

formData.append('file', 'test data');

and that works without erroring out.


问:
Think CacheStoreMode.REFRESH is not working (Hibernate second level cache)
I tested the following code to study CacheStoreMode.

All of the procedures below were executed in order after one procedure was completed. The method proceeded with a web controller.

[Thread 1 : Register and store entities in the database and second level cache]

```<code>Member member = new Member();
member.setName("original");
em.persist(member);
</code>```

[DB console : Modify data on an entity]

```<code>update member set name = "changed" where member_id = 1;
/* Suppose that there is no other insert in the application, so you know that the id of the entity registered above is 1.
Because this query does not come from an application, keep in mind that the value of the second level cache has not changed, but only the value of the database has changed.*/
</code>```

[Thread 2 : Get data directly from DB and refresh the second level cache.]

```<code>Member member = em.createQuery("select m from Member m where m.id = 1", Member.class)
         .setHint("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS)
         .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
         .getSingleResult();

System.out.println(member.name);
</code>```

[Thread 3 : Gets the entity from the refreshed second level cache.]

```<code>Member member = em.find(Member.class, 1L);
System.out.println(member.name);
// can put CacheRetrieveMode.USE to make sure that "find" gets data from second level cache, but I omitted.
</code>```

So the result was this.

Thread 2 prints "changed"

and

Thread 3 prints "original"

This means that Thread2 normally fetched data from the database, but did not refresh the second level cache.

Thread3 did not fetch data from persistence context or DB. After Thread 3 started, the persistence context was initialized, and if data was taken from the DB, the data could not be "original".

I wonder if there is a problem with CacheStoreMode.REFRESH or if I misunderstand CacheStoreMode.REFRESH.

Body:
I tested the following code to study CacheStoreMode.

All of the procedures below were executed in order after one procedure was completed. The method proceeded with a web controller.

[Thread 1 : Register and store entities in the database and second level cache]

Member member = new Member();
member.setName("original");
em.persist(member);

[DB console : Modify data on an entity]

update member set name = "changed" where member_id = 1;
/* Suppose that there is no other insert in the application, so you know that the id of the entity registered above is 1.
Because this query does not come from an application, keep in mind that the value of the second level cache has not changed, but only the value of the database has changed.*/

[Thread 2 : Get data directly from DB and refresh the second level cache.]

Member member = em.createQuery("select m from Member m where m.id = 1", Member.class)
         .setHint("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS)
         .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
         .getSingleResult();

System.out.println(member.name);

[Thread 3 : Gets the entity from the refreshed second level cache.]

Member member = em.find(Member.class, 1L);
System.out.println(member.name);
// can put CacheRetrieveMode.USE to make sure that "find" gets data from second level cache, but I omitted.

So the result was this.

Thread 2 prints "changed"

and

Thread 3 prints "original"

This means that Thread2 normally fetched data from the database, but did not refresh the second level cache.

Thread3 did not fetch data from persistence context or DB. After Thread 3 started, the persistence context was initialized, and if data was taken from the DB, the data could not be "original".

I wonder if there is a problem with CacheStoreMode.REFRESH or if I misunderstand CacheStoreMode.REFRESH.


问:
How do I show the CWD in the iTerm2 prompt?
Specifically, my prompt is %~%# .  When I've descended into many directories, my prompt looks like this:

```<code>~/development/games/super-star-trek/lib%
</code>```

I'd like to shorten the paths like vim's pathshorten function:

```<code>~/d/g/s/lib%
</code>```

How can I do so in iTerm2?

(I'm not using oh-my-zsh)

Body:
Specifically, my prompt is %~%# .  When I've descended into many directories, my prompt looks like this:

~/development/games/super-star-trek/lib%

I'd like to shorten the paths like vim's pathshorten function:

~/d/g/s/lib%

How can I do so in iTerm2?

(I'm not using oh-my-zsh)


问:
Problem with voronoi library (scipy Voronoi, geovoronoi and libpysal Voronoi)
I'm having problems with several libraries and I can't think of a way to fix the problem.
When I perform Voronoi processing. Some polygons are generated "inwards" causing numerous polygon overlaps.

Here is the code snippet that generated the problem.
The same grid of points processed in Qgis presents no problem.

```<code>  p = []
  for i, df in enumerate(data_frame_new.X):
    p.append((data_frame_new.X[i], data_frame_new.Y[i]))

  p_array = np.array(p)
  p = coords_to_points(p_array)
</code>```

GEOVORONOI

```<code> region_df, point_df = voronoi_regions_from_coords(p, boundary_shape)
 gs = gpd.GeoSeries(region_df)
 region_df = gpd.GeoDataFrame(gs, columns=["geometry"])
</code>```

libpysal Voronoi

```<code>  region_df, point_df = voronoi_frames(p, radius=None, clip = boundary_shape)
  region_df = region_df.drop(columns=['area'], axis=1).reset_index(drop=True)
  region_df_clip = region_df.clip(ext)
</code>```

scipy Voronoi

```<code>coords = points_to_coords(data_frame_new.geometry)

vor = Voronoi(coords)
lines = [
    shapely.geometry.LineString(vor.vertices[line])
    for line in vor.ridge_vertices
    if -1 not in line
]
features = [i for i in range(len(lines))]
gdr = gpd.GeoDataFrame({'feature': features, 'geometry': lines})
</code>```

Body:
I'm having problems with several libraries and I can't think of a way to fix the problem.
When I perform Voronoi processing. Some polygons are generated "inwards" causing numerous polygon overlaps.

Here is the code snippet that generated the problem.
The same grid of points processed in Qgis presents no problem.

  p = []
  for i, df in enumerate(data_frame_new.X):
    p.append((data_frame_new.X[i], data_frame_new.Y[i]))

  p_array = np.array(p)
  p = coords_to_points(p_array)

GEOVORONOI

 region_df, point_df = voronoi_regions_from_coords(p, boundary_shape)
 gs = gpd.GeoSeries(region_df)
 region_df = gpd.GeoDataFrame(gs, columns=["geometry"])

libpysal Voronoi

  region_df, point_df = voronoi_frames(p, radius=None, clip = boundary_shape)
  region_df = region_df.drop(columns=['area'], axis=1).reset_index(drop=True)
  region_df_clip = region_df.clip(ext)

scipy Voronoi

coords = points_to_coords(data_frame_new.geometry)

vor = Voronoi(coords)
lines = [
    shapely.geometry.LineString(vor.vertices[line])
    for line in vor.ridge_vertices
    if -1 not in line
]
features = [i for i in range(len(lines))]
gdr = gpd.GeoDataFrame({'feature': features, 'geometry': lines})


问:
python opencv / why do i get different result with matchtemplate when image size differs?
I am trying to find a 67x45-sized rectangle on template images.

Both templates 1 and 2 are the same except template2 is a few pixels bigger.

What I don't get is that if I do matchtemplate on template2, it finds the wrong object while on template1, it doesn't.

Is there any reason why this is happening and any way to fix it?

Target:

template1:

template2:

```<code>def search():
    img = cv2.imread('./template2.png' , cv2.IMREAD_GRAYSCALE)
    target = cv2.imread('./test.png' , cv2.IMREAD_GRAYSCALE)

    #target = target.astype('uint8')

    print (target.shape)
    w, h = target.shape[::-1]

    res = cv2.matchTemplate(img, target, cv2.TM_CCORR_NORMED, mask = target)

    per = 1
    threshold = per
    loc = np.where(res>=threshold)

    if loc[0].any():
        for pt in zip(*loc[::-1]):
            cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (255), 1)
            #pass

        x = (pt[0]+(w/2))
        y = (pt[1]+(h/2))

        print (x, y)

        cv2.imshow("output", img)
        cv2.waitKey()
        cv2.destroyAllWindows()

        return x, y

search()
</code>```

matchtemplate with template1: works fine

matchtemplate with template2: finds two rectangles

Body:
I am trying to find a 67x45-sized rectangle on template images.

Both templates 1 and 2 are the same except template2 is a few pixels bigger.

What I don't get is that if I do matchtemplate on template2, it finds the wrong object while on template1, it doesn't.

Is there any reason why this is happening and any way to fix it?

Target:

template1:

template2:

def search():
    img = cv2.imread('./template2.png' , cv2.IMREAD_GRAYSCALE)
    target = cv2.imread('./test.png' , cv2.IMREAD_GRAYSCALE)

    #target = target.astype('uint8')

    print (target.shape)
    w, h = target.shape[::-1]

    res = cv2.matchTemplate(img, target, cv2.TM_CCORR_NORMED, mask = target)

    per = 1
    threshold = per
    loc = np.where(res>=threshold)

    if loc[0].any():
        for pt in zip(*loc[::-1]):
            cv2.rectangle(img, pt, (pt[0] + w, pt[1] + h), (255), 1)
            #pass

        x = (pt[0]+(w/2))
        y = (pt[1]+(h/2))

        print (x, y)

        cv2.imshow("output", img)
        cv2.waitKey()
        cv2.destroyAllWindows()

        return x, y

search()

matchtemplate with template1: works fine

matchtemplate with template2: finds two rectangles


问:
How to apply multiple action button cateogries in Objective-C?
https://useyourloaf.com/blog/local-notifications-with-ios-10/

I found this article which works if I just want to add one category of action buttons. But how should I add more than one category?

The code they provided:

UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"UYLReminderCategory"
  actions:@[snoozeAction,deleteAction] intentIdentifiers:@[]
  options:UNNotificationCategoryOptionNone];
NSSet *categories = [NSSet setWithObject:category];

[center setNotificationCategories:categories];
```


问:
Vertex Shader Depth Bias
What would be the most reliable way to apply a constant depth bias inside the vertex shader that remains a consistent depth offset at different camera depths?

I'm working in D3D12 + HLSL. I don't think that matters much, but I don't seem to have any built-in method to apply a depth bias for things like decals. The built-in D3D bias does not seem to be depth-independent. But its possible I'm using it incorrectly.

Currently, in the vertex shader, I'm applying an arbitrary negative offset to clip-space z after dividing by w, after transforming by the view-projection:

```<code>ClipPos.z = max( 0.0, ClipPos.z - (100.0/ClipPos.w) );
</code>```

The 100.0 here is my "bias". This is as close as I can get to the desired behavior. This is still not consistent at different depths, but is close. And I'm puzzled as to why I have to divide the bias by ClipPos.w here, since this line is before the GPU depth divide. Additionally, the 100.0 only buys me about 1.0 unit of world space depth, which also puzzles me, but isn't as important, since I can always scale if the influence change is linear.

My old engine simply offset the near plane distance, and that worked pretty well for decals. But I'd prefer to modify the position in the shader, if that's possible.

Edit:

This is the best solution I've been able to come up with. It works pretty well with a bias of around 1.5-2.0 for me, and does a pretty decent job of keeping the bias offset consistent regardless of camera depth.

The global variables should be pretty obvious, but please ask if something is not clear. After transforming the vertex position by the view-projection transform(s), you send clip-position-w to this method along with the bias amount, and it will return the value to store in clip-position-z:

```<code>inline float clipZBias(float clip_w,float depth_bias)
{
    // calculate near plane depth with bias offset
    float bias_near = Scene.Near + depth_bias / clip_w;

    // compute scale and translation based on updated near distance
    float bias_scale = Scene.Far / ( Scene.Far - bias_near );
    float bias_trans = bias_scale * -bias_near;

    // finally, compute and return the generated clip-space z value
    return bias_trans + clip_w * bias_scale;
}
</code>```

example:

```<code>lerp.ClipPos = mul( Scene.ViewProj, float4( lerp.WorldPos, 1.0f) );

// apply depth bias if enabled
#ifdef poly_depth_bias
    lerp.ClipPos.z = clipZBias( lerp.ClipPos.w, poly_depth_bias );
#endif
</code>```

Title: Vertex Shader Depth Bias

Body:
What would be the most reliable way to apply a constant depth bias inside the vertex shader that remains a consistent depth offset at different camera depths?

I'm working in D3D12 + HLSL. I don't think that matters much, but I don't seem to have any built-in method to apply a depth bias for things like decals. The built-in D3D bias does not seem to be depth-independent. But its possible I'm using it incorrectly.

Currently, in the vertex shader, I'm applying an arbitrary negative offset to clip-space z after dividing by w, after transforming by the view-projection:

ClipPos.z = max( 0.0, ClipPos.z - (100.0/ClipPos.w) );

The 100.0 here is my "bias". This is as close as I can get to the desired behavior. This is still not consistent at different depths, but is close. And I'm puzzled as to why I have to divide the bias by ClipPos.w here, since this line is before the GPU depth divide. Additionally, the 100.0 only buys me about 1.0 unit of world space depth, which also puzzles me, but isn't as important, since I can always scale if the influence change is linear.

My old engine simply offset the near plane distance, and that worked pretty well for decals. But I'd prefer to modify the position in the shader, if that's possible.

Edit:

This is the best solution I've been able to come up with. It works pretty well with a bias of around 1.5-2.0 for me, and does a pretty decent job of keeping the bias offset consistent regardless of camera depth.

The global variables should be pretty obvious, but please ask if something is not clear. After transforming the vertex position by the view-projection transform(s), you send clip-position-w to this method along with the bias amount, and it will return the value to store in clip-position-z:

inline float clipZBias(float clip_w,float depth_bias)
{
    // calculate near plane depth with bias offset
    float bias_near = Scene.Near + depth_bias / clip_w;

    // compute scale and translation based on updated near distance
    float bias_scale = Scene.Far / ( Scene.Far - bias_near );
    float bias_trans = bias_scale * -bias_near;

    // finally, compute and return the generated clip-space z value
    return bias_trans + clip_w * bias_scale;
}

example:

lerp.ClipPos = mul( Scene.ViewProj, float4( lerp.WorldPos, 1.0f) );

// apply depth bias if enabled
#ifdef poly_depth_bias
    lerp.ClipPos.z = clipZBias( lerp.ClipPos.w, poly_depth_bias );
#endif


问:
Express SQL Server Connection Pools
I've got an app that connects to a SQL Server database.  It has 3 post API's that are going to get A LOT of traffic.  I'm having trouble with connection timeout and want to make sure I have Connection Pooling setup correctly or figure out where I'm going wrong.  I have a DBConfig.js file setup as follows

```<code>var sql = require('mssql');
let curacaopool = null;

const curacao = () => {
  let config;

  if (null !== curacaopool) {
    return curacaopool;
  }

  if (process.env.APP_ENV === 'prod') {
    config = {
      user: 'user',
      password: 'password',
      server: 'IP Address',
      port: 51678,
      database: 'Database',
      connectionTimeout: 15000,
      //requestTimeout: 45000,
      pool: {
        max: 10,
        min: 1,
        idleTimeoutMillis: 30000
      }
    };
  }

  curacaopool = new sql.ConnectionPool(config).connect();
  return curacaopool;
};

module.exports = { curacao };
</code>```

My API's are setup as follows.  I have 3 of them.  The first API gets called and returns an ID then the next two API's get called

APIs

```<code>var express = require('express');
var router = express.Router();
var sql = require('mssql');
const { curacao } = require('../../../repository/getDbConfig');

router.post('/workstation', async function (req, res, next) {

  curacao()
    .then((pool) => pool.request())
    .then((request) => {

     for (const [key, value] of Object.entries(dbColumns)) {
        if (typeof value !== 'undefined' && value !== '') {
          request.input(key, dbTypes[key], value);
        }
      }

      request.input('ip_address', sql.VarChar, ip_address);

      request.output('workstationId', sql.Int);

      request.execute('Gumshoe.dbo.InsertWorkstations', (err, result) => {
        if (err) {
          res.status(500).json({ 'Workstation Error': err });
        }
        res.status(200).json({
          status: 200,
          message: 'Data Saved',
          workstationId: result.output.workstationId
        });
      });
    })
    .catch((err) => {
      console.log('Workstations Error', err);
      res.status(500).json({ 'Workstations Error': err });
    });

});

router.post('/packages', async function (req, res, next) {

  const sentdata = req.body;

  var table = new sql.Table('Database.dbo.Packages');
  table.create = false;
  table.columns.add('workstation_id', sql.Int, { nullable: true });
  table.columns.add('pkg_name', sql.VarChar, { nullable: true });
  table.columns.add('pkg_ver', sql.VarChar, { nullable: true });
  table.columns.add('appWizName', sql.VarChar, { nullable: true });
  table.columns.add('appWizPublisher', sql.VarChar, { nullable: true });
  table.columns.add('appWizInstalledOn', sql.Date, { nullable: true });
  table.columns.add('appWizVersion', sql.VarChar, { nullable: true });
  table.columns.add('appWizSize', sql.VarChar, { nullable: true });
  table.columns.add('customTrack1', sql.VarChar, { nullable: true });
  table.columns.add('customTrack2', sql.VarChar, { nullable: true });
  table.columns.add('customTrack3', sql.VarChar, { nullable: true });

  if (sentdata.length > 0) {
    sentdata.forEach((item) => {
      if (parseInt(item.workstation_id) > 0 && item.pkg_name.length > 1) {
        return table.rows.add(
          item.workstation_id,
          item.pkg_name,
          item?.pkg_ver || null,
          item?.appWizName || null,
          item?.appWizPublisher || null,
          item?.appWizInstalledOn ? (dateCheck(item.appWizInstalledOn) === true ? item.appWizInstalledOn : null) : null,
          item?.appWizVersion || null,
          item?.appWizSize || null,
          item?.customTrack1 || null,
          item?.customTrack2 || null,
          item?.customTrack3 || null
        );
      }
    });

    curacao()
      .then((pool) => pool.request())
      .then((request) =>
        request
          .bulk(table, (err, result) => {
            if (err) {
              console.log('Package Bulk Error:', err);
              res.status(500).json({ 'Bulk Packages': err });
            }
            res.status(200).json(result);
          })
          .catch((err) => {
            console.log('Packages Error', err);
            res.status(500).json({ 'Packages Error': err });
          })
      );
  } else {
    console.log('Package sent data was empty Array', sentdata);
    res.status(500).send('Package empty Array');
  }
});
</code>```

The first API calls a stored proc, this stored proc deletes data from the tables for the next two APIs.  The next two (both setup the same) do Bulk Inserts to two other tables

I'm having a lot of trouble with Timeout Errors

Webserver
returned:{"status":500,"pool_error":{"code":"ETIMEOUT","originalError":{"message":"Timeout:
Request failed to complete in 15000ms

I've tried increasing the pool Max to 25.  I've tried increased the requestTimeout value.  Both of those haven't worked or helped.  These work in test when not under heavy load so wondering what I look to next to get this resolved.

Thanks for any assistance

Title: Express SQL Server Connection Pools

Body:
I've got an app that connects to a SQL Server database.  It has 3 post API's that are going to get A LOT of traffic.  I'm having trouble with connection timeout and want to make sure I have Connection Pooling setup correctly or figure out where I'm going wrong.  I have a DBConfig.js file setup as follows

var sql = require('mssql');
let curacaopool = null;

const curacao = () => {
  let config;

  if (null !== curacaopool) {
    return curacaopool;
  }

  if (process.env.APP_ENV === 'prod') {
    config = {
      user: 'user',
      password: 'password',
      server: 'IP Address',
      port: 51678,
      database: 'Database',
      connectionTimeout: 15000,
      //requestTimeout: 45000,
      pool: {
        max: 10,
        min: 1,
        idleTimeoutMillis: 30000
      }
    };
  }

  curacaopool = new sql.ConnectionPool(config).connect();
  return curacaopool;
};

module.exports = { curacao };

My API's are setup as follows.  I have 3 of them.  The first API gets called and returns an ID then the next two API's get called

APIs

var express = require('express');
var router = express.Router();
var sql = require('mssql');
const { curacao } = require('../../../repository/getDbConfig');

router.post('/workstation', async function (req, res, next) {

  curacao()
    .then((pool) => pool.request())
    .then((request) => {

     for (const [key, value] of Object.entries(dbColumns)) {
        if (typeof value !== 'undefined' && value !== '') {
          request.input(key, dbTypes[key], value);
        }
      }

      request.input('ip_address', sql.VarChar, ip_address);

      request.output('workstationId', sql.Int);

      request.execute('Gumshoe.dbo.InsertWorkstations', (err, result) => {
        if (err) {
          res.status(500).json({ 'Workstation Error': err });
        }
        res.status(200).json({
          status: 200,
          message: 'Data Saved',
          workstationId: result.output.workstationId
        });
      });
    })
    .catch((err) => {
      console.log('Workstations Error', err);
      res.status(500).json({ 'Workstations Error': err });
    });

});

router.post('/packages', async function (req, res, next) {

  const sentdata = req.body;

  var table = new sql.Table('Database.dbo.Packages');
  table.create = false;
  table.columns.add('workstation_id', sql.Int, { nullable: true });
  table.columns.add('pkg_name', sql.VarChar, { nullable: true });
  table.columns.add('pkg_ver', sql.VarChar, { nullable: true });
  table.columns.add('appWizName', sql.VarChar, { nullable: true });
  table.columns.add('appWizPublisher', sql.VarChar, { nullable: true });
  table.columns.add('appWizInstalledOn', sql.Date, { nullable: true });
  table.columns.add('appWizVersion', sql.VarChar, { nullable: true });
  table.columns.add('appWizSize', sql.VarChar, { nullable: true });
  table.columns.add('customTrack1', sql.VarChar, { nullable: true });
  table.columns.add('customTrack2', sql.VarChar, { nullable: true });
  table.columns.add('customTrack3', sql.VarChar, { nullable: true });

  if (sentdata.length > 0) {
    sentdata.forEach((item) => {
      if (parseInt(item.workstation_id) > 0 && item.pkg_name.length > 1) {
        return table.rows.add(
          item.workstation_id,
          item.pkg_name,
          item?.pkg_ver || null,
          item?.appWizName || null,
          item?.appWizPublisher || null,
          item?.appWizInstalledOn ? (dateCheck(item.appWizInstalledOn) === true ? item.appWizInstalledOn : null) : null,
          item?.appWizVersion || null,
          item?.appWizSize || null,
          item?.customTrack1 || null,
          item?.customTrack2 || null,
          item?.customTrack3 || null
        );
      }
    });

    curacao()
      .then((pool) => pool.request())
      .then((request) =>
        request
          .bulk(table, (err, result) => {
            if (err) {
              console.log('Package Bulk Error:', err);
              res.status(500).json({ 'Bulk Packages': err });
            }
            res.status(200).json(result);
          })
          .catch((err) => {
            console.log('Packages Error', err);
            res.status(500).json({ 'Packages Error': err });
          })
      );
  } else {
    console.log('Package sent data was empty Array', sentdata);
    res.status(500).send('Package empty Array');
  }
});

The first API calls a stored proc, this stored proc deletes data from the tables for the next two APIs.  The next two (both setup the same) do Bulk Inserts to two other tables

I'm having a lot of trouble with Timeout Errors

Webserver
returned:{"status":500,"pool_error":{"code":"ETIMEOUT","originalError":{"message":"Timeout:
Request failed to complete in 15000ms

I've tried increasing the pool Max to 25.  I've tried increased the requestTimeout value.  Both of those haven't worked or helped.  These work in test when not under heavy load so wondering what I look to next to get this resolved.

Thanks for any assistance