问:
How to resize a small OpenCV videocapture window in Python?
I am making a rock paper scissors game using tensorflow in which the user can play with the computer through the webcam but the webcam image is too small like this : screenshot

Here is the snippet where i used OpenCV:

```<code>cap = cv2.VideoCapture(0)

prev_move = None

while True:
    ret, frame = cap.read()
    if not ret:
        continue

    # rectangle for user to play
    cv2.rectangle(frame, (100, 100), (500, 500), (255, 255, 255), 2)
    # rectangle for computer to play
    cv2.rectangle(frame, (800, 100), (1200, 500), (255, 255, 255), 2)

    # extract the region of image within the user rectangle
    roi = frame[100:500, 100:500]
    img = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (227, 227))

    # predict the move made
    pred = model.predict(np.array([img]))
    move_code = np.argmax(pred[0])
    user_move_name = mapper(move_code)

    # predict the winner (human vs computer)
    if prev_move != user_move_name:
        if user_move_name != "none":
            computer_move_name = choice(['rock', 'paper', 'scissors'])
            winner = calculate_winner(user_move_name, computer_move_name)
        else:
            computer_move_name = "none"
            winner = "Waiting..."
    prev_move = user_move_name

    # display the information
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(frame, "Your Move: " + user_move_name,
                (50, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA)
    cv2.putText(frame, "Computer's Move: " + computer_move_name,
                (750, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA)
    cv2.putText(frame, "Winner: " + winner,
                (400, 600), font, 2, (0, 0, 255), 4, cv2.LINE_AA)

    if computer_move_name != "none":
        icon = cv2.imread(
            "{}.png".format(computer_move_name))
        icon = cv2.resize(icon, (400, 400))
        frame[100:500, 800:1200] = icon

    cv2.imshow("Rock Paper Scissors", frame)

    k = cv2.waitKey(10)
    if k == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
</code>```

Is there a problem with my webcam I have tring resizing the frame but it does not work.

答:
You can resize by using this:</p>

```<code>width = 1500
height = 1080
dim = (width, height)

frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)
</code>```

Body:
I am making a rock paper scissors game using tensorflow in which the user can play with the computer through the webcam but the webcam image is too small like this : screenshot

Here is the snippet where i used OpenCV:

cap = cv2.VideoCapture(0)

prev_move = None

while True:
    ret, frame = cap.read()
    if not ret:
        continue

    # rectangle for user to play
    cv2.rectangle(frame, (100, 100), (500, 500), (255, 255, 255), 2)
    # rectangle for computer to play
    cv2.rectangle(frame, (800, 100), (1200, 500), (255, 255, 255), 2)

    # extract the region of image within the user rectangle
    roi = frame[100:500, 100:500]
    img = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (227, 227))

    # predict the move made
    pred = model.predict(np.array([img]))
    move_code = np.argmax(pred[0])
    user_move_name = mapper(move_code)

    # predict the winner (human vs computer)
    if prev_move != user_move_name:
        if user_move_name != "none":
            computer_move_name = choice(['rock', 'paper', 'scissors'])
            winner = calculate_winner(user_move_name, computer_move_name)
        else:
            computer_move_name = "none"
            winner = "Waiting..."
    prev_move = user_move_name

    # display the information
    font = cv2.FONT_HERSHEY_SIMPLEX
    cv2.putText(frame, "Your Move: " + user_move_name,
                (50, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA)
    cv2.putText(frame, "Computer's Move: " + computer_move_name,
                (750, 50), font, 1.2, (255, 255, 255), 2, cv2.LINE_AA)
    cv2.putText(frame, "Winner: " + winner,
                (400, 600), font, 2, (0, 0, 255), 4, cv2.LINE_AA)

    if computer_move_name != "none":
        icon = cv2.imread(
            "{}.png".format(computer_move_name))
        icon = cv2.resize(icon, (400, 400))
        frame[100:500, 800:1200] = icon

    cv2.imshow("Rock Paper Scissors", frame)

    k = cv2.waitKey(10)
    if k == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Is there a problem with my webcam I have tring resizing the frame but it does not work.

Body:
You can resize by using this:

width = 1500
height = 1080
dim = (width, height)

frame = cv2.resize(frame, dim, interpolation=cv2.INTER_AREA)


来源: stackexchange

问:
Create lead in D365 from PowerApps information

When 'Request Quote' is pressed, I want all the info from the text boxes to be sent to Dynamics 365 and for a lead entity to be created and filled out with all info.

答:
For other data sources, we usually do SubmitForm. But for CDS we have to use PATCH function.

Read more

```<code>Patch(
 "CDSEntityDataSource",
 Defaults(CDSEntityDataSource),
 {
   Column1:DataCardValue1.Text,
   Column2:DataCardValue2.Text,
   ...
 }
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For other data sources, we usually do SubmitForm. But for CDS we have to use PATCH function.

Read more

Patch(
 "CDSEntityDataSource",
 Defaults(CDSEntityDataSource),
 {
   Column1:DataCardValue1.Text,
   Column2:DataCardValue2.Text,
   ...
 }
)


问:
Svn to git: How to deal with our not-standard, probably wrongly branched svn
Our current svn structure looks like this:

```<code>trunk
-- project
-- projectDao
-- projectResources
branches
-- project-1.0
-- projectDao-1.0
-- projectResources-1.0
-- project-2.0
-- projectDao-2.0
-- projectResources-2.0
tags
-- project-1.0.0
-- ...
</code>```

To make things worse project-1.0 was branched from project projectDao-1.0 from projectDao (each in seperate move commits). Idealy it would have been like this.

This is the commit log:

```<code>trunk
-- project
-- projectDao
-- projectResources
branches
-- 1.0
---- project
---- projectDao
---- projectResources
-- 2.0
---- project
---- projectDao
---- projectResources
tags
--1.0.0
----project
---- ...
</code>```

And this is the way it makes sense. And we should then have branched from trunk to 1.0 instead of 2 different commits.

We however want to switch to git now (permanently) and I am at a loss how i should start with this.

I don't really get how i should do this. When i just git clone my repository with standard layout I get something this.

```<code>* master
  remotes/project-1.0
  remotes/project-1.0@3
  remotes/project-2.0
  remotes/project-2.0@10
  remotes/projectDao-1.0
  remotes/projectDao-1.0@4
  remotes/projectDao-2.0
  remotes/projectDao-2.0@11
  remotes/projectResources-1.0
  remotes/projectResources-1.0@5
  remotes/projectResources-2.0
  remotes/projectResources-2.0@12
  remotes/tags/project-1.0.0
  remotes/tags/projectDao-1.0.0
  remotes/tags/projectResources-1.0.0
  remotes/trunk
</code>```

This is what gitg generates

I don't know how I can use rebase to get this right like:

```<code>* master
  remotes/1.0
  remotes/2.0
  remotes/tags/1.0.0
  remotes/trunk
</code>```

答:
If I understand correctly, you want to change the imported branches to directories in a 1.0 branch. Furtheron you don't mention if this is a permanent migration or a git-svn checkout while you maintain your svn repository.

In case this is just a git-svn checkout and the goal is to keep working with the original SVN as central repository, I would just do a checkout without using the standard layout switch and work in the directories of SVN. It's a bit dirtier, but you don't have problems while pushing back to SVN.

In case you want to transform your repository, add a commit to all branches putting the contents of that branch into a directory in the root, to merge the branches together afterwards. You won't loose the SVN history with the old branch structure in your GIT history, but the future will be new-style.

Only in case you want to transform all of the history you will have to create directories and rebase.

ContentLicense: CC BY-SA 3.0

Body:
Our current svn structure looks like this:

trunk
-- project
-- projectDao
-- projectResources
branches
-- project-1.0
-- projectDao-1.0
-- projectResources-1.0
-- project-2.0
-- projectDao-2.0
-- projectResources-2.0
tags
-- project-1.0.0
-- ...

To make things worse project-1.0 was branched from project projectDao-1.0 from projectDao (each in seperate move commits). Idealy it would have been like this.

This is the commit log:

trunk
-- project
-- projectDao
-- projectResources
branches
-- 1.0
---- project
---- projectDao
---- projectResources
-- 2.0
---- project
---- projectDao
---- projectResources
tags
--1.0.0
----project
---- ...

And this is the way it makes sense. And we should then have branched from trunk to 1.0 instead of 2 different commits.

We however want to switch to git now (permanently) and I am at a loss how i should start with this.

I don't really get how i should do this. When i just git clone my repository with standard layout I get something this.

* master
  remotes/project-1.0
  remotes/project-1.0@3
  remotes/project-2.0
  remotes/project-2.0@10
  remotes/projectDao-1.0
  remotes/projectDao-1.0@4
  remotes/projectDao-2.0
  remotes/projectDao-2.0@11
  remotes/projectResources-1.0
  remotes/projectResources-1.0@5
  remotes/projectResources-2.0
  remotes/projectResources-2.0@12
  remotes/tags/project-1.0.0
  remotes/tags/projectDao-1.0.0
  remotes/tags/projectResources-1.0.0
  remotes/trunk

This is what gitg generates

I don't know how I can use rebase to get this right like:

* master
  remotes/1.0
  remotes/2.0
  remotes/tags/1.0.0
  remotes/trunk


问:
Golang stops navigation on downloading
Whenever I make a large download from my website using Go, it prevents me from navigating or doing anything else in my website in the same browser at the same time the download is happening. This happens with Firefox, chrome and Safari which makes me think it is a conf issue.

Go env

```<code>GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/root/.cache/go-build"
GOENV="/root/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build062753082=/tmp/go-build"
</code>```

Using the default GO Web server net/http for this.

EDIT:

Sorry forgot about the code for the download

```<code>func FunctionName(res http.ResponseWriter, req *http.Request, p httprouter.Params) {
    defer req.Body.Close()
    setSecurityHeaders(res)
    req.ParseForm()
    id := p.ByName("id")

    incletter, err := GetIncLetterById(bson.ObjectIdHex(id))
    if err != nil {
        jsonResponse(res, map[string]string{"status": "error", "message": "."})
        return
    }

    bytes, filename := incletter.GetFileBytes()

    res.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
    res.Header().Set("Content-type", "application/pdf")
    res.Header().Set("Content-Length", strconv.Itoa(len(bytes)))
    res.Write(bytes)
}
</code>```

答:
After hours of beeing troubled I reached out to my server provider and it was their fault, they had some kind of limited bandwith...
Thanks all</p>

Title: Golang stops navigation on downloading

Body:
Whenever I make a large download from my website using Go, it prevents me from navigating or doing anything else in my website in the same browser at the same time the download is happening. This happens with Firefox, chrome and Safari which makes me think it is a conf issue.

Go env

GO111MODULE=""
GOARCH="amd64"
GOBIN=""
GOCACHE="/root/.cache/go-build"
GOENV="/root/.config/go/env"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/usr/local/go"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build062753082=/tmp/go-build"

Using the default GO Web server net/http for this.

EDIT:

Sorry forgot about the code for the download

func FunctionName(res http.ResponseWriter, req *http.Request, p httprouter.Params) {
    defer req.Body.Close()
    setSecurityHeaders(res)
    req.ParseForm()
    id := p.ByName("id")

    incletter, err := GetIncLetterById(bson.ObjectIdHex(id))
    if err != nil {
        jsonResponse(res, map[string]string{"status": "error", "message": "."})
        return
    }

    bytes, filename := incletter.GetFileBytes()

    res.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
    res.Header().Set("Content-type", "application/pdf")
    res.Header().Set("Content-Length", strconv.Itoa(len(bytes)))
    res.Write(bytes)
}


问:
Three.js: how to use a plane to cut objects in 2 parts?
I have a complex object, i.e. a box, and I would like to cut it dynamically. This jsFiddle is a very simple example:jsFiddle

Very simple plane

```<code>var plane = new THREE.Mesh( geometry, material3 );
plane.rotation.x =1.3; // -Math.PI / 2;
gui.add(plane.rotation, "x", 0.1, Math.PI / 2).name("angle");
gui.add(plane.position, "y", -1, 1).name("h");
scene.add( plane );
</code>```

I would like to remove from my object the upper part. Just like to cut off a piece from an apple using a knife.

The plane is the knife: In my example, you can play with 2 controls to move the plane up and down or change the angle.

Can you help me to hide the removed part from the object?

答:
You've got two options:

You could use clipping as WestLangley mentioned above.

Clipping does not modify the vertex geometry, it's only visual.

Is non-destructive, so it's good for animating or making constant updates.

Clipping is mostly done with a few planes instead of complex geometry.

You could use a boolean operation with Constructive Solid Geometry.

Boolean does affect the vertex geometry, which can be exported.

Operation is "destructive", so you can't make updates once it's done.

Boolean can be performed with complex geometries, as long as they're "manifold".

Boolean operations require both geometries to be manifold geometries in order to work. This means both meshes have to be closed, without open faces. You cannot use infinitely thin planes, so the example in your JSFiddle wouldn't work. You would need to give each side a little bit of thickness, like using a box with a width of 0.0001 instead of a plane.

Body:
I have a complex object, i.e. a box, and I would like to cut it dynamically. This jsFiddle is a very simple example:jsFiddle

Very simple plane

var plane = new THREE.Mesh( geometry, material3 );
plane.rotation.x =1.3; // -Math.PI / 2;
gui.add(plane.rotation, "x", 0.1, Math.PI / 2).name("angle");
gui.add(plane.position, "y", -1, 1).name("h");
scene.add( plane );

I would like to remove from my object the upper part. Just like to cut off a piece from an apple using a knife.

The plane is the knife: In my example, you can play with 2 controls to move the plane up and down or change the angle.

Can you help me to hide the removed part from the object?


问:
How to search a 2d array to find max and mins in columns using pointers in standard C?
today I have a problem with searching a max and min value in a column. I did it with a row, but with columns something went wrong. It's a task for university, so I have to operate using pointers. So I wrote a function:

```<code>int column_statistics(const int *ptr, int width, int height, int column_id, int* max, int* min, float *avg){

  //problem generator
      if(ptr==NULL || width<=0 || height<=0 || column_id<0 || max==NULL || min==NULL || avg==NULL || column_id>(--width)){
        return 1;
  }

  int maximal;
  int minimal;
  int sum=0;

  for(int i=0;i<width;i++){
    printf("%d ",*(ptr+column_id*width+i));
    sum+=*(ptr+column_id*width+i);
    if(i==0){
      minimal=*(ptr+column_id*width+i);
      maximal=*(ptr+column_id*width+i);
      continue;
    }

    if(*(ptr+column_id*width+i)<maximal && *(ptr+column_id*width+i)>minimal){
      continue;
    }
    else if(*(ptr+column_id*width+i)>maximal){
      maximal=*(ptr+column_id*width+i);
    }
    else if(*(ptr+column_id*width+i)<minimal){
      minimal=*(ptr+column_id*width+i);
    }
  }

  *max=maximal;
  *min=minimal;
  *avg=(float)sum/(float)height;
  return 0;
}
</code>```

I think that it is OK, but when I am testing this in main:

```<code>#include <stdio.h>

int column_statistics(const int *ptr, int width, int height, int column_id, int* max, int* min, float *avg);

int main(void) {

  int input_array[3][5] = {{ 11, 81, -86, -63, 79}, { 94, -9, 11, -22, 72}, { 64, -61, 33, -36, -73}};
  int *ptr = input_array[0];
  int max, min, test;
  float a;

  for(int i=0; i<3; i++){
    printf("%d %d %d %d %d\n", *(ptr+i*5),*((ptr+i*5)+1),*((ptr+i*5)+2),*((ptr+i*5)+3),*((ptr+i*5)+4));
  }
  puts("============================================");
  for(int i=0;i<3;i++){
    column_statistics(ptr, 5, 3, i, &max, &min, &a);
    printf("Column %d: %d %d %.2f | Test: %d\n", ++i, max, min, a, test);
  }

  return 0;
}
</code>```

Something goes wrong and in output I have something like this:

(The inputed 2d-array)
11 81 -86 -63 79
94 -9 11 -22 72
64 -61 33 -36 -73

(The actual output of a function, the first string are the numbers that were in the function, than there is a max and min from column, average of a column, and test from "problem generator")

11 81 -86 -63 Column 1: 81 -86 -19.00 | Test: 0

79 94 -9 11 Column 2: 94 -9 58.33 | Test: 0

-22 72 64 -61 Column 3: 72 -61 17.67 | Test: 0

So the problem is that function loads only 4 variable instead of 5, but I don't know if the problem is in main or in the column_statistics. Guys, if you see what is wrong please, report this. Have a nice day and thanks for your time.

答:
The problem is most likely due to the condition column_id>(--width). That --width will modify the value of the variable. If you passed 5 for width, after --width the value will be 4.

That will affect your loops where you iterate using width, like for example the very first loop:

```<code>for(int i=0;i<width;i++){
</code>```

It will also affect all calculation you have suing width, like for example *(ptr+column_id*width+i).

If you want to compare column_id with width - 1 then use width - 1 instead (like column_id>(width-1)).

Body:
today I have a problem with searching a max and min value in a column. I did it with a row, but with columns something went wrong. It's a task for university, so I have to operate using pointers. So I wrote a function:

int column_statistics(const int *ptr, int width, int height, int column_id, int* max, int* min, float *avg){

  //problem generator
      if(ptr==NULL || width<=0 || height<=0 || column_id<0 || max==NULL || min==NULL || avg==NULL || column_id>(--width)){
        return 1;
  }

  int maximal;
  int minimal;
  int sum=0;

  for(int i=0;i<width;i++){
    printf("%d ",*(ptr+column_id*width+i));
    sum+=*(ptr+column_id*width+i);
    if(i==0){
      minimal=*(ptr+column_id*width+i);
      maximal=*(ptr+column_id*width+i);
      continue;
    }

    if(*(ptr+column_id*width+i)<maximal && *(ptr+column_id*width+i)>minimal){
      continue;
    }
    else if(*(ptr+column_id*width+i)>maximal){
      maximal=*(ptr+column_id*width+i);
    }
    else if(*(ptr+column_id*width+i)<minimal){
      minimal=*(ptr+column_id*width+i);
    }
  }

  *max=maximal;
  *min=minimal;
  *avg=(float)sum/(float)height;
  return 0;
}

I think that it is OK, but when I am testing this in main:

#include <stdio.h>

int column_statistics(const int *ptr, int width, int height, int column_id, int* max, int* min, float *avg);

int main(void) {

  int input_array[3][5] = {{ 11, 81, -86, -63, 79}, { 94, -9, 11, -22, 72}, { 64, -61, 33, -36, -73}};
  int *ptr = input_array[0];
  int max, min, test;
  float a;

  for(int i=0; i<3; i++){
    printf("%d %d %d %d %d\n", *(ptr+i*5),*((ptr+i*5)+1),*((ptr+i*5)+2),*((ptr+i*5)+3),*((ptr+i*5)+4));
  }
  puts("============================================");
  for(int i=0;i<3;i++){
    column_statistics(ptr, 5, 3, i, &max, &min, &a);
    printf("Column %d: %d %d %.2f | Test: %d\n", ++i, max, min, a, test);
  }

  return 0;
}

Something goes wrong and in output I have something like this:

(The inputed 2d-array)
11 81 -86 -63 79
94 -9 11 -22 72
64 -61 33 -36 -73

(The actual output of a function, the first string are the numbers that were in the function, than there is a max and min from column, average of a column, and test from "problem generator")

11 81 -86 -63 Column 1: 81 -86 -19.00 | Test: 0

79 94 -9 11 Column 2: 94 -9 58.33 | Test: 0

-22 72 64 -61 Column 3: 72 -61 17.67 | Test: 0

So the problem is that function loads only 4 variable instead of 5, but I don't know if the problem is in main or in the column_statistics. Guys, if you see what is wrong please, report this. Have a nice day and thanks for your time.

Body:
The problem is most likely due to the condition column_id>(--width). That --width will modify the value of the variable. If you passed 5 for width, after --width the value will be 4.

That will affect your loops where you iterate using width, like for example the very first loop:

for(int i=0;i<width;i++){

It will also affect all calculation you have suing width, like for example *(ptr+column_id*width+i).

If you want to compare column_id with width - 1 then use width - 1 instead (like column_id>(width-1)).


问:
How to click a button in an automated test using Selenium and Java
I'm trying to automate a test using Selenium and I want to click a button using xpath. This is what I'm doing:

```<code>WebElement LogInButton = driver.findElement(By.xpath("/login"));
LogInButton.click();
</code>```

But I get an error that says:

```<code>Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/login"}
</code>```

The only information I have about that button is this:

```<code><a href="/login">Login</a>
</code>```

and the URL where it redirects to.
What am I doing wrong? What would be the correct way of referring to this button? Any help please let me know. Thanks

答:
To invoke click() on the element you can use either of the following Locator Strategies:

Using linkText:

```<code>driver.findElement(By.linkText("Login")).click();
</code>```

Using cssSelector:

```<code>driver.findElement(By.cssSelector("a[href='/login']")).click();
</code>```

Using xpath:

```<code>driver.findElement(By.xpath("//a[@href='/login' and text()='Login']")).click();
</code>```

Best practices

As you are invoking click() ideally you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

Using linkText:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Login"))).click();
</code>```

Using cssSelector:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/login']"))).click();
</code>```

Using xpath:

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/login' and text()='Login']"))).click();
</code>```

Reference

You can find a couple of relevant discussions in:

NoSuchElementException, Selenium unable to locate element

Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: //*[@id='login-email']

Body:
I'm trying to automate a test using Selenium and I want to click a button using xpath. This is what I'm doing:

WebElement LogInButton = driver.findElement(By.xpath("/login"));
LogInButton.click();

But I get an error that says:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/login"}

The only information I have about that button is this:

Login

and the URL where it redirects to.
What am I doing wrong? What would be the correct way of referring to this button? Any help please let me know. Thanks

Body:
To invoke click() on the element you can use either of the following Locator Strategies:

Using linkText:

driver.findElement(By.linkText("Login")).click();

Using cssSelector:

driver.findElement(By.cssSelector("a[href='/login']")).click();

Using xpath:

driver.findElement(By.xpath("//a[@href='/login' and text()='Login']")).click();

Best practices

As you are invoking click() ideally you need to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:

Using linkText:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Login"))).click();

Using cssSelector:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/login']"))).click();

Using xpath:

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/login' and text()='Login']"))).click();

Reference

You can find a couple of relevant discussions in:

NoSuchElementException, Selenium unable to locate element

Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: //*[@id='login-email']


问:
.NET Core project not reading launchSettings.json
I have a web app using .NET Core 3.1, everything launches fine:

```<code>Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
</code>```

Only thing is that those ports aren't the ones specified in my launchSettings.json file.

A little back story: Originally both those localhosts were specified in the launchSettings.json file, then I eliminated the 5001 one, and it only started the 5000, which is what I wanted.

All of a sudden the 5001 is back, and no matter what I change in the launchSettings.json file it reverts to both 5000 and 5001, I event deleted the launchSettings.json file and it still listens on the same address/ports, I don't know where it's reading it from.

Just for reference, this is my current launchSettings.json file, it's supposed to be reading from the StudentsWebApp profile:

```<code>{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:61527",
      "sslPort": 44325
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "StudentsWebApp": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "http://localhost:5005",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</code>```

This is how I'm running the web app, just clicking the play button or F5 for the startup project:

Why is it bypassing my launchSettings.json file?

答:
After more searching around I got it to work:

Adding this in Project Properties > Debug Tab > Application arguments

```<code>--urls=http://localhost:5000/
</code>```

This way it reads exactly what address/port you want.

Body:
I have a web app using .NET Core 3.1, everything launches fine:

Now listening on: http://localhost:5000
Now listening on: https://localhost:5001

Only thing is that those ports aren't the ones specified in my launchSettings.json file.

A little back story: Originally both those localhosts were specified in the launchSettings.json file, then I eliminated the 5001 one, and it only started the 5000, which is what I wanted.

All of a sudden the 5001 is back, and no matter what I change in the launchSettings.json file it reverts to both 5000 and 5001, I event deleted the launchSettings.json file and it still listens on the same address/ports, I don't know where it's reading it from.

Just for reference, this is my current launchSettings.json file, it's supposed to be reading from the StudentsWebApp profile:

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:61527",
      "sslPort": 44325
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "StudentsWebApp": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "applicationUrl": "http://localhost:5005",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

This is how I'm running the web app, just clicking the play button or F5 for the startup project:

Why is it bypassing my launchSettings.json file?

Body:
After more searching around I got it to work:

Adding this in Project Properties > Debug Tab > Application arguments

--urls=http://localhost:5000/

This way it reads exactly what address/port you want.


问:
Tracking of an added object in the database
I have a Firebase Realtime Database. The user can do:

add item to the database

update item in the database

I have a function that tracks the database in a specific position. At the moment I have one function for new items and for updated items

This function will be called when there is something new and when there is an update of an existing object:

```<code>const readyForData = async () => {
    const ref = database().ref('users/' + user.id + '/data');
    ref.on('child_added', snapshot => {
        const ref = database().ref('/data/' + snapshot.key);
        ref.on('value', async (snapshot) => {
            if (snapshot.val()) {
                let data = snapshot.val() ? snapshot.val() : {};
            }
        })
    })
}
</code>```

Should I do two separate on() functions?

for new items

for object update

EDIT:

As above, I have a function that responds when we add a new object in the database or change an existing object.

How to rebuild it to make it work more efficiently? Can separate support for new and updated objects?

答: As stated here you should be able to track your data collection changes using onSnapshot function (adding or editing)</p>

Body:
I have a Firebase Realtime Database. The user can do:

add item to the database

update item in the database

I have a function that tracks the database in a specific position. At the moment I have one function for new items and for updated items

This function will be called when there is something new and when there is an update of an existing object:

const readyForData = async () => {
    const ref = database().ref('users/' + user.id + '/data');
    ref.on('child_added', snapshot => {
        const ref = database().ref('/data/' + snapshot.key);
        ref.on('value', async (snapshot) => {
            if (snapshot.val()) {
                let data = snapshot.val() ? snapshot.val() : {};
            }
        })
    })
}

Should I do two separate on() functions?

for new items

for object update

EDIT:

As above, I have a function that responds when we add a new object in the database or change an existing object.

How to rebuild it to make it work more efficiently? Can separate support for new and updated objects?


问:
Python's new `functools.cached_property` bug or limitation?
Since Python 3.8, functools has a cached_property.
I've been using a similar lazyprop decorator based on Beazley's cookbook (code below), but when I replace by the builtin, I get problems. Here's one of them.

When I use the decorator within the class definition, using the @ operator, it doesn't complain.

But if I use it with setattr, I get:

```<code>TypeError: Cannot use cached_property instance without calling __set_name__ on it.
</code>```

Beazley's simple version works fine though.

from functools import cached_property

class lazyprop:
    """Based on code from David Beazley's "Python Cookbook"."""
    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            value = instance.__dict__[self.func.__name__] = self.func(instance)
            return value

class D:
    def __init__(self, greeting='Hello'):
        self.greeting = greeting

def greet(self):
    return self.greeting + " world!"

# Beazley's version works...
D.greet = lazyprop(greet)
assert D().greet == "Hello world!"

# ... but the builtin version will fail
D.greet = cached_property(greet)
# D().greet  # this will fail
```

答:
TL;DR The cache is the instance dict itself, and the name of the property is needed as the key. The chosen design imposes the limitation, but (IMO) it's a good compromise. lazyprop is not thread-safe, or at least may call self.func more than is strictly necessary in a multi-threaded environment.

To start, it is documented that __set_name__ is only called if the assignment occurs in the context of type creation. The note in the documentation (adapted to your example) shows what you need to do: call __set_name__ yourself.

```<code>class D:
    def __init__(self, greeting='Hello'):
        self.greeting = greeting

    def greet(self):
        return self.greeting + " world!"

D.greet = cached_property(greet)
D.greet.__set_name__(D, 'greet')  # sets D.greet.attrname = "greet" for later use

assert D().greet == "hello world!"
</code>```

Why is the attribute name needed? cached_property.__set__ is not defined, so given d = D(), d.greet will first look for an instance attribute named greet in d.__dict__. If it is not found, then D.greet.__get__(d, D) will be called. That function basically does three things: it calls the original greet function if needed to compute the value, then saves it to a new instance attribute with the same name, and then returns the computed value.

"Wait", you ask, "what do you mean, 'if needed'? Didn't you just say D.greet.__get__ is only called if the instance attribute doesn't already exist?" Yes, but in a multithreaded environment, you don't know if another thread might also be executing D.greet.__get__ at the same time. In order to prevent a race condition, __get__ goes through the following steps (you can follow along in the code if you like):

Check for an instance attribute with the same name, in case it was created in another thread after the current call started.

If not, try to get a lock so we can create the instance attribute ourselves.

Once you get the lock, look for the instance attribute again, in case someone created it while we waited for the lock.

If the instance attribute still does not exist, we can safely create it ourselves.

Finally, whether we pulled a value from the instance attribute or called the original greet function ourselves, we can return the value.

With all this in mind, I would call this a limitation rather than a bug, but a limitation that is easily worked around. This implementation is probably simpler than one that tries not to rely on the name of the property itself for maintaining the necessary mapping.

Body:
Since Python 3.8, functools has a cached_property.
I've been using a similar lazyprop decorator based on Beazley's cookbook (code below), but when I replace by the builtin, I get problems. Here's one of them.

When I use the decorator within the class definition, using the @ operator, it doesn't complain.

But if I use it with setattr, I get:

TypeError: Cannot use cached_property instance without calling __set_name__ on it.

Beazley's simple version works fine though.

from functools import cached_property

class lazyprop:
    """Based on code from David Beazley's "Python Cookbook"."""
    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            value = instance.__dict__[self.func.__name__] = self.func(instance)
            return value

class D:
    def __init__(self, greeting='Hello'):
        self.greeting = greeting

def greet(self):
    return self.greeting + " world!"

# Beazley's version works...
D.greet = lazyprop(greet)
assert D().greet == "Hello world!"

# ... but the builtin version will fail
D.greet = cached_property(greet)
# D().greet  # this will fail

Body:
TL;DR The cache is the instance dict itself, and the name of the property is needed as the key. The chosen design imposes the limitation, but (IMO) it's a good compromise. lazyprop is not thread-safe, or at least may call self.func more than is strictly necessary in a multi-threaded environment.

To start, it is documented that __set_name__ is only called if the assignment occurs in the context of type creation. The note in the documentation (adapted to your example) shows what you need to do: call __set_name__ yourself.

class D:
    def __init__(self, greeting='Hello'):
        self.greeting = greeting

    def greet(self):
        return self.greeting + " world!"

D.greet = cached_property(greet)
D.greet.__set_name__(D, 'greet')  # sets D.greet.attrname = "greet" for later use

assert D().greet == "hello world!"

Why is the attribute name needed? cached_property.__set__ is not defined, so given d = D(), d.greet will first look for an instance attribute named greet in d.__dict__. If it is not found, then D.greet.__get__(d, D) will be called. That function basically does three things: it calls the original greet function if needed to compute the value, then saves it to a new instance attribute with the same name, and then returns the computed value.

"Wait", you ask, "what do you mean, 'if needed'? Didn't you just say D.greet.__get__ is only called if the instance attribute doesn't already exist?" Yes, but in a multithreaded environment, you don't know if another thread might also be executing D.greet.__get__ at the same time. In order to prevent a race condition, __get__ goes through the following steps (you can follow along in the code if you like):

Check for an instance attribute with the same name, in case it was created in another thread after the current call started.

If not, try to get a lock so we can create the instance attribute ourselves.

Once you get the lock, look for the instance attribute again, in case someone created it while we waited for the lock.

If the instance attribute still does not exist, we can safely create it ourselves.

Finally, whether we pulled a value from the instance attribute or called the original greet function ourselves, we can return the value.

With all this in mind, I would call this a limitation rather than a bug, but a limitation that is easily worked around. This implementation is probably simpler than one that tries not to rely on the name of the property itself for maintaining the necessary mapping.


问:
TypeError: string indices must be integers when using json file in python
I'm trying to count the number of national holidays N in each city in a .json file and I keep getting the error TypeError: string indices must be integers.

I've read a bunch of other posts about this error and I can't really find anything that helps. I'm assuming its related to how I'm pulling the .json file?
(encoding for non-english letters in file)

```<code>import json

world_hol_data = json.load(open("holiday_data.json", "r", encoding="utf8"))

total_national_hol = 0

for cont in world_hol_data:
    for city in cont:
        if city["type"] == "N":
            total_national_hol += 1
print(total_national_hol)
</code>```

答: Please first check your data variable to see what you received there. I guess at least a list containing with string whereas it should be a list of dictionaries.</p>

Body:
I'm trying to count the number of national holidays N in each city in a .json file and I keep getting the error TypeError: string indices must be integers.

I've read a bunch of other posts about this error and I can't really find anything that helps. I'm assuming its related to how I'm pulling the .json file?
(encoding for non-english letters in file)

import json

world_hol_data = json.load(open("holiday_data.json", "r", encoding="utf8"))

total_national_hol = 0

for cont in world_hol_data:
    for city in cont:
        if city["type"] == "N":
            total_national_hol += 1
print(total_national_hol)


问:
Python: Formatting wav data of variable length into specific length
I'm trying to create a program that will read and analyze .wav files, find the magnitude + frequency in regards to time, set it into an array ([time magnitude frequency] (id est: [x y z])) and run it through a neutral network. My issue is that I need a constant number of values, but the audio clips have differing lengths.

How can I 'average' (in a sense) the data in order to create an array of, for example, 20 000 values out of say 22050, as well as doing the same to an array of 17500?

Also would it be best to do this (if possible) with the raw .wav data, or with the magnitude/frequency

Edit: For clarification, I'm looking to keep the audio unchanged, so not speeding it up/slowing it down as I'm using it for a voice recognition program for my voice specifically.

I'm also looking to avoid adding null values to the end of the array, but I might have to resort to this.

答:
I'd suggest pre-processing the audio files in this case. If you are using the python "wave" library. You can use this to read a file and then write it out with a modified rate.

Eg:

```<code>...
outfile = wave.open("processed.wav", "rb")
outfile.setframerate(original_rate/factor)
...
</code>```

If factor is > 1 then you will shorten the file (fastplay) if it's < 1 you will "stretch" (slowplay). You can calculate the factor easily based on goal_length/actual_length.

Body:
I'd suggest pre-processing the audio files in this case. If you are using the python "wave" library. You can use this to read a file and then write it out with a modified rate.

Eg:

...
outfile = wave.open("processed.wav", "rb")
outfile.setframerate(original_rate/factor)
...

If factor is > 1 then you will shorten the file (fastplay) if it's < 1 you will "stretch" (slowplay). You can calculate the factor easily based on goal_length/actual_length.


问:
Access the containing object in a constructor function
I want to access the parent object when calling a function contained inside that object as a constructor. See this example:

```<code>var users = {
    // The count of users
    count: 0,

    // Naturally _this is undefined
    _this: this,

    // Constructor function
    CreateUser: function (name, email) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        users.count++;
    },

    getCount: function () {
        return this.count;
    },
};
</code>```

If I try to invoke the CreateUser function as a constructor, then this will be a reference to the blank object that the new operator created. See this:

```<code>var user = new users.CreateUser('Rick', 'rick@example.com')
</code>```

How can I access the users containing object in this case without explicitly referring to it?

答:
Pass it as an explicit parameter.</p>

```<code>var users = {
    count: 0,
    _this: this,

    // Constructor function
    CreateUser: function (name, email, parent) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        parent.count++;
    },

    getCount: function () {
        return this.count;
    },
};

var user = new users.CreateUser('Rick', 'rick@example.com', users);
</code>```

Body:
I want to access the parent object when calling a function contained inside that object as a constructor. See this example:

var users = {
    // The count of users
    count: 0,

    // Naturally _this is undefined
    _this: this,

    // Constructor function
    CreateUser: function (name, email) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        users.count++;
    },

    getCount: function () {
        return this.count;
    },
};

If I try to invoke the CreateUser function as a constructor, then this will be a reference to the blank object that the new operator created. See this:

var user = new users.CreateUser('Rick', 'rick@example.com')

How can I access the users containing object in this case without explicitly referring to it?

Body:
Pass it as an explicit parameter.

var users = {
    count: 0,
    _this: this,

    // Constructor function
    CreateUser: function (name, email, parent) {
        this.name = name;
        this.email = email;

        // Is this the only way to access the containing object?
        parent.count++;
    },

    getCount: function () {
        return this.count;
    },
};

var user = new users.CreateUser('Rick', 'rick@example.com', users);


问:
Drawing on JavaFX canvas does nothing
I am trying to draw an oval in a canvas but fillOval does nothing.
There are no exceptions or errors. While debugging it seems to get to the code and run it but nothing appears on the screen.

code (only the relevant package): https://github.com/amnon3234/PTM_Project/tree/master/PTM_Project_Final/src/view

specific parts:
My canvas:

```<code>public class HeightMapDisplayer extends Canvas {

    public HeightMapDisplayer() {
        GraphicsContext gc = this.getGraphicsContext2D();
        gc.setFill(Color.RED);
        gc.fillOval(10,10,40,40);
    }
}
</code>```

My controller:

```<code>public class MainWindowController implements Initializable {
    @FXML
    HeightMapDisplayer _heightMap;

    // Constructor , Initialize data
    public MainWindowController() {
        _heightMap = new HeightMapDisplayer();
    }
}
</code>```

My XML:

```<code><BorderPane xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.MainWindowController">
   <left>
    ...
               <HeightMapDisplayer fx:id="heightMap" height="400.0" width="400.0" />
    ...
</BorderPane>
</code>```

Result:

答:
The problem is that you are trying to draw on the canvas before you set the width and height. Because your Canvas subclass implicitly invokes the default Canvas constructor, which sets the width and height to zero, then in the constructor you perform the drawing. Since this drawing happens outside the bounds of the canvas, nothing appears. The width and height attributes in the FXML cause the setWidth() and setHeight() methods to be invoked, but of course this happens after the constructor call is complete, by which time it is too late.

A "quick fix" is to allow the width and height to be passed to your constructor, so you can pass them on to the Canvas constructor:

```<code>public class HeightMapDisplayer extends Canvas {

    public HeightMapDisplayer(
            @NamedArg("width") double width,
            @NamedArg("height") double height) {

        super(width, height);
        GraphicsContext gc = this.getGraphicsContext2D();
        gc.setFill(Color.RED);
        gc.fillOval(10,10,40,40);
    }
}
</code>```

However, it is generally a bad idea to subclass JavaFX node classes (other than those specifically written with the intention of subclassing them, such as Cells). A much better approach is to use a MVC approach: define a model class encapsulating the data you want to represent on the canvas, define a controller to do the drawing, and just use a plain Canvas.

E.g. the (mock) model class might look like

```<code>public class HeightMap {

    // data you need here...
    private int offset ;
    private int size ;

    public int getOffset() {
        return offset;
    }
    public void setOffset(int offset) {
        this.offset = offset;
    }
    public int getSize() {
        return size;
    }
    public void setSize(int size) {
        this.size = size;
    }

}
</code>```

with a controller class

```<code>import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

public class HeightMapController {

    private final Canvas view ;
    private HeightMap model ;

    public HeightMapController(Canvas view) {
        this.view = view ;
    }

    public void setModel(HeightMap model) {
        this.model = model ;
        GraphicsContext gc = view.getGraphicsContext2D();
        gc.setFill(Color.RED);
        gc.fillOval(model.getOffset(), model.getOffset(), model.getSize(), model.getSize());
    }

}
</code>```

Here's an updated MainWindowController:

```<code>import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;

public class MainWindowController implements Initializable {
    @FXML
    private Canvas heightMap;

    private HeightMapController heightMapController ;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        heightMapController = new HeightMapController(heightMap);
    }

    public void setHeightMapModel(HeightMap heightMapModel) {
        heightMapController.setModel(heightMapModel);
    }
}
</code>```

and FXML file:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane xmlns="http://javafx.com/javafx/10.0.2-internal"
    xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="org.jamesd.examples.canvas.MainWindowController">
    <left>
        <Canvas fx:id="heightMap"
            height="400" width="400" />
    </left>
</BorderPane>
```

<p>and finally the code that assembles everything:</p>

```import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
        Scene scene = new Scene(loader.load());
        MainWindowController controller = loader.getController();
        HeightMap heightMap = new HeightMap();
        heightMap.setOffset(10);
        heightMap.setSize(40);
        controller.setHeightMapModel(heightMap);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}
```

There are other techniques that can make this a bit cleaner, e.g. using a controller factory to instantiate controllers with the model already present, or using a dependency injection framework to achieve the same thing, but this should give you the idea of the correct structure.

Title: Drawing on JavaFX canvas does nothing

Body:
I am trying to draw an oval in a canvas but fillOval does nothing.
There are no exceptions or errors. While debugging it seems to get to the code and run it but nothing appears on the screen.

code (only the relevant package): https://github.com/amnon3234/PTM_Project/tree/master/PTM_Project_Final/src/view

specific parts:
My canvas:

public class HeightMapDisplayer extends Canvas {

    public HeightMapDisplayer() {
        GraphicsContext gc = this.getGraphicsContext2D();
        gc.setFill(Color.RED);
        gc.fillOval(10,10,40,40);
    }
}

My controller:

public class MainWindowController implements Initializable {
    @FXML
    HeightMapDisplayer _heightMap;

    // Constructor , Initialize data
    public MainWindowController() {
        _heightMap = new HeightMapDisplayer();
    }
}

My XML:

<BorderPane xmlns="http://javafx.com/javafx/10.0.2-internal" xmlns:fx="http://javafx.com/fxml/1" fx:controller="view.MainWindowController">
   <left>
    ...
               <HeightMapDisplayer fx:id="heightMap" height="400.0" width="400.0" />
    ...
</BorderPane>

Result:

Body:
The problem is that you are trying to draw on the canvas before you set the width and height. Because your Canvas subclass implicitly invokes the default Canvas constructor, which sets the width and height to zero, then in the constructor you perform the drawing. Since this drawing happens outside the bounds of the canvas, nothing appears. The width and height attributes in the FXML cause the setWidth() and setHeight() methods to be invoked, but of course this happens after the constructor call is complete, by which time it is too late.

A "quick fix" is to allow the width and height to be passed to your constructor, so you can pass them on to the Canvas constructor:

public class HeightMapDisplayer extends Canvas {

    public HeightMapDisplayer(
            @NamedArg("width") double width,
            @NamedArg("height") double height) {

        super(width, height);
        GraphicsContext gc = this.getGraphicsContext2D();
        gc.setFill(Color.RED);
        gc.fillOval(10,10,40,40);
    }
}

However, it is generally a bad idea to subclass JavaFX node classes (other than those specifically written with the intention of subclassing them, such as Cells). A much better approach is to use a MVC approach: define a model class encapsulating the data you want to represent on the canvas, define a controller to do the drawing, and just use a plain Canvas.

E.g. the (mock) model class might look like

public class HeightMap {

    // data you need here...
    private int offset ;
    private int size ;

    public int getOffset() {
        return offset;
    }
    public void setOffset(int offset) {
        this.offset = offset;
    }
    public int getSize() {
        return size;
    }
    public void setSize(int size) {
        this.size = size;
    }

}

with a controller class

import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

public class HeightMapController {

    private final Canvas view ;
    private HeightMap model ;

    public HeightMapController(Canvas view) {
        this.view = view ;
    }

    public void setModel(HeightMap model) {
        this.model = model ;
        GraphicsContext gc = view.getGraphicsContext2D();
        gc.setFill(Color.RED);
        gc.fillOval(model.getOffset(), model.getOffset(), model.getSize(), model.getSize());
    }

}

Here's an updated MainWindowController:

import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.canvas.Canvas;

public class MainWindowController implements Initializable {
    @FXML
    private Canvas heightMap;

    private HeightMapController heightMapController ;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        heightMapController = new HeightMapController(heightMap);
    }

    public void setHeightMapModel(HeightMap heightMapModel) {
        heightMapController.setModel(heightMapModel);
    }
}

and FXML file:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.canvas.Canvas?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane xmlns="http://javafx.com/javafx/10.0.2-internal"
    xmlns:fx="http://javafx.com/fxml/1"
    fx:controller="org.jamesd.examples.canvas.MainWindowController">
    <left>
        <Canvas fx:id="heightMap"
            height="400" width="400" />
    </left>
</BorderPane>

and finally the code that assembles everything:

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
        Scene scene = new Scene(loader.load());
        MainWindowController controller = loader.getController();
        HeightMap heightMap = new HeightMap();
        heightMap.setOffset(10);
        heightMap.setSize(40);
        controller.setHeightMapModel(heightMap);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }

}

There are other techniques that can make this a bit cleaner, e.g. using a controller factory to instantiate controllers with the model already present, or using a dependency injection framework to achieve the same thing, but this should give you the idea of the correct structure.


问:
Why does aggregate GROUPBY() COUNT(*) of 0's not show up in the query?
This is a problem I'm not sure I've run into before (and frankly didn't know it existed). I am grouping by YEAR and MONTH for monthly time-series analysis but COUNTs of 0's are not showing up in the output. Here is the query:

```<code>SELECT
    ROW_NUMBER() OVER(
        ORDER BY YEAR(order_date), MONTH(order_date)) AS 'Index',
    YEAR(order_date) AS 'Year',
    MONTH(order_date) AS 'Month',
    CONCAT(CASE
                WHEN MONTH(order_date) = 1 THEN 'Jan'
                WHEN MONTH(order_date) = 2 THEN 'Feb'
                WHEN MONTH(order_date) = 3 THEN 'Mar'
                WHEN MONTH(order_date) = 4 THEN 'Apr'
                WHEN MONTH(order_date) = 5 THEN 'May'
                WHEN MONTH(order_date) = 6 THEN 'Jun'
                WHEN MONTH(order_date) = 7 THEN 'Jul'
                WHEN MONTH(order_date) = 8 THEN 'Aug'
                WHEN MONTH(order_date) = 9 THEN 'Sep'
                WHEN MONTH(order_date) = 10 THEN 'Oct'
                WHEN MONTH(order_date) = 11 THEN 'Nov'
                WHEN MONTH(order_date) = 12 THEN 'Dec'
            END,
            ' ',
            YEAR(order_date)) AS 'Timeline',
    COUNT(*) AS 'Pending Cases'
FROM dbo.result_management_report
WHERE final_reported_date IS NULL
AND order_type = 'Commercial'
AND test_name = 'CTC-FISH'
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY YEAR(order_date), MONTH(order_date)
</code>```

Here is the output. You can see that where Jan 2020, it is missing instead of the Pending Cases being "0"

I've tried IIF and NULLIF and ISNULL but to no avail. If someone knows a trick to help me here it would be greatly appreciated.

答:
They are not showing because they are not available in your souce table.

One option to work around this is to left join a list of fixed dates, that you can generate with a recursive cte:

```<code>with all_dates as (
    select
        datefromparts(year(min(orderdate)), month(min(orderdate)), 1) dt
        datefromparts(year(max(orderdate)), max(min(orderdate)), 1) maxdt
    from dbo.result_management_report
    union all
    select dateadd(month, 1, dt), maxdt
    from all_dates
    where dt < maxdt
)
select
    row_number() over(order by d.dt) as idx,
    d.dt start_of_month,
    count(r.orderdate) pending_cases
from all_dates d
left join bo.result_management_report r
    on  r.orderdate >= d.dt
    and r.orderdate <  dateadd(month, 1, d.dt)
    and r.final_reported_date is null
    and r.order_type = 'commercial'
    and r.test_name = 'ctc-fish'
group by d.dt
</code>```

Body:
This is a problem I'm not sure I've run into before (and frankly didn't know it existed). I am grouping by YEAR and MONTH for monthly time-series analysis but COUNTs of 0's are not showing up in the output. Here is the query:

SELECT
    ROW_NUMBER() OVER(
        ORDER BY YEAR(order_date), MONTH(order_date)) AS 'Index',
    YEAR(order_date) AS 'Year',
    MONTH(order_date) AS 'Month',
    CONCAT(CASE
                WHEN MONTH(order_date) = 1 THEN 'Jan'
                WHEN MONTH(order_date) = 2 THEN 'Feb'
                WHEN MONTH(order_date) = 3 THEN 'Mar'
                WHEN MONTH(order_date) = 4 THEN 'Apr'
                WHEN MONTH(order_date) = 5 THEN 'May'
                WHEN MONTH(order_date) = 6 THEN 'Jun'
                WHEN MONTH(order_date) = 7 THEN 'Jul'
                WHEN MONTH(order_date) = 8 THEN 'Aug'
                WHEN MONTH(order_date) = 9 THEN 'Sep'
                WHEN MONTH(order_date) = 10 THEN 'Oct'
                WHEN MONTH(order_date) = 11 THEN 'Nov'
                WHEN MONTH(order_date) = 12 THEN 'Dec'
            END,
            ' ',
            YEAR(order_date)) AS 'Timeline',
    COUNT(*) AS 'Pending Cases'
FROM dbo.result_management_report
WHERE final_reported_date IS NULL
AND order_type = 'Commercial'
AND test_name = 'CTC-FISH'
GROUP BY YEAR(order_date), MONTH(order_date)
ORDER BY YEAR(order_date), MONTH(order_date)

Here is the output. You can see that where Jan 2020, it is missing instead of the Pending Cases being "0"

I've tried IIF and NULLIF and ISNULL but to no avail. If someone knows a trick to help me here it would be greatly appreciated.

Body:
They are not showing because they are not available in your souce table.

One option to work around this is to left join a list of fixed dates, that you can generate with a recursive cte:

with all_dates as (
    select
        datefromparts(year(min(orderdate)), month(min(orderdate)), 1) dt
        datefromparts(year(max(orderdate)), max(min(orderdate)), 1) maxdt
    from dbo.result_management_report
    union all
    select dateadd(month, 1, dt), maxdt
    from all_dates
    where dt < maxdt
)
select
    row_number() over(order by d.dt) as idx,
    d.dt start_of_month,
    count(r.orderdate) pending_cases
from all_dates d
left join bo.result_management_report r
    on  r.orderdate >= d.dt
    and r.orderdate <  dateadd(month, 1, d.dt)
    and r.final_reported_date is null
    and r.order_type = 'commercial'
    and r.test_name = 'ctc-fish'
group by d.dt


问:
Does Amazon RDS for SQL Server support SSIS?
Reading some conflicting answers from Google searches, not sure if the answer is Yes, No, or maybe.  </p>

答:
Amazon now supports SSIS on RDS as of May 2020.

More info here


问:
How can I develop the in-site product filtering program with multiple dropdown using a JSON file?
I have an in-site redirect tool for our E-Commerce site that I developed with the help of this site. I would like to make these in-site redirects with a JSON file with options suitable for existing links.

The code I wrote

$("#find").on("click", function() {
    let mevsim = ($("#mevsim").val() == 0) ? "" : $("#mevsim").val();
    let tabangenisligi = ($("#tabangenisligi").val() == 0) ? "" : $("#tabangenisligi").val();
    let kesitorani = ($("#kesitorani").val() == 0) ? "" : $("#kesitorani").val();
    let jantcapi = ($("#jantcapi").val() == 0) ? "" : $("#jantcapi").val();
    let url = "https://kolayoto.com/collections/lastikleri?_=pf" + mevsim + tabangenisligi + kesitorani + jantcapi;
    console.log("url: " + url);
    location.href = url
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#find {
    background: #E8562A;
    color: white;
    border-style:none;
    border-radius: 5px;
    left: 50%;
    margin-left: 30%;
}
#baslik {
    color: #fff;
    margin: 0 0 5px;
    margin-top:-5px;
    padding: 0;
    font-weight: 700;
    font-size: 15px;
    text-align: center;
}
#dropdown-container {
    background: url(https://cdn.shopify.com/s/files/1/0251/6146/5961/files/summer_banner_2-2.jpg?v=1582620652) no-repeat center center !important;
    background-size: cover !important;
    margin-top: -40px !important;
    padding: 80px 0 !important;
}
#dropdown-holder {
    width: 300px;
    background: rgba(25, 18, 18, 0.4);
    margin: auto !important;
    padding: 20px !important;
}
.dropdown-holder .fo-info {
    color: #fff !important;
    margin: 5px 0 !important;
}
#dropdown-container > b {
    display: block !important;
    text-align: center !important;
    color: #000 !important;
    font-weight: 700 !important;
    font-size: 25px !important;
    margin-bottom: 15px !important;
}</code>```

    Lastik ebatınızı seçin.

Mevsim

        <select id="mevsim">
            <option value="">Seçiniz</option>
            <option value="&pf_t_diger_oezellikler=DiğerÖzellikler-4Mevsim">Dört Mevsim</option>
            <option value="&pf_t_mevsim=Mevsim-Yaz">Yaz</option>
            <option value="&pf_t_mevsim=Mevsim-Kış">Kış</option>
        </select>

Taban Genişliği

        <select id="tabangenisligi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-135">135</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-145">145</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-155">155</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-165">165</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-175">175</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-185">185</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-195">195</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-205">205</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-215">215</option>
        </select>

Kesit Oranı

        <select id="kesitorani">
            <option value="">Seçiniz</option>
            <option value="&pf_t_oran=Kesit%20Oranı-30">30</option>
            <option value="&pf_t_oran=Kesit%20Oranı-35">35</option>
            <option value="&pf_t_oran=Kesit%20Oranı-40">40</option>
            <option value="&pf_t_oran=Kesit%20Oranı-45">45</option>
            <option value="&pf_t_oran=Kesit%20Oranı-50">50</option>
            <option value="&pf_t_oran=Kesit%20Oranı-55">55</option>
            <option value="&pf_t_oran=Kesit%20Oranı-60">60</option>
        </select>

Jant Çapı

        <select id="jantcapi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_cap=Jant%20Çapı-13">13</option>
            <option value="&pf_t_cap=Jant%20Çapı-14">14</option>
            <option value="&pf_t_cap=Jant%20Çapı-15">15</option>
            <option value="&pf_t_cap=Jant%20Çapı-16">16</option>
            <option value="&pf_t_cap=Jant%20Çapı-17">17</option>
            <option value="&pf_t_cap=Jant%20Çapı-18">18</option>
        </select>

                Lastik ebatınızı, lastiğinizin yanak yüzeyine bakarak öğrenebilirsiniz.

            <button id="find">Hemen Bul</button>

```

And,

I found this solution because the site needs a more specific application, but I couldn't figure out how to integrate this into the app.

I have filter combinations as a JSON file that gives product results. Can we add filtering in order to select them only? For example, if we select the "Yaz" option in the first dropdown, only "Taban Genisligi" options of the "Yaz" option will be added to the second dropdown. Also, there is no need to assign values to each option in this filter option. If 4 options are selected, the button should direct us to the links in the csv file.And of course, in this case, we should use the dropdowns in order from start to finish and all selected. There may be exceptions because some filter options have 2 or 3 options instead of 4.

If you want to try it, the application on our live site also uses a way of working as I mentioned above. Our Site

As a newby software developer, I really need this development and I am waiting for your help. Thank you very much in advance.

答:
Here is my final dropdown in-site linking tool. Thank you for your help, especially Matthias.</p>

```<code>`https://codepen.io/berkb-the-scripter/pen/yLeLOVm`
</code>```

Body:
I have an in-site redirect tool for our E-Commerce site that I developed with the help of this site. I would like to make these in-site redirects with a JSON file with options suitable for existing links.

The code I wrote

$("#find").on("click", function() {
    let mevsim = ($("#mevsim").val() == 0) ? "" : $("#mevsim").val();
    let tabangenisligi = ($("#tabangenisligi").val() == 0) ? "" : $("#tabangenisligi").val();
    let kesitorani = ($("#kesitorani").val() == 0) ? "" : $("#kesitorani").val();
    let jantcapi = ($("#jantcapi").val() == 0) ? "" : $("#jantcapi").val();
    let url = "https://kolayoto.com/collections/lastikleri?_=pf" + mevsim + tabangenisligi + kesitorani + jantcapi;
    console.log("url: " + url);
    location.href = url
});

#find {
    background: #E8562A;
    color: white;
    border-style:none;
    border-radius: 5px;
    left: 50%;
    margin-left: 30%;
}
#baslik {
    color: #fff;
    margin: 0 0 5px;
    margin-top:-5px;
    padding: 0;
    font-weight: 700;
    font-size: 15px;
    text-align: center;
}
#dropdown-container {
    background: url(https://cdn.shopify.com/s/files/1/0251/6146/5961/files/summer_banner_2-2.jpg?v=1582620652) no-repeat center center !important;
    background-size: cover !important;
    margin-top: -40px !important;
    padding: 80px 0 !important;
}
#dropdown-holder {
    width: 300px;
    background: rgba(25, 18, 18, 0.4);
    margin: auto !important;
    padding: 20px !important;
}
.dropdown-holder .fo-info {
    color: #fff !important;
    margin: 5px 0 !important;
}
#dropdown-container > b {
    display: block !important;
    text-align: center !important;
    color: #000 !important;
    font-weight: 700 !important;
    font-size: 25px !important;
    margin-bottom: 15px !important;
}

    Lastik ebatınızı seçin.

Mevsim

        <select id="mevsim">
            <option value="">Seçiniz</option>
            <option value="&pf_t_diger_oezellikler=DiğerÖzellikler-4Mevsim">Dört Mevsim</option>
            <option value="&pf_t_mevsim=Mevsim-Yaz">Yaz</option>
            <option value="&pf_t_mevsim=Mevsim-Kış">Kış</option>
        </select>

Taban Genişliği

        <select id="tabangenisligi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-135">135</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-145">145</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-155">155</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-165">165</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-175">175</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-185">185</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-195">195</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-205">205</option>
            <option value="&pf_t_genislik=Taban%20Genişliği-215">215</option>
        </select>

Kesit Oranı

        <select id="kesitorani">
            <option value="">Seçiniz</option>
            <option value="&pf_t_oran=Kesit%20Oranı-30">30</option>
            <option value="&pf_t_oran=Kesit%20Oranı-35">35</option>
            <option value="&pf_t_oran=Kesit%20Oranı-40">40</option>
            <option value="&pf_t_oran=Kesit%20Oranı-45">45</option>
            <option value="&pf_t_oran=Kesit%20Oranı-50">50</option>
            <option value="&pf_t_oran=Kesit%20Oranı-55">55</option>
            <option value="&pf_t_oran=Kesit%20Oranı-60">60</option>
        </select>

Jant Çapı

        <select id="jantcapi">
            <option value="">Seçiniz</option>
            <option value="&pf_t_cap=Jant%20Çapı-13">13</option>
            <option value="&pf_t_cap=Jant%20Çapı-14">14</option>
            <option value="&pf_t_cap=Jant%20Çapı-15">15</option>
            <option value="&pf_t_cap=Jant%20Çapı-16">16</option>
            <option value="&pf_t_cap=Jant%20Çapı-17">17</option>
            <option value="&pf_t_cap=Jant%20Çapı-18">18</option>
        </select>

                Lastik ebatınızı, lastiğinizin yanak yüzeyine bakarak öğrenebilirsiniz.

            <button id="find">Hemen Bul</button>

And,

I found this solution because the site needs a more specific application, but I couldn't figure out how to integrate this into the app.

I have filter combinations as a JSON file that gives product results. Can we add filtering in order to select them only? For example, if we select the "Yaz" option in the first dropdown, only "Taban Genisligi" options of the "Yaz" option will be added to the second dropdown. Also, there is no need to assign values to each option in this filter option. If 4 options are selected, the button should direct us to the links in the csv file.And of course, in this case, we should use the dropdowns in order from start to finish and all selected. There may be exceptions because some filter options have 2 or 3 options instead of 4.

If you want to try it, the application on our live site also uses a way of working as I mentioned above. Our Site

As a newby software developer, I really need this development and I am waiting for your help. Thank you very much in advance.

Body:
Here is my final dropdown in-site linking tool. Thank you for your help, especially Matthias.

`https://codepen.io/berkb-the-scripter/pen/yLeLOVm`


问:
How to load catalog model in admin controller
I am using Opencart Version 2.1.0.1, how to load frontend model in admin controller,

i have a model function which tells external booking id

```<code>class ModelShippingParcelled extends Model {
        public function getParcelledBooking($order_id) {
             $query = $this->db->query("SELECT booking_id FROM " . DB_PREFIX . "parcelled WHERE order_id = '" . (int)$order_id . "'");
             return $query->row;
    }
</code>```

I want to load this model in admin controller. What is the best way to do this?
Should I rewrite this model in admin too? But I don't want to rewrite the same function. If there is a good way please suggest!

答:
I also needed to call a function from catalog/model inside admin/model (without copying). Requiring a function occured to be imposible in php.
But I figured out that I can move the function into system/library, for example in /system/library/cart/cart.php.
Albeit cart functions is never called in admin it occured to be possible. So I called it like

$this->cart->functionName($params)

To make sure function is still working in catalog I made replacement via shell like

find catalog -type f -print0 | xargs -0 sed -i '' -e 's/this->model_catalog_filter->functionName/this->cart->functionName/g'

Body:
I am using Opencart Version 2.1.0.1, how to load frontend model in admin controller,

i have a model function which tells external booking id

class ModelShippingParcelled extends Model {
        public function getParcelledBooking($order_id) {
             $query = $this->db->query("SELECT booking_id FROM " . DB_PREFIX . "parcelled WHERE order_id = '" . (int)$order_id . "'");
             return $query->row;
    }

I want to load this model in admin controller. What is the best way to do this?
Should I rewrite this model in admin too? But I don't want to rewrite the same function. If there is a good way please suggest!


问:
div with innerhtml and variable
I need to put a link inside a div or  together with a variable value coming from a function in javascript.

function getRadios(){
      var radios = $("input[name='radio']:checked").val()
      return radios;
  }
var resultado = getRadios();
var jogar = document.getElementsById('jogar');

jogar.innerHTML = 'click';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>
<div id="jogar"></div></code>```

I need the radio value to be inserted in the url I'm using ajax.

答:
I think your problem is, that you run this code once on page load. You should run t every time radio is changed.</p>

```<code>function getRadios(){
    var radios = document.querySelector("input[name='radio']:checked").value;
    return radios;
}
document.querySelectorAll("input[name='radio']").forEach(x => x.onchange = () => {
    var resultado = getRadios();
    var jogar = document.getElementsById('jogar');
    jogar.innerHTML = '<a href="somepage.htm?varName='+ resultado +'">click</a>';
});
</code>```

Title: div with innerhtml and variable

Body:
I need to put a link inside a div or  together with a variable value coming from a function in javascript.

function getRadios(){
      var radios = $("input[name='radio']:checked").val()
      return radios;
  }
var resultado = getRadios();
var jogar = document.getElementsById('jogar');

jogar.innerHTML = 'click';

<input type="radio" id="radio1" name="radio" value="1"/>
<input type="radio" id="radio2" name="radio" value="2"/>

I need the radio value to be inserted in the url I'm using ajax.

Body:
I think your problem is, that you run this code once on page load. You should run t every time radio is changed.

function getRadios(){
    var radios = document.querySelector("input[name='radio']:checked").value;
    return radios;
}
document.querySelectorAll("input[name='radio']").forEach(x => x.onchange = () => {
    var resultado = getRadios();
    var jogar = document.getElementsById('jogar');
    jogar.innerHTML = '<a href="somepage.htm?varName='+ resultado +'">click</a>';
});


问:
Is it possible to bind not to a property of an element but the element itself in WPF?
TransformA is a TranslateTransform, I would like to do something like this:

```<code><Setter Property="RenderTransform">
  <Setter.Value>
    <TransformGroup>
      <RotateTransform Angle="90"/>
      <TranslateTransform Self="{Binding TransformA}"/>
    </TransformGroup>
  </Setter.Value>
</Setter>
</code>```

Is there another way to achieve this?

I know I can bind a single RenderTransform like this

```<code><Path RenderTransform="{Binding TransformA}"/>
</code>```

with a Setter

```<code><Setter Property="RenderTransform" Value="{Binding TransformA}"/>
</code>```

or multiple transformations with a TransformGroup

```<code><Setter Property="RenderTransform">
  <Setter.Value>
    <TransformGroup>
      <TranslateTransform X="5" Y="5"/>
      <RotateTransform Angle="90"/>
    </TransformGroup>
  </Setter.Value>
</Setter>
</code>```

答:
According to Ash's answer, this is not possible. I instead got it to work by creating a new TransformGroup in codebehind and binding that

Codebehind:

```<code>public TransformGroup combinedTransformGroup {
  get {
    var transformGroup = new TransformGroup();
    if (TransformA != null)
      transformGroup.Children.Add(TransformA);
    transformGroup.Children.Add(new RotateTransform(90));
    return transformGroup;
    }
    set { }
}
</code>```

XAML:

```<code><Setter Property="RenderTransform" Value="{Binding combinedTransformGroup}"/>
</code>```

Body:
TransformA is a TranslateTransform, I would like to do something like this:

<Setter Property="RenderTransform">
  <Setter.Value>
    <TransformGroup>
      <RotateTransform Angle="90"/>
      <TranslateTransform Self="{Binding TransformA}"/>
    </TransformGroup>
  </Setter.Value>
</Setter>

Is there another way to achieve this?

I know I can bind a single RenderTransform like this

<Path RenderTransform="{Binding TransformA}"/>

with a Setter

<Setter Property="RenderTransform" Value="{Binding TransformA}"/>

or multiple transformations with a TransformGroup

<Setter Property="RenderTransform">
  <Setter.Value>
    <TransformGroup>
      <TranslateTransform X="5" Y="5"/>
      <RotateTransform Angle="90"/>
    </TransformGroup>
  </Setter.Value>
</Setter>

Body:
According to Ash's answer, this is not possible. I instead got it to work by creating a new TransformGroup in codebehind and binding that

Codebehind:

public TransformGroup combinedTransformGroup {
  get {
    var transformGroup = new TransformGroup();
    if (TransformA != null)
      transformGroup.Children.Add(TransformA);
    transformGroup.Children.Add(new RotateTransform(90));
    return transformGroup;
    }
    set { }
}

XAML:

<Setter Property="RenderTransform" Value="{Binding combinedTransformGroup}"/>


问:
PhpStorm shows warning on :src directive in Vue.js
I have Vue file:

```<code><template>
    <div class="card">
        <img :src="file" alt=""/>
    </div>
</template>

<script>
    export default {
        name: 'card',
        data() {
            return {
                file : 'assets/images/playingCards/backSide.jpg'
            }
        }
    };
</script>
</code>```

But inspection in PhpStorm gives me warning in :src directive:

This inspection checks unresolved file references in HTML.

I've tried removing : from src (so classic html) and write path with PhpStorm autocomplete (to be 100% sure validity path) and this value bind in data() to key file... but problem persist.

How to tell PhpStorm about vue and directive? (I don't want turn off check for file references)

答: It's a known issue: WEB-42737. Please follow it to be notified on updates.</p>

Body:
I have Vue file:

<template>

</template>

But inspection in PhpStorm gives me warning in :src directive:

This inspection checks unresolved file references in HTML.

I've tried removing : from src (so classic html) and write path with PhpStorm autocomplete (to be 100% sure validity path) and this value bind in data() to key file... but problem persist.

How to tell PhpStorm about vue and directive? (I don't want turn off check for file references)


问:
Override a method in a single object instance
Am not sure how to put this, and I couldn't find the answer because of my inability to find the words to express what am looking for. (!)

In Java, I used to do something like this (I don't remember):

```<code>JPanel myButton = new JPanel("Press me"){
    public void add(JComponent component){
        //override add method
    }
};
</code>```

But, i couldn't find how to do this in Objective-C .. What I found in my search was categories and weird ^{} symbols ...

So, how can I override method(s) in a newly created object?

(For example, override -(BOOL)isEqual; in a newly created NSString* ?)

Am sorry if the question is a bit vague..

EDIT:

Obviously, without subclassing :)

EDIT:

Might as well post my problem in case someone has a better idea:

I have a few CCTransitions in COCOS2D, and I want to be notified when the transition ends .. The thing is, as soon as the transition ends, the -(void)finish; method is invoked (which is part of the CCTransition class structure)

I would really want to avoid subclassing the CCTransition class, and override the finish method to do my logic when the transition ends :)

EDIT:

-(void)onEnterTransitionDidFinish; ... I can't believe something as awesome as that existed and I haven't came across it while searching......

Which means, instead of subclassing CCTransition, override this method in my CCNode subclass :D!

答:
Following Daniel's suggestion, you can implement a method in an NSObject category of the form

```<code>[anObject overrideMethod:@selector(foo:)
          byBlock:^(id self,id super,id originalArg){
          ...
}];
</code>```

What you need to do is to

objc_allocateClassPair against self's own class, to create a new temporary class

Turn a block into a function pointer, using e.g. this or this

method_setImplementation to set the new implementation to the temporary class

use object_setClass to self to set the class to the new temporary class

I haven't figured out how to provide super to the block :p

It's believed this is basically how the KVO is done by Apple, see e.g. this discussion.

Read Runtime reference.

Body:
Am not sure how to put this, and I couldn't find the answer because of my inability to find the words to express what am looking for. (!)

In Java, I used to do something like this (I don't remember):

JPanel myButton = new JPanel("Press me"){
    public void add(JComponent component){
        //override add method
    }
};

But, i couldn't find how to do this in Objective-C .. What I found in my search was categories and weird ^{} symbols ...

So, how can I override method(s) in a newly created object?

(For example, override -(BOOL)isEqual; in a newly created NSString* ?)

Am sorry if the question is a bit vague..

EDIT:

Obviously, without subclassing :)

EDIT:

Might as well post my problem in case someone has a better idea:

I have a few CCTransitions in COCOS2D, and I want to be notified when the transition ends .. The thing is, as soon as the transition ends, the -(void)finish; method is invoked (which is part of the CCTransition class structure)

I would really want to avoid subclassing the CCTransition class, and override the finish method to do my logic when the transition ends :)

EDIT:

-(void)onEnterTransitionDidFinish; ... I can't believe something as awesome as that existed and I haven't came across it while searching......

Which means, instead of subclassing CCTransition, override this method in my CCNode subclass :D!

Body:
Following Daniel's suggestion, you can implement a method in an NSObject category of the form

[anObject overrideMethod:@selector(foo:)
          byBlock:^(id self,id super,id originalArg){
          ...
}];

What you need to do is to

objc_allocateClassPair against self's own class, to create a new temporary class

Turn a block into a function pointer, using e.g. this or this

method_setImplementation to set the new implementation to the temporary class

use object_setClass to self to set the class to the new temporary class

I haven't figured out how to provide super to the block :p

It's believed this is basically how the KVO is done by Apple, see e.g. this discussion.

Read Runtime reference.


问:
SwiftUI: onCommit triggered when is when I click away rather than press Return
I am working with onCommit for a text view in SwiftUI (the app is for MacOS).

```<code>struct TextBlockView: View {
     @State private var content = ""
    var id = UUID()

       var body: some View {

        let block = MacEditorTextView(text: $content, onEditingChanged: {
            print("editing changed")
        }, onCommit: {
            Keystroke.keystroke.enterPressed = true
            print("add new textblock here")
            //trigger function to create next block
           }).multilineTextAlignment(.leading)
               .frame(minWidth: 300,
                      maxWidth: .infinity,
                      minHeight: 40,
                      maxHeight: .infinity)
                .focusable()

        let tag = Rectangle()
                    .fill(Color.init(red: 1.00, green: 0.95, blue: 0.80, opacity: 1))
                    .frame(width: 10, height: 10)

        return HStack {
            tag
            block
        }
       }
}
</code>```

The desired action occurs when the user clicks away from the text block (a new textblock is added). However, I would like this action to occur when the user hits return. It worked this way for about 30 minutes when I first wrote the code for onCommit, before it decided a commit was a click rather than press of the return key.

I have tried to use the "onCommand" instead of onCommit, but this did not work, and I am unsure if I used the appropriate selector. I have also tried to capture when the enter key is pressed at the level of the NSWindow. However, I decided this was not desired, as I do not wish for this action to take place whenever the enter key is pressed.

Any help in relating onCommit to a specific key (return) would be very appreciated.

I am new to StackOverflow, so let me know if more information is needed.

答:
I was able to fix my issue not by using onCommit, but rather including this function in the NSTextView wrapper:

```<code>        func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
             if (commandSelector == #selector(NSResponder.insertNewline(_:))) {
                            // Do something against ENTER key
                            print("enter")
                            //triggers function to create next block.
                            Keystroke.keystroke.enterPressed = true
                            return true
                        } else if (commandSelector == #selector(NSResponder.deleteForward(_:))) {
                            // Do something against DELETE key
                            return true
                        } else if (commandSelector == #selector(NSResponder.deleteBackward(_:))) {
                            // Do something against BACKSPACE key
                            return true
                        } else if (commandSelector == #selector(NSResponder.insertTab(_:))) {
                            // Do something against TAB key
                            return true
                        } else if (commandSelector == #selector(NSResponder.cancelOperation(_:))) {
                            // Do something against ESCAPE key
                            return true
                        }
            return false
        }
</code>```

Note, this was written in a coordinator that conformed to the NSTextViewDelegate and NSControlTextEditingDelegate protocols. I'm not exactly sure which one specifically caused it to work.

If anyone faces this issue in the future and stumbles upon this post, do not hesitate to reach out to me.

Body:
I am working with onCommit for a text view in SwiftUI (the app is for MacOS).

struct TextBlockView: View {
     @State private var content = ""
    var id = UUID()

       var body: some View {

        let block = MacEditorTextView(text: $content, onEditingChanged: {
            print("editing changed")
        }, onCommit: {
            Keystroke.keystroke.enterPressed = true
            print("add new textblock here")
            //trigger function to create next block
           }).multilineTextAlignment(.leading)
               .frame(minWidth: 300,
                      maxWidth: .infinity,
                      minHeight: 40,
                      maxHeight: .infinity)
                .focusable()

        let tag = Rectangle()
                    .fill(Color.init(red: 1.00, green: 0.95, blue: 0.80, opacity: 1))
                    .frame(width: 10, height: 10)

        return HStack {
            tag
            block
        }
       }
}

The desired action occurs when the user clicks away from the text block (a new textblock is added). However, I would like this action to occur when the user hits return. It worked this way for about 30 minutes when I first wrote the code for onCommit, before it decided a commit was a click rather than press of the return key.

I have tried to use the "onCommand" instead of onCommit, but this did not work, and I am unsure if I used the appropriate selector. I have also tried to capture when the enter key is pressed at the level of the NSWindow. However, I decided this was not desired, as I do not wish for this action to take place whenever the enter key is pressed.

Any help in relating onCommit to a specific key (return) would be very appreciated.

I am new to StackOverflow, so let me know if more information is needed.

Body:
I was able to fix my issue not by using onCommit, but rather including this function in the NSTextView wrapper:

        func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
             if (commandSelector == #selector(NSResponder.insertNewline(_:))) {
                            // Do something against ENTER key
                            print("enter")
                            //triggers function to create next block.
                            Keystroke.keystroke.enterPressed = true
                            return true
                        } else if (commandSelector == #selector(NSResponder.deleteForward(_:))) {
                            // Do something against DELETE key
                            return true
                        } else if (commandSelector == #selector(NSResponder.deleteBackward(_:))) {
                            // Do something against BACKSPACE key
                            return true
                        } else if (commandSelector == #selector(NSResponder.insertTab(_:))) {
                            // Do something against TAB key
                            return true
                        } else if (commandSelector == #selector(NSResponder.cancelOperation(_:))) {
                            // Do something against ESCAPE key
                            return true
                        }
            return false
        }

Note, this was written in a coordinator that conformed to the NSTextViewDelegate and NSControlTextEditingDelegate protocols. I'm not exactly sure which one specifically caused it to work.

If anyone faces this issue in the future and stumbles upon this post, do not hesitate to reach out to me.


问:
Problem with code in Sharepoint/Powershell
So here's my problem,
We want to automate the copy of notepad (Sharepoint) in my company,
We already have the power-automate script which allows us to copy links from sharepoint sites,
And here is the Power shell code which allows you to recover the site files and copy them to another:

```<code>$SiteURL = "https://******.sharepoint.com/sites/********"
$TargetFolderURL = "/sites/*********/*****"
$SitestoCopy = "copy"

Connect-PnPOnline -Url $SiteURL -UseWebLogin

$items = Get-PnPListItem -List $SitestoCopy

Write-Host "Nombre total d'éléments :" $items.Count

ForEach ($item in $items)
{
    Write-Host $item["Title"]

    #Copy All Files and Folders from one folder to another
    Copy-PnPFile -SourceUrl $item["Title"] -TargetUrl $TargetFolderURL -SkipSourceFolderName -Force

}
</code>```

I have an error : Copy-PnPFile : File not found.

i have no clue to resolve this problem,
Anyone could help me?

Thank you

答:
I think the problem is in the -SourceUrl param. You pass the item Title. According to the spec this should be the relative url to the item. I am not sure now in what column it was stored I am guessing something like "ServerRelativeUrl" or "FileRef". Please try to check it out and change it to correct column to pass the url to the item not the title.

I hope it will be of any help :)

Body:
So here's my problem,
We want to automate the copy of notepad (Sharepoint) in my company,
We already have the power-automate script which allows us to copy links from sharepoint sites,
And here is the Power shell code which allows you to recover the site files and copy them to another:

$SiteURL = "https://******.sharepoint.com/sites/********"
$TargetFolderURL = "/sites/*********/*****"
$SitestoCopy = "copy"

Connect-PnPOnline -Url $SiteURL -UseWebLogin

$items = Get-PnPListItem -List $SitestoCopy

Write-Host "Nombre total d'éléments :" $items.Count

ForEach ($item in $items)
{
    Write-Host $item["Title"]

    #Copy All Files and Folders from one folder to another
    Copy-PnPFile -SourceUrl $item["Title"] -TargetUrl $TargetFolderURL -SkipSourceFolderName -Force

}

I have an error : Copy-PnPFile : File not found.

i have no clue to resolve this problem,
Anyone could help me?

Thank you


问:
Execute SQL Statement stored in table column
I have insert statement in DB2 database table column and i want to execute that in store procedure

Table:

```<code>TB_SQL
(
DATA_SQL VARCHAR(12000)
)
</code>```

DATA_SQL column contains INSERT statements. for example :

SELECT * FROM TB_SQL

```<code>INSERT INTO ADDRESS (COL1, COL2)
SELECT COL1, COL2 FROM DEMO WHERE TYPE='ADDRESS'
</code>```

How to PREPARE and EXECUTE the INSERT STATEMENT from DATA_SQL Column in DB2 Store Procedure ?

Code I tried:

```<code>SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY ;
</code>```

In reality the above PREPARE AND EXECUTE will only prepare SELECT statement and execute SELECT statement.
What i want is, I want to execute the statement that comes as output from SELECT statement.

I also have below option to store the INSERT statement again in another variable

```<code>SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY INTO v_INSERT_STATEMENT;
        PREPARE SQL_INSERT FROM v_INSERT_STATEMENT;
        EXECUTE SQL_INSERT;

</code>```

I believe now i have insert statement stored in v_INSERT_STATEMENT
And again prepared SQL from variable and then executed. But this is not working.

答:
you don't need two dynamic statements...one static and one dynamic makes much more sense.</p>

```<code>select data_sql into v_Insert_statement
from tb_sql
where tbname = v_TBNAME;

PREPARE SQL_INSERT FROM v_INSERT_STATEMENT;
EXECUTE SQL_INSERT;
</code>```

Body:
I have insert statement in DB2 database table column and i want to execute that in store procedure

Table:

TB_SQL
(
DATA_SQL VARCHAR(12000)
)

DATA_SQL column contains INSERT statements. for example :

SELECT * FROM TB_SQL

INSERT INTO ADDRESS (COL1, COL2)
SELECT COL1, COL2 FROM DEMO WHERE TYPE='ADDRESS'

How to PREPARE and EXECUTE the INSERT STATEMENT from DATA_SQL Column in DB2 Store Procedure ?

Code I tried:

SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY ;

In reality the above PREPARE AND EXECUTE will only prepare SELECT statement and execute SELECT statement.
What i want is, I want to execute the statement that comes as output from SELECT statement.

I also have below option to store the INSERT statement again in another variable

SET v_SQL=
        'SET ?=(
                    SELECT
                    DATA_SQL
                    FROM TB_SQL
                    WHERE TBNAME='''||v_TBNAME||'''
               )
        ';
        PREPARE SQL_QUERY FROM v_SQL;
        EXECUTE SQL_QUERY INTO v_INSERT_STATEMENT;
        PREPARE SQL_INSERT FROM v_INSERT_STATEMENT;
        EXECUTE SQL_INSERT;

I believe now i have insert statement stored in v_INSERT_STATEMENT
And again prepared SQL from variable and then executed. But this is not working.

Body:
you don't need two dynamic statements...one static and one dynamic makes much more sense.

select data_sql into v_Insert_statement
from tb_sql
where tbname = v_TBNAME;

PREPARE SQL_INSERT FROM v_INSERT_STATEMENT;
EXECUTE SQL_INSERT;