问:
Kotlin - How to know if editText lost focus
In my app I need to be able to catch if an editText lost focus, I've found how to do it in java but I'm not quite able to find how to do it in kotlin.

The Java answer I found was this one:

```<code> EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               // code to execute when EditText loses focus
            }
        }
    });
</code>```

Can anyone help me convert this to kotlin?

答:
This way</p>

```<code>// Class level
lateinit var editText: EditText

// Method onCreate/onCreateView
editText = findViewById(R.id.whatever)

editText.setOnFocusChangeListener { view, hasFocus ->
    if(!hasFocus) {

    }
}
</code>```

Body:
In my app I need to be able to catch if an editText lost focus, I've found how to do it in java but I'm not quite able to find how to do it in kotlin.

The Java answer I found was this one:

 EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               // code to execute when EditText loses focus
            }
        }
    });

Can anyone help me convert this to kotlin?

Body:
This way

// Class level
lateinit var editText: EditText

// Method onCreate/onCreateView
editText = findViewById(R.id.whatever)

editText.setOnFocusChangeListener { view, hasFocus ->
    if(!hasFocus) {

    }
}


来源: stackexchange

问:
Error when picking out unique numbers in an array
This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)

-The output is:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 6 4

-When it should be:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 6
 The distinct numbers are: 1 2 3 6 4 5

```<code>
public class ch7e5{

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter 10 numbers: ");

        int[] numberArray = new int[10];
        //create array for all numbers

        int[] distinctArray = new int[10];
        //create array for distinct numbers

        int distinct = 0;

        for (int i = 0; i < 10; i++)

            numberArray[i] = input.nextInt();

        distinctArray[0] = numberArray[0];
        //first value will be distinct

        for (int i = 1; i < numberArray.length; i++) {
        //loop to go through remaining values in numberArray

            boolean exists = false;
            //create boolean

            for (int j = 0; j < numberArray.length; j++) {
            //loop to check if value exists already in distinctArray

                if (numberArray[i] == distinctArray[j]) {

                    exists = true;

                    break;
                    //break out of inner loop

                }
            }

            if (exists == false) {
            //if value is unique then add it to the distinct array

                distinct++;
                distinctArray[distinct] = distinctArray[i];

            }
        }
        //}

        System.out.println("The number of distinct numbers is " + distinct);

        System.out.print("The distinct numbers are: ");

        for (int k = 0; k < distinct; k++)

            System.out.print(distinctArray[k] + " ");

    }

}```

```

答:
There are 3 distinct numbers, 1, 2, and 3 are not any of them as they appear twice. The output should be 6 4 5. I'm not sure how you got 5 distinct numbers here, maybe you inputted them wrong? I would try not using a scanner at first and try putting the numbers in the array manually. Additionally, I would create a boolean array length 10 starting all true to record if numbers are distinct. If a number appears twice, the corresponding boolean in the array will be false. I will update this with code once i have written it.

EDIT: apparently having a duplicate does not delete it from the distinct list. If this is the case, please elaborate on the title.

Here is my code:

```<code>public class Main {
  public static void main(String[] args) {
    int inputs = 3;
    int[] numberArray = new int[inputs];
    int distinct = 0;
    boolean[] mirror = new boolean[inputs];

    //just setting up arrays
    for(int i = 0; i < numberArray.length; i++) {
      //numberArray[i] = i;
      mirror[i] = true;
    }
    numberArray[0] = 1;

    //finds out what numbers are not distinct
    for (int x = 0; x < numberArray.length; x++) {
      for (int y = 0; y < numberArray.length; y++) {
        System.out.println("x is " + x);
        System.out.println("y is " + y);
        if(numberArray[x] == numberArray[y] && x != y) {
          System.out.println(numberArray[x] + " is not distinct");
          mirror[x] = false;//if current position in array matches any other position, number is not distinct
        }
      }
    }

    //calculates how many are distinct
    for(int j = 0; j < inputs; j++) {
      if(mirror[j]) {distinct++;}
    }

    //outputs text
    System.out.println("The number of distinct numbers is " + distinct);
    System.out.print("The distinct numbers are: ");
    for(int k = 0; k < inputs; k++){
      if(mirror[k]) {System.out.print(numberArray[k] + " ");}
    }
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is a problem in my textbook for my Java class where the user enters 10 integers. The program is supposed to read all integers and only display the unique numbers (not duplicated) as the output. I am having trouble understanding why my output is not picking up the last unique value in the array (5). Can anyone give some insight to this issue? Any help would be appreciated. (Since we are in the early stages of the class and understanding the language, our assignment is to complete this using a nested loop.)

-The output is:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 5
 The distinct numbers are: 1 2 3 6 4

-When it should be:
 Enter 10 numbers: 1 2 3 2 1 6 3 4 5 2
 The number of distinct numbers is 6
 The distinct numbers are: 1 2 3 6 4 5

public class ch7e5{

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.print("Enter 10 numbers: ");

        int[] numberArray = new int[10];
        //create array for all numbers

        int[] distinctArray = new int[10];
        //create array for distinct numbers

        int distinct = 0;

        for (int i = 0; i < 10; i++)

            numberArray[i] = input.nextInt();

        distinctArray[0] = numberArray[0];
        //first value will be distinct

        for (int i = 1; i < numberArray.length; i++) {
        //loop to go through remaining values in numberArray

            boolean exists = false;
            //create boolean

            for (int j = 0; j < numberArray.length; j++) {
            //loop to check if value exists already in distinctArray

                if (numberArray[i] == distinctArray[j]) {

                    exists = true;

                    break;
                    //break out of inner loop

                }
            }

            if (exists == false) {
            //if value is unique then add it to the distinct array

                distinct++;
                distinctArray[distinct] = distinctArray[i];

            }
        }
        //}

        System.out.println("The number of distinct numbers is " + distinct);

        System.out.print("The distinct numbers are: ");

        for (int k = 0; k < distinct; k++)

            System.out.print(distinctArray[k] + " ");

    }

}```

Body:
There are 3 distinct numbers, 1, 2, and 3 are not any of them as they appear twice. The output should be 6 4 5. I'm not sure how you got 5 distinct numbers here, maybe you inputted them wrong? I would try not using a scanner at first and try putting the numbers in the array manually. Additionally, I would create a boolean array length 10 starting all true to record if numbers are distinct. If a number appears twice, the corresponding boolean in the array will be false. I will update this with code once i have written it.

EDIT: apparently having a duplicate does not delete it from the distinct list. If this is the case, please elaborate on the title.

Here is my code:

public class Main {
  public static void main(String[] args) {
    int inputs = 3;
    int[] numberArray = new int[inputs];
    int distinct = 0;
    boolean[] mirror = new boolean[inputs];

    //just setting up arrays
    for(int i = 0; i < numberArray.length; i++) {
      //numberArray[i] = i;
      mirror[i] = true;
    }
    numberArray[0] = 1;

    //finds out what numbers are not distinct
    for (int x = 0; x < numberArray.length; x++) {
      for (int y = 0; y < numberArray.length; y++) {
        System.out.println("x is " + x);
        System.out.println("y is " + y);
        if(numberArray[x] == numberArray[y] && x != y) {
          System.out.println(numberArray[x] + " is not distinct");
          mirror[x] = false;//if current position in array matches any other position, number is not distinct
        }
      }
    }

    //calculates how many are distinct
    for(int j = 0; j < inputs; j++) {
      if(mirror[j]) {distinct++;}
    }

    //outputs text
    System.out.println("The number of distinct numbers is " + distinct);
    System.out.print("The distinct numbers are: ");
    for(int k = 0; k < inputs; k++){
      if(mirror[k]) {System.out.print(numberArray[k] + " ");}
    }
  }
}


问:
Github Release Azure Pipeline task - tagpattern wildcards does not work
Have an issue setting up a github release task in my azure devops pipeline. The pipeline yml looks like the following (its for a multi framework nuget package if that is of any use):

```<code>trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

workspace:
    clean: all

...

- task: GitHubRelease@1
  inputs:
    gitHubConnection: '**/**'
    repositoryName: '$(Build.Repository.Name)'
    action: 'create'
    target: '$(Build.SourceVersion)'
    tagSource: 'gitTag'
    tagPattern: 'v*'
    changeLogCompareToRelease: 'lastFullRelease'
    changeLogType: 'commitBased'
</code>```

I i enter the exact name of the tag (for example tagPattern: 'v1') it works fine. If i use the tagpattern above and push the same tag, v1, it just gives me ##[warning]Release will not be created as the tags for the target commit do not match with the given tag pattern warning.

I tried some other regex patterns but it seems that pattern matching does not work at all, only specifying the exact git tag name. So my question is if there is some known issue im not aware of or if im missing something i should be doing here?

答:
Judging from the code, it's pasting the tag pattern into a regex. Your current pattern would thus match zero or more v's.  You'd need v.* to match any tags that start with v.

See:

https://github.com/microsoft/azure-pipelines-tasks/blob/07db48a072301f7401a5d6630bcf6774bab98478/Tasks/GitHubReleaseV1/operations/Utility.ts#L258-L268

Body:
Have an issue setting up a github release task in my azure devops pipeline. The pipeline yml looks like the following (its for a multi framework nuget package if that is of any use):

trigger:
- master

pool:
  vmImage: 'ubuntu-latest'

workspace:
    clean: all

...

- task: GitHubRelease@1
  inputs:
    gitHubConnection: '**/**'
    repositoryName: '$(Build.Repository.Name)'
    action: 'create'
    target: '$(Build.SourceVersion)'
    tagSource: 'gitTag'
    tagPattern: 'v*'
    changeLogCompareToRelease: 'lastFullRelease'
    changeLogType: 'commitBased'

I i enter the exact name of the tag (for example tagPattern: 'v1') it works fine. If i use the tagpattern above and push the same tag, v1, it just gives me ##[warning]Release will not be created as the tags for the target commit do not match with the given tag pattern warning.

I tried some other regex patterns but it seems that pattern matching does not work at all, only specifying the exact git tag name. So my question is if there is some known issue im not aware of or if im missing something i should be doing here?


问:
How to get my scanner work in more than one method
I am making a connect 4 game for school. I have a player class defining aspects of each player, Board class, "logic" class and game class which runs the game.  My Player class has two methods almost identacle to set up each player only difference is the game piece, X or O.  The Player method also reads in a registration ID and gamerTag.  It runs flawlessly on player1, but I get java.util.NoSuchElementException.  I actually get this error when trying to run any method that uses in.next...();

Player Class Methods

```<code>public void setPlayer1() {
    Scanner in = new Scanner(System.in);
    System.out.println("\nPlayer 1 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 1 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"X\".");
    this.setPiece("X");
    in.close();
}

public void setPlayer2() {
    Scanner in = new Scanner(System.in);
    System.out.println("\nPlayer 2 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 2 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"O\".");
    this.setPiece("O");
    in.close();}

public static void main(String[] args) {
    Connect4TextConsole game = new Connect4TextConsole();
    System.out.print(board);
    player1.setPlayer1();
    player2.setPlayer2();
    winner = Connect4.checkForWin(board);
    while (!winner){
        turn = turn.playerTurn(player1, player2);// switch players
        int column = Connect4.askForColumn(turn);

    }
}
</code>```

答:
You just need to give it to the method as an argument</p>

```<code>public void setPlayer1(Scanner in) {

    System.out.println("\nPlayer 1 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 1 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"X\".");
    this.setPiece("X");

}

public void setPlayer2(Scanner in) {

    System.out.println("\nPlayer 2 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 2 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"O\".");
    this.setPiece("O");
    }

`public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Connect4TextConsole game = new Connect4TextConsole();
    System.out.print(board);
//Here u give the scanner ur methods
    player1.setPlayer1(in);
    player2.setPlayer2(in);
    in.close();
    winner = Connect4.checkForWin(board);
    while (!winner){
        turn = turn.playerTurn(player1, player2);// switch players
        int column = Connect4.askForColumn(turn);

    }
}`
</code>```

Body:
I am making a connect 4 game for school. I have a player class defining aspects of each player, Board class, "logic" class and game class which runs the game.  My Player class has two methods almost identacle to set up each player only difference is the game piece, X or O.  The Player method also reads in a registration ID and gamerTag.  It runs flawlessly on player1, but I get java.util.NoSuchElementException.  I actually get this error when trying to run any method that uses in.next...();

Player Class Methods

public void setPlayer1() {
    Scanner in = new Scanner(System.in);
    System.out.println("\nPlayer 1 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 1 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"X\".");
    this.setPiece("X");
    in.close();
}

public void setPlayer2() {
    Scanner in = new Scanner(System.in);
    System.out.println("\nPlayer 2 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 2 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"O\".");
    this.setPiece("O");
    in.close();}

public static void main(String[] args) {
    Connect4TextConsole game = new Connect4TextConsole();
    System.out.print(board);
    player1.setPlayer1();
    player2.setPlayer2();
    winner = Connect4.checkForWin(board);
    while (!winner){
        turn = turn.playerTurn(player1, player2);// switch players
        int column = Connect4.askForColumn(turn);

    }
}

Body:
You just need to give it to the method as an argument

public void setPlayer1(Scanner in) {

    System.out.println("\nPlayer 1 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 1 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"X\".");
    this.setPiece("X");

}

public void setPlayer2(Scanner in) {

    System.out.println("\nPlayer 2 please enter your Arena registration ID.");
    this.setID(in.nextLong());
    System.out.print("");
    System.out.println("Player 2 please enter the name you would like to use.");
    this.setTag(in.next());
    System.out.print("");
    System.out.print(gamerTag + " your game piece is \"O\".");
    this.setPiece("O");
    }

`public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    Connect4TextConsole game = new Connect4TextConsole();
    System.out.print(board);
//Here u give the scanner ur methods
    player1.setPlayer1(in);
    player2.setPlayer2(in);
    in.close();
    winner = Connect4.checkForWin(board);
    while (!winner){
        turn = turn.playerTurn(player1, player2);// switch players
        int column = Connect4.askForColumn(turn);

    }
}`


问:
How to hide a column from a Telerik MVC grid and ALSO from the Edit view
I have a Telerik MVC grid.

1 of the columns needs to be hidden from certain users.

This is easy to achieve using .Visible

The problem is, when I launch the Edit mode for the row, the column I want hidden is displayed in the edit view.

Any idea how to hide the column from both the grid view and the edit view?

Edit: I'm using Pop Up edit mode and Ajax binding.

答:
Hiding a column from the edit form depends on the edit mode. You have not specified which edit mode you are using so I will give a solution for every single one:

Inline and InCell - you just need to make the column Readonly() and it will no longer be editable.

Popup or InForm - those modes use Html.EditorForModel which displays all properties of the model by design. As a result even the properties which are not bound as columns will be shown. Hiding something from the edit form must be done with JavaScript via the OnEdit event. However the OnEdit event is raised only during Ajax binding. It is not clear from your description whether you are using ajax or server binding. If you use server binding you have to hook to the OnLoad JavaScript event and hide the unnecessary column from the editor using jQuery.

ContentLicense: CC BY-SA 3.0


问:
plotting threshold/piecewise/change point models with 95% confidence intervals in R
I would like to plot a threshold model with smooth 95% confidence interval lines between line segments. You would think this would be on the simple side but I have not been able to find an answer!

My threshold/breakpoints are known, it would be great if there were a way to visualize this data. I have tried the segmented package which produces the following plot:

The plot shows a threshold model with a breakpoint at 5.4. However, the confidence intervals are not smooth between regression lines.

If anyone knows of any way to produce smooth (i.e. without the jump between line segments) CI lines between segmented regression lines (ideally in ggplot) that would be amazing. Thank you so much.

I have included sample data and the code I have tried below:

```<code>x <- c(2.26, 1.95, 1.59, 1.81, 2.01, 1.63, 1.62, 1.19, 1.41, 1.35, 1.32, 1.52, 1.10, 1.12, 1.11, 1.14, 1.23, 1.05, 0.95, 1.30, 0.79,
0.81, 1.15, 1.10, 1.29, 0.97, 1.05, 1.05, 0.84, 0.64, 0.80, 0.81, 0.61, 0.71, 0.75, 0.30, 0.30, 0.49, 1.13, 0.55, 0.77, 0.51,
0.67, 0.43, 1.11, 0.29, 0.36, 0.57, 0.02, 0.22, 3.18, 3.79, 2.49, 2.44, 2.12, 2.45, 3.22, 3.44, 3.86, 3.53, 3.13)

y <- c(22.37, 18.93, 16.99, 15.65, 14.62, 13.79, 13.09, 12.49, 11.95, 11.48, 11.05, 10.66, 10.30,  9.96,  9.65,  9.35,  9.07,  8.81,
       8.56,  8.32,  8.09,  7.87,  7.65,  7.45,  7.25,  7.05,  6.86,  6.68,  6.50,  6.32,  6.15,  5.97,  5.80,  5.63,  5.47,  5.30,
        5.13,  4.96,  4.80,  4.63,  4.45,  4.28,  4.09,  3.90,  3.71,  3.50,  3.27,  3.01,  2.70,  2.28, 22.37, 16.99, 11.05,  8.81,
       8.56,  8.32,  7.25,  7.05,  6.50,  6.15,  5.63)

lin.mod <- lm(y ~  x)
segmented.mod <- segmented(lin.mod, seg.Z = ~x, psi=2)
plot(x, y)
plot(segmented.mod, add=TRUE, conf.level = 0.95)
</code>```

which produces the following plot (and associated jumps in 95% confidence intervals):

segmented plot

答:
Background: The non-smoothness in existing change point packages are due to the fact that frequentist packages operate with a fixed change point value. But as with all inferred parameters, this is wrong because there is indeed uncertainty concerning the location of the change.

Solution: AFAIK, only Bayesian methods can quantify that and the mcp package fills this space.

```<code>library(mcp)
model = list(
  y ~ 1 + x,   # Segment 1: Intercept and slope
  ~ 0 + x  # Segment 2: Joined slope (no intercept change)
)
fit = mcp(model, data = data.frame(x, y))
</code>```

Default plot (plot.mcpfit() returns a ggplot object):

```<code>plot(fit) + ggtitle("Default plot")
</code>```

Each line represents a possible model that generated the data. The posterior for the change point is shown as a blue density. You can add a credible interval on top using plot(fit, q_fit = TRUE) or plot it alone:

```<code>plot(fit, lines = 0, q_fit = c(0.025, 0.975), cp_dens = FALSE) + ggtitle("Credible interval only")
</code>```

If your change point is indeed known and if you want to model different residual scales for each segment (i.e., quasi-emulate segmented), you can do:

```<code>model2 = list(
  y ~ 1 + x,
  ~ 0 + x + sigma(1)  # Add intercept change in residual scale
)
fit = mcp(model2, df, prior = list(cp_1 = 1.9))  # Note: prior is a fixed value - not a distribution.
plot(fit, q_fit = TRUE, cp_dens = FALSE)
</code>```

Notice that the CI does not "jump" around the change point as in segmented. I believe that this is the correct behavior. Disclosure: I am the author of mcp.

Body:
I would like to plot a threshold model with smooth 95% confidence interval lines between line segments. You would think this would be on the simple side but I have not been able to find an answer!

My threshold/breakpoints are known, it would be great if there were a way to visualize this data. I have tried the segmented package which produces the following plot:

The plot shows a threshold model with a breakpoint at 5.4. However, the confidence intervals are not smooth between regression lines.

If anyone knows of any way to produce smooth (i.e. without the jump between line segments) CI lines between segmented regression lines (ideally in ggplot) that would be amazing. Thank you so much.

I have included sample data and the code I have tried below:

x <- c(2.26, 1.95, 1.59, 1.81, 2.01, 1.63, 1.62, 1.19, 1.41, 1.35, 1.32, 1.52, 1.10, 1.12, 1.11, 1.14, 1.23, 1.05, 0.95, 1.30, 0.79,
0.81, 1.15, 1.10, 1.29, 0.97, 1.05, 1.05, 0.84, 0.64, 0.80, 0.81, 0.61, 0.71, 0.75, 0.30, 0.30, 0.49, 1.13, 0.55, 0.77, 0.51,
0.67, 0.43, 1.11, 0.29, 0.36, 0.57, 0.02, 0.22, 3.18, 3.79, 2.49, 2.44, 2.12, 2.45, 3.22, 3.44, 3.86, 3.53, 3.13)

y <- c(22.37, 18.93, 16.99, 15.65, 14.62, 13.79, 13.09, 12.49, 11.95, 11.48, 11.05, 10.66, 10.30,  9.96,  9.65,  9.35,  9.07,  8.81,
       8.56,  8.32,  8.09,  7.87,  7.65,  7.45,  7.25,  7.05,  6.86,  6.68,  6.50,  6.32,  6.15,  5.97,  5.80,  5.63,  5.47,  5.30,
        5.13,  4.96,  4.80,  4.63,  4.45,  4.28,  4.09,  3.90,  3.71,  3.50,  3.27,  3.01,  2.70,  2.28, 22.37, 16.99, 11.05,  8.81,
       8.56,  8.32,  7.25,  7.05,  6.50,  6.15,  5.63)

lin.mod <- lm(y ~  x)
segmented.mod <- segmented(lin.mod, seg.Z = ~x, psi=2)
plot(x, y)
plot(segmented.mod, add=TRUE, conf.level = 0.95)

which produces the following plot (and associated jumps in 95% confidence intervals):

segmented plot

Body:
Background: The non-smoothness in existing change point packages are due to the fact that frequentist packages operate with a fixed change point value. But as with all inferred parameters, this is wrong because there is indeed uncertainty concerning the location of the change.

Solution: AFAIK, only Bayesian methods can quantify that and the mcp package fills this space.

library(mcp)
model = list(
  y ~ 1 + x,   # Segment 1: Intercept and slope
  ~ 0 + x  # Segment 2: Joined slope (no intercept change)
)
fit = mcp(model, data = data.frame(x, y))

Default plot (plot.mcpfit() returns a ggplot object):

plot(fit) + ggtitle("Default plot")

Each line represents a possible model that generated the data. The posterior for the change point is shown as a blue density. You can add a credible interval on top using plot(fit, q_fit = TRUE) or plot it alone:

plot(fit, lines = 0, q_fit = c(0.025, 0.975), cp_dens = FALSE) + ggtitle("Credible interval only")

If your change point is indeed known and if you want to model different residual scales for each segment (i.e., quasi-emulate segmented), you can do:

model2 = list(
  y ~ 1 + x,
  ~ 0 + x + sigma(1)  # Add intercept change in residual scale
)
fit = mcp(model2, df, prior = list(cp_1 = 1.9))  # Note: prior is a fixed value - not a distribution.
plot(fit, q_fit = TRUE, cp_dens = FALSE)

Notice that the CI does not "jump" around the change point as in segmented. I believe that this is the correct behavior. Disclosure: I am the author of mcp.


问:
How to use function expression values in other functions?
I'm learning Javascript and I make a rock, scissors, paper project. I already make it work with the sample code but now I want to use a function expression to use its value in other functions. When I load the code it gave me undefined and I don't know why. I assign all the values.
Here is my code.

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  console.log()
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {

  console.log('You threw: ' + userChoice('rock'));
  console.log('The computer threw: ' + computerChoice());
  console.log(determineWinner(userChoice, computerChoice));
}
playGame();```

Please help me.

答:
just a few mistakes.
You need to store the values into variables.

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  console.log()
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {
  const threw = {
      computer: null,
      user: null
  }
  threw.user = userChoice("rock")
  threw.computer = computerChoice()

  console.log('You threw: ' + threw.user);
  console.log('The computer threw: ' + threw.computer);
  console.log(determineWinner(userChoice(threw.user), threw.computer));
}
playGame();```

Body:
I'm learning Javascript and I make a rock, scissors, paper project. I already make it work with the sample code but now I want to use a function expression to use its value in other functions. When I load the code it gave me undefined and I don't know why. I assign all the values.
Here is my code.

const userChoice = userInput => {
  //userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'scissors' || userInput === 'paper' || userInput === 'bomb') {
    return userInput;
  } else {
    console.log('Error!');
  }
}

//console.log(getUserChoice('Fork'));

const computerChoice = function() {
  const randomNumber = Math.floor(Math.random() * 3);
  switch (randomNumber) {
    case 0:
      return 'rock';
    case 1:
      return 'paper';
    case 2:
      return 'scissors'
  }
};
//console.log(getComputerChoice());

function determineWinner(userChoice, computerChoice) {
  console.log()
  if (userChoice === computerChoice) {
    return 'The game is a tie!'
  }
  if (userChoice === 'rock') {
    if (computerChoice === 'paper') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'scissors') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'paper') {
    if (computerChoice === 'rock') {
      return 'The computer won!';
    } else {
      return 'You won!'
    }
  }
  if (userChoice === 'bomb') {
    return 'You won!';

  }
}

const playGame = () => {

  console.log('You threw: ' + userChoice('rock'));
  console.log('The computer threw: ' + computerChoice());
  console.log(determineWinner(userChoice, computerChoice));
}
playGame();

Please help me.


问:
Chrome Extension: JS DOM button click method is not working
From an extension I need to click a button but click event is not triggered, I tested the following JS DOM methods:

```<code>getElementsByClassName('button')[0].click(); // Not working
document.querySelector('button').click(); // Not working
</code>```

The button is created on React.js, this can be the causes of the failed click event?

Any suggestion?

答:
If the button has the class button and you want to click it by its class. Then please follow this code.

```<code>setTimeout(()=>{
  var buttons = document.getElementsByClassName('button');
  for (let btn of buttons) {
    btn.click();
  }
}, 1000);
</code>```

I have added setTimeout in case you don't get in react function as the buttons as not been loaded into DOM. you can neglect it if not required.

Body:
From an extension I need to click a button but click event is not triggered, I tested the following JS DOM methods:

getElementsByClassName('button')[0].click(); // Not working
document.querySelector('button').click(); // Not working

The button is created on React.js, this can be the causes of the failed click event?

Any suggestion?

Body:
If the button has the class button and you want to click it by its class. Then please follow this code.

setTimeout(()=>{
  var buttons = document.getElementsByClassName('button');
  for (let btn of buttons) {
    btn.click();
  }
}, 1000);

I have added setTimeout in case you don't get in react function as the buttons as not been loaded into DOM. you can neglect it if not required.


问:
Content Script is injected in every frame but doesn't seem to execute
I'm writing a chrome extension to manipulate DOM elements in a website.

I have a content script that seems to be blocked somehow from executing in the webpage's iFrames even though it is injected.

```<code>content.js:

console.log("this script is executed");
chrome.runtime.sendMessage("Hello background.js, I am a frame");
</code>```

Both in the webpage's console and the background.js' console only the first frame is logged.
At first I thought the iFrames were dynamically loaded and therefore the content scripts could not be injected.
Then I looked at the JS contexts in the console and it seems like the opposite is true:

They are injected but not executed.

I also tried accessing the frames via the top frame by:

```<code>let iFrames = document.getElementsByClassName('js-iframe');
    for (iFrame of iFrames) {
        console.log(iFrame.contentDocument);
        console.log(iFrame.contentWindow);
    }

//null
//Uncaught (in promise) DOMException: Blocked a frame with origin "https://www.webpage.com" from accessing a cross-origin frame.
</code>```

What am I missing out?

PS: Of course a solution by executing in the frames themselves would be more preferable but a workaround like the one I tried would be extremely helpful as well.

答:
update the Permission in manifest.json
"permissions": [
    "...",
    "content.js"//something that you want to allow
  ]</p>

Body:
I'm writing a chrome extension to manipulate DOM elements in a website.

I have a content script that seems to be blocked somehow from executing in the webpage's iFrames even though it is injected.

content.js:

console.log("this script is executed");
chrome.runtime.sendMessage("Hello background.js, I am a frame");

Both in the webpage's console and the background.js' console only the first frame is logged.
At first I thought the iFrames were dynamically loaded and therefore the content scripts could not be injected.
Then I looked at the JS contexts in the console and it seems like the opposite is true:

They are injected but not executed.

I also tried accessing the frames via the top frame by:

let iFrames = document.getElementsByClassName('js-iframe');
    for (iFrame of iFrames) {
        console.log(iFrame.contentDocument);
        console.log(iFrame.contentWindow);
    }

//null
//Uncaught (in promise) DOMException: Blocked a frame with origin "https://www.webpage.com" from accessing a cross-origin frame.

What am I missing out?

PS: Of course a solution by executing in the frames themselves would be more preferable but a workaround like the one I tried would be extremely helpful as well.


问:
Using Material Design Icons in Flutter Projects
Due to the lack of icons in the classic material icon pack I'd like to use the Material Design Icons.

As for the pubspec.yaml I added the following dependancy:

```<code>material_design_icons_flutter: 3.4.4595
</code>```

As an output I'm getting:

```<code>[project] flutter packages get
Running "flutter pub get" in project...                            0,5s
</code>```

The package is imported as well:

```<code>import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';
</code>```

when using the icons it actually offers me the icons from the package:

```<code>  floatingActionButton: FloatingActionButton(
    child: Icon(MdiIcons.fileAccount),
    backgroundColor: Colors.blueAccent,
    onPressed: () {},
  ),
</code>```

However, when reloading the app, I get an missing Icon error:

Thankful for any hints to get Material Design icons working here.

答: I was also getting the "missing icon" error symbol after adding the material_design_icons_flutter package as a dependency to pubspec.yaml.  Once I restarted my emulator the "missing icon" symbol went away and the icons displayed correctly.</p>

Body:
Due to the lack of icons in the classic material icon pack I'd like to use the Material Design Icons.

As for the pubspec.yaml I added the following dependancy:

material_design_icons_flutter: 3.4.4595

As an output I'm getting:

[project] flutter packages get
Running "flutter pub get" in project...                            0,5s

The package is imported as well:

import 'package:material_design_icons_flutter/material_design_icons_flutter.dart';

when using the icons it actually offers me the icons from the package:

  floatingActionButton: FloatingActionButton(
    child: Icon(MdiIcons.fileAccount),
    backgroundColor: Colors.blueAccent,
    onPressed: () {},
  ),

However, when reloading the app, I get an missing Icon error:

Thankful for any hints to get Material Design icons working here.


问:
Istio Ingress resulting in "no healthy upstream"
I am using deploying an outward facing service, that is exposed behind a nodeport and then an istio ingress. The deployment is using manual sidecar injection. Once the deployment, nodeport and ingress are running, I can make a request to the istio ingress.

For some unkown reason, the request does not route through to my deployment and instead displays the text "no healthy upstream". Why is this, and what is causing it?

I can see in the http response that the status code is 503 (Service Unavailable) and the server is "envoy". The deployment is functioning as I can map a port forward to it and everything works as expected.

答:
Just in case, like me, you get curious... Even though in my scenario it was clear the case of the error...

Error cause: I had two versions of the same service (v1 and v2), and an Istio VirtualService configured with traffic route destination using weights. Then, 95% goes to v1 and 5% goes to v2. As I didn't have the v1 deployed (yet), of course, the error "503 - no healthy upstream" shows up 95% of the requests.

Ok, even so, I knew the problem and how to fix it (just deploy v1), I was wondering...  But, how can I have more information about this error?  How could I get a deeper analysis of this error to find out what was happening?

This is a way of investigating using the configuration command line utility of Istio, the istioctl:

```<code># 1) Check the proxies status -->
  $ istioctl proxy-status
# Result -->
  NAME                                                   CDS        LDS        EDS        RDS          PILOT                       VERSION
  ...
  teachstore-course-v1-74f965bd84-8lmnf.development      SYNCED     SYNCED     SYNCED     SYNCED       istiod-86798869b8-bqw7c     1.5.0
  ...
  ...

# 2) Get the name outbound from JSON result using the proxy (service with the problem) -->
  $ istioctl proxy-config cluster teachstore-course-v1-74f965bd84-8lmnf.development --fqdn teachstore-student.development.svc.cluster.local -o json
# 2) If you have jq install locally (only what we need, already extracted) -->
  $ istioctl proxy-config cluster teachstore-course-v1-74f965bd84-8lmnf.development --fqdn teachstore-course.development.svc.cluster.local -o json | jq -r .[].name
# Result -->
  outbound|80||teachstore-course.development.svc.cluster.local
  inbound|80|9180-tcp|teachstore-course.development.svc.cluster.local
  outbound|80|v1|teachstore-course.development.svc.cluster.local
  outbound|80|v2|teachstore-course.development.svc.cluster.local

# 3) Check the endpoints of "outbound|80|v2|teachstore-course..." using v1 proxy -->
  $ istioctl proxy-config endpoints teachstore-course-v1-74f965bd84-8lmnf.development --cluster "outbound|80|v2|teachstore-course.development.svc.cluster.local"
# Result (the v2, 5% of the traffic route is ok, there are healthy targets) -->
  ENDPOINT             STATUS      OUTLIER CHECK     CLUSTER
  172.17.0.28:9180     HEALTHY     OK                outbound|80|v2|teachstore-course.development.svc.cluster.local
  172.17.0.29:9180     HEALTHY     OK                outbound|80|v2|teachstore-course.development.svc.cluster.local

# 4) However, for the v1 version "outbound|80|v1|teachstore-course..." -->
$ istioctl proxy-config endpoints teachstore-course-v1-74f965bd84-8lmnf.development --cluster "outbound|80|v1|teachstore-course.development.svc.cluster.local"
  ENDPOINT             STATUS      OUTLIER CHECK     CLUSTER
# Nothing! Emtpy, no Pods, that's explain the "no healthy upstream" 95% of time.
</code>```

Body:
Just in case, like me, you get curious... Even though in my scenario it was clear the case of the error...

Error cause: I had two versions of the same service (v1 and v2), and an Istio VirtualService configured with traffic route destination using weights. Then, 95% goes to v1 and 5% goes to v2. As I didn't have the v1 deployed (yet), of course, the error "503 - no healthy upstream" shows up 95% of the requests.

Ok, even so, I knew the problem and how to fix it (just deploy v1), I was wondering...  But, how can I have more information about this error?  How could I get a deeper analysis of this error to find out what was happening?

This is a way of investigating using the configuration command line utility of Istio, the istioctl:

# 1) Check the proxies status -->
  $ istioctl proxy-status
# Result -->
  NAME                                                   CDS        LDS        EDS        RDS          PILOT                       VERSION
  ...
  teachstore-course-v1-74f965bd84-8lmnf.development      SYNCED     SYNCED     SYNCED     SYNCED       istiod-86798869b8-bqw7c     1.5.0
  ...
  ...

# 2) Get the name outbound from JSON result using the proxy (service with the problem) -->
  $ istioctl proxy-config cluster teachstore-course-v1-74f965bd84-8lmnf.development --fqdn teachstore-student.development.svc.cluster.local -o json
# 2) If you have jq install locally (only what we need, already extracted) -->
  $ istioctl proxy-config cluster teachstore-course-v1-74f965bd84-8lmnf.development --fqdn teachstore-course.development.svc.cluster.local -o json | jq -r .[].name
# Result -->
  outbound|80||teachstore-course.development.svc.cluster.local
  inbound|80|9180-tcp|teachstore-course.development.svc.cluster.local
  outbound|80|v1|teachstore-course.development.svc.cluster.local
  outbound|80|v2|teachstore-course.development.svc.cluster.local

# 3) Check the endpoints of "outbound|80|v2|teachstore-course..." using v1 proxy -->
  $ istioctl proxy-config endpoints teachstore-course-v1-74f965bd84-8lmnf.development --cluster "outbound|80|v2|teachstore-course.development.svc.cluster.local"
# Result (the v2, 5% of the traffic route is ok, there are healthy targets) -->
  ENDPOINT             STATUS      OUTLIER CHECK     CLUSTER
  172.17.0.28:9180     HEALTHY     OK                outbound|80|v2|teachstore-course.development.svc.cluster.local
  172.17.0.29:9180     HEALTHY     OK                outbound|80|v2|teachstore-course.development.svc.cluster.local

# 4) However, for the v1 version "outbound|80|v1|teachstore-course..." -->
$ istioctl proxy-config endpoints teachstore-course-v1-74f965bd84-8lmnf.development --cluster "outbound|80|v1|teachstore-course.development.svc.cluster.local"
  ENDPOINT             STATUS      OUTLIER CHECK     CLUSTER
# Nothing! Emtpy, no Pods, that's explain the "no healthy upstream" 95% of time.


问:
'If' statement causing unit test to fail, but I don’t know why
I have the following unit test and cannot figure out why it's failing (the test passes if I remove if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):), though I can't figure out how to make the test pass with it still there.

File tests.py

```<code>def test_redirects_after_POST(self):
        user = User.objects.create_superuser('username')
        self.client.force_login(user)

        response = self.client.post(
            reverse('page1'), data={
            'first_name': 'testuser',
            'dob': UnitTest.set_age(20)}
        )

        self.assertRedirects(response, reverse('page2'))
</code>```

I have tried adding this, but it doesn’t help:

```<code>referer = 'http://testserver{}'.format(reverse('page1'))
# Also tried: referer = 'http://testserver{}'.format(reverse('page2'))
        response = self.client.post(
            reverse('page1'), data={
            'first_name': 'testuser',
            'dob': UnitTest.set_age(20)}
            , HTTP_REFERER=referer)
</code>```

File views.py

```<code>@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page1(request):

    if request.method == 'POST':
        form = Page1Form(request.POST, request.FILES, instance=request.user.page1)
        if form.is_valid():
            form.save()
            return redirect('page2')

    else:
        form = Page1Form(instance=request.user.page1)

    context = {
        'form' : form,
    }
    return render(request, 'website/page1.html', context)

@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page2(request):

    if request.method == 'POST':
        form = Page2Form(request.POST, request.FILES, instance=request.user.page2)
        if form.is_valid():
            form.save()

            return redirect('page3')
    else:
        # redirect if user didnt access the page from page1
        if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
            return redirect('page1')

        else:
            form = Page2Form(instance=request.user.page2)

    context = {
        'form' : form
    }

    return render(request, 'website/page2.html', context)
</code>```

Error message

```<code>AssertionError: 302 != 200 : Couldn't retrieve redirection page '/website/page2/': response code was 302 (expected 200)
</code>```

答:
Your request succeeded, but your test failed, because you coded the wrong expectations:

If your request used the follow argument, the expected_url and target_status_code will be the url and status code for the final point of the redirect chain.

Yet, your request didn't set follow to true, since it defaults to false.

Body:
I have the following unit test and cannot figure out why it's failing (the test passes if I remove if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):), though I can't figure out how to make the test pass with it still there.

File tests.py

def test_redirects_after_POST(self):
        user = User.objects.create_superuser('username')
        self.client.force_login(user)

        response = self.client.post(
            reverse('page1'), data={
            'first_name': 'testuser',
            'dob': UnitTest.set_age(20)}
        )

        self.assertRedirects(response, reverse('page2'))

I have tried adding this, but it doesn’t help:

referer = 'http://testserver{}'.format(reverse('page1'))
# Also tried: referer = 'http://testserver{}'.format(reverse('page2'))
        response = self.client.post(
            reverse('page1'), data={
            'first_name': 'testuser',
            'dob': UnitTest.set_age(20)}
            , HTTP_REFERER=referer)

File views.py

@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page1(request):

    if request.method == 'POST':
        form = Page1Form(request.POST, request.FILES, instance=request.user.page1)
        if form.is_valid():
            form.save()
            return redirect('page2')

    else:
        form = Page1Form(instance=request.user.page1)

    context = {
        'form' : form,
    }
    return render(request, 'website/page1.html', context)

@login_required
@allowed_users(allowed_roles=['admin', 'registered_user'])
def page2(request):

    if request.method == 'POST':
        form = Page2Form(request.POST, request.FILES, instance=request.user.page2)
        if form.is_valid():
            form.save()

            return redirect('page3')
    else:
        # redirect if user didnt access the page from page1
        if(request.META.get('HTTP_REFERER') != request.build_absolute_uri(reverse('page1'))):
            return redirect('page1')

        else:
            form = Page2Form(instance=request.user.page2)

    context = {
        'form' : form
    }

    return render(request, 'website/page2.html', context)

Error message

AssertionError: 302 != 200 : Couldn't retrieve redirection page '/website/page2/': response code was 302 (expected 200)


问:
AWS: can't connect to RDS database from my machine
The EC2 instance/live web can connect just fine to the RDS database. But when I want to debug the code in my local machine, I can't connect to the database and got this error:

OperationalError: (2003, "Can't connect to MySQL server on 'aa9jliuygesv4w.c03i1
  ck3o0us.us-east-1.rds.amazonaws.com' (10060)")

I've added .pem and .ppk keys to .ssh and I already configure EB CLI. I don't know what should I do anymore.

FYI: The app is in Django

答:
In my case, when I upgrade the size. The private address of the rds instance fell into a private subnet of the VPC. You can use the article
My instance is in a private subnet, and I can't connect to it from my local computer to find out your db instance address.

However, changing the route table didn't fix my issue. What I did finally solve my problem is to downgrade the size and then upgrade the size back. Once the private address falls back to the public subnet. Everything works like a charm.


问:
TCPDF and PHPMailer PDF is brocken
I read a lot here and there, but somehow I could'n find a solution.

I am trying to send a PDF, generated with TCPDF, as attachment using with PHPMailer.
As soon as I try I get the message:
Warning: base64_encode() expects parameter 1 to be string, object given in C:\xampp\htdocs\pap KK\Root\phpmailer-master\src\PHPMailer.php on line 3179"", but the mail is Always send. Unfortunatelly the PDF is brocken. It is not empty. As soon as I use:
    $pdf->Output('e-tickets.pdf', 'D');
it saves a perfect PDF copy,

Help, what the heck am I doing wrong...
V

Here is the Code

```<code><?php
// Include the main TCPDF library (search for installation path).
require_once('path.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('KK Abt HC');
$pdf->SetTitle('Zuweiserbrief');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData('');

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

//remove header footer
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}

// set font
$pdf->SetFont('helvetica', '', 10);

// add a page
$pdf->AddPage();

// define some HTML content with style
require_once('print.php');

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

//Close and output PDF document

//$pdf->Output('no_name.pdf', 'I');
$pdf->Output('e-tickets.pdf', 'S');

//set random filename to pdf
$file_name = md5(rand()) . '.pdf';

//add mailer manually
require '../phpmailer-master/src/Exception.php';
require '../phpmailer-master/src/PHPMailer.php';
require '../phpmailer-master/src/SMTP.php';

//create new PHPMailer class
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer(TRUE);

//create new PHPMailer object
$mail = new PHPMailer();

//SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '*******';
$mail->Password = '*******';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

//PHPMailer headers
$mail->setFrom('mail.1@gmail.com', 'Robot');
$mail->addReplyTo('mail.2@gmail.com', 'Robot');
$mail->addAddress('mustermann@mail.de', 'Mustermann');
$mail->addCC('someone@yahoo.com', 'Yahoo');
$mail->addBCC('', '');

//HTML Format
$mail->isHTML(true);
$bodyContent = '<p>Hallo zusammen,</p>';
$bodyContent .= '<p>Im Anhang finden Sie bitte ein Brief</p>';
$bodyContent .= '<p>Mit freundlichen Grüßen</p>';
$bodyContent .= '<p><br></p>';
$bodyContent .= '<p>Das ist einen automatischen Mail</p>';

//Attachment
$mail->AddStringAttachment($pdf, $file_name);

//Subject
$mail->Subject = 'Email from Localhost Testing with YAHOO!';
$mail->Body    = $bodyContent;

//Debugging:
/*
$mail->SMTPDebug = N; where N is (1) = client; (2) = client and server; (recommended); (3) = client, server, and connection; (4) = low-level information.
*/

$mail->SMTPDebug = 3;

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
?>
</code>```

答:
It’s because you are passing the PDF object and not the string representation of it.

Do this:

$pdfdata = $pdf->Output('e-tickets.pdf', 'S');
$mail->AddStringAttachment($pdfdata, $file_name);
```

Title: TCPDF and PHPMailer PDF is brocken

Body:
I read a lot here and there, but somehow I could'n find a solution.

I am trying to send a PDF, generated with TCPDF, as attachment using with PHPMailer.
As soon as I try I get the message:
Warning: base64_encode() expects parameter 1 to be string, object given in C:\xampp\htdocs\pap KK\Root\phpmailer-master\src\PHPMailer.php on line 3179"", but the mail is Always send. Unfortunatelly the PDF is brocken. It is not empty. As soon as I use:
    $pdf->Output('e-tickets.pdf', 'D');
it saves a perfect PDF copy,

Help, what the heck am I doing wrong...
V

Here is the Code

<?php
// Include the main TCPDF library (search for installation path).
require_once('path.php');

// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('KK Abt HC');
$pdf->SetTitle('Zuweiserbrief');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// set default header data
$pdf->SetHeaderData('');

// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

//remove header footer
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);

// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
    require_once(dirname(__FILE__).'/lang/eng.php');
    $pdf->setLanguageArray($l);
}

// set font
$pdf->SetFont('helvetica', '', 10);

// add a page
$pdf->AddPage();

// define some HTML content with style
require_once('print.php');

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

//Close and output PDF document

//$pdf->Output('no_name.pdf', 'I');
$pdf->Output('e-tickets.pdf', 'S');

//set random filename to pdf
$file_name = md5(rand()) . '.pdf';

//add mailer manually
require '../phpmailer-master/src/Exception.php';
require '../phpmailer-master/src/PHPMailer.php';
require '../phpmailer-master/src/SMTP.php';

//create new PHPMailer class
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$email = new PHPMailer(TRUE);

//create new PHPMailer object
$mail = new PHPMailer();

//SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '*******';
$mail->Password = '*******';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;

//PHPMailer headers
$mail->setFrom('mail.1@gmail.com', 'Robot');
$mail->addReplyTo('mail.2@gmail.com', 'Robot');
$mail->addAddress('mustermann@mail.de', 'Mustermann');
$mail->addCC('someone@yahoo.com', 'Yahoo');
$mail->addBCC('', '');

//HTML Format
$mail->isHTML(true);
$bodyContent = '
Hallo zusammen,
';
$bodyContent .= '
Im Anhang finden Sie bitte ein Brief
';
$bodyContent .= '
Mit freundlichen Grüßen
';
$bodyContent .= '

';
$bodyContent .= '
Das ist einen automatischen Mail
';

//Attachment
$mail->AddStringAttachment($pdf, $file_name);

//Subject
$mail->Subject = 'Email from Localhost Testing with YAHOO!';
$mail->Body    = $bodyContent;

//Debugging:
/*
$mail->SMTPDebug = N; where N is (1) = client; (2) = client and server; (recommended); (3) = client, server, and connection; (4) = low-level information.
*/

$mail->SMTPDebug = 3;

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}
?>


问:
In a class, what is `using Base::BaseOfBase;` supposed to do?
Consider this code:

```<code>#include <iostream>
#include <type_traits>

struct A
{
    A(int x) {std::cout << "A(" << x << ")\n";}
};

struct B : A
{
    using A::A;
    B(int x, int y) : A(x) {std::cout << "B(" << x << "," << y << ")\n";}
};

struct C : B
{
    using B::A; // <--

    // C() : B(0,0) {}
};

int main()
{
    C c(1);
}
</code>```

gcc.godbolt.org

It compiles on GCC and prints A(1), which means that an instance of B was "constructed" without calling the constructor. If you uncomment C(), then C c(1); no longer compiles (GCC can't find a suitable constructor)

Clang doesn't say anything about using B::A;, but refuses to compile C c(1); (also can't find a suitable constructor).

MSVC stops right at using B::A;, basically saying that you can only inherit constructors from direct bases.

Cppreference doesn't mention inheriting constructors from indirect bases, so it seems to be disallowed.

Is it a GCC & Clang bug, or what's going on here?

答:
The constructor is not inherited. Primarily because

[namespace.udecl]

3 In a using-declaration used as a member-declaration, each
using-declarator's nested-name-specifier shall name a base class of
the class being defined. If a using-declarator names a constructor,
its nested-name-specifier shall name a direct base class of the class
being defined.

But the kicker is that B::A doesn't even name a constructor at all.

[class.qual]

2 In a lookup in which function names are not ignored and the
nested-name-specifier nominates a class C:

if the name specified after the nested-name-specifier, when looked up in C, is the injected-class-name of C (Clause [class]), or

in a using-declarator of a using-declaration that is a member-declaration, if the name specified after the
nested-name-specifier is the same as the identifier or the
simple-template-id's template-name in the last component of the
nested-name-specifier,

the name is instead considered to name the constructor of class C.
[ Note: For example, the constructor is not an acceptable lookup
result in an elaborated-type-specifier so the constructor would not be
used in place of the injected-class-name.  — end note ] Such a
constructor name shall be used only in the declarator-id of a
declaration that names a constructor or in a using-declaration.
[ Example:

```<code>struct A { A(); };
struct B: public A { B(); };

A::A() { }
B::B() { }

B::A ba;            // object of type A
A::A a;             // error, A::A is not a type name
struct A::A a2;     // object of type A
</code>```

 — end example ]

Neither of the two bullets above applies. So B::A is not the name of the constructor. It's just the injected class name A, which is already available to use in C. I guess it should be just like bringing in any old type definition from a base class. I.e. Clang would let you define

```<code>C::A a(0);
</code>```

Which appears correct. The only utility of this is if B was inheriting from a protected A. In which case the injected class name would also be inaccessible by default, until brought forward with a using declaration. Tinkering with your example on godbolt confirms it.

MSVC is probably too zealous in rejecting this code outright.

As far as which compiler is correct, C++20 introduced aggregate initialization via parenthesized list of values. C is an aggregate, so C c(1); is in fact aggregate initializing c by using 1 to copy-initialize the B sub-object. So no constructor needs to be inherited by C for this code to be valid.

GCC is indeed doing that (because making the c'tors explicit makes it reject the code), while Clang seems to have not implemented P0960 yet.

Body:
Consider this code:

#include <iostream>
#include <type_traits>

struct A
{
    A(int x) {std::cout << "A(" << x << ")\n";}
};

struct B : A
{
    using A::A;
    B(int x, int y) : A(x) {std::cout << "B(" << x << "," << y << ")\n";}
};

struct C : B
{
    using B::A; // <--

    // C() : B(0,0) {}
};

int main()
{
    C c(1);
}

<a href="https://gcc.godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAM1QDsCBlZAQwBtMQBGAFlICsupVs1qhkAUgBMAISnTSAZ0ztkBPHUqZa6AMKpWAVwC2tLgDZSW9ABk8tTADljAI0zEunUgAdUCwuto9QxNzb19/Olt7JyNXd05PJRU1OgYCZmICIONTTgskzFUAtIyCKMcXNw9FdMzskLya0vKYuI8ASkVUA2JkDgByKQBmO2RDLABqcSGddQUCYkxmI2nscQAGAEFh0fHMKZmCAE8vTAB9BeZCBVWN7a354gNVCfvtgHZZLYmf14g7AgTAAe7Smn3m6BAKG6gOmOjhU0kkk2ECkkgO8JmwIxCLR7XEAFYdLQ0dNZO8ACJ3cSUsnUh4LZ6A6QTECvamfO6/CYGPyiV5Q7ZDL6bbnSf70YGkCYAiZHUFslEgsHSCFQtAGWEzXFI8VonFYoEGnSIySkfVwhFHY2m/FEklIum0rY0qnC%2BmbR5MiYmtkimki7m8uzACbSQVkiYAeijGIAtHGPdyYz6IAqwxB1qR1vjOc6Pm7/VtZUYrrQ0xzA78TcgIJx8e6Xfn%2Bp1WCB%2BgT%2BqRTP11l3UO34TI5BMFN1evthpwuwR2332p0ANYgSQATgAdATuJw10MCUNJEMhgAOIbrY9CdvcLs9vukAf9LsKEBZ2e9lukOCwGCIaFGLx4OwZAUBAaD/oBVTAJw6yeFQgEEG4z4QM4c5ds4dgZEc7bTqQYFGFoBAAPK0KwWHvqQWClqI7CoRReCLEUABumDPuRmBAoUmoDHeALKLRrB4M4xCYXoWDYTOxB4EY4mdDQ9BMGwHCcEM/CCMIogoHIchCIJz6QJ0qBeCktCsXGELTBSEjDjIkjMBMcYAOpsKw9kOexlz2ac6AiGoyBxm4xAkAoT7KIUxmaNo9S5JY2gtJU8RhH4xlRYIPhJQEcWxFUiShUUqS1Fk%2Bg5IIBR5bQJSZJlbSJAVKU1c0dgVFl8SdGOPR9Fwrbtp23a0Q%2BQLHmYcZmNwEzAMgyATNB66cBMEC4IQJCIkMng%2Bqg4FAct9Y%2BlpMgzqhC6kAgSxYO4aakMu7zrOukjnquBIEkiJ7HusFhtv016kNJBJZre/btk%2BL6kG%2B86fj%2BEBIDCXiauQlBgQBQGCJg%2BBEAlcmMCwNHQaQADuwleDJl4djefXtlOEw44QCDAoNw2jeNk3TThIMtp0x3MKdlBdR9Xbfb9pOPooQMs4dy6SNw67cJII3Hvut2nmY6yrip71DCT5EPvt76dF%2BUDg0g8MQcBcPrQjVRjCIUHrNbpBwawCHEEhKHkehtCYeJuHrfh9DEaRtGUZbNHkfgDFqMxrF3uxnEIbRvHvXeAlCSJGADMzknSf006yXQGOKVwKkCGa6liLt8iJ3p52GcZpnmUMlml7ZrnOa57nCZ5yM%2BXgfkBUFIXJAEEW6EVDQxTYjWtNliURIEw/RWl09VZPpXGRVhXBNFy/FAVi8JfMpR1U0lXj/FnVdO1Sncz1f33u2A1DSNEwW/y03Xesc0LajW3SnoG1uMtkigiHLIPawMDpsxOlUc6y5uAEnXOsbg6xJDvBGkefcnBVyriJp9PmvUNYAyFq%2BA6YN4AQxAFDGGIFDaIzNMjRaaMc4KSxlmPGzACaZw/O9K%2BAthjokpgQamd86aP2LlNV%2BcCtbznARzSB3NsEgB%2Brgu8msCGgO1kuFcQw4F5ASOsAk7whjbkkBeVW6slH4JFsQ78JCDamyNrDUCtjEaMWQF4LwZxGLoLOOLM4QIRq23gohSgzs7yu3duwz2RhvZERImRO8AdqLcS7CHMKeBw60SjsgLisd6B8XIonYSxAjiiVThJKShN0aMKUgXEAKtLaaWsmXXS8ADJGQCKxPuKSNAQCsAfKwO9UrhGSrPAZ6VIjH2aiVXKK9arDJyv3fKDVogn3qnUWZh8yjjOqq1ccHV6xEy4Xg/ovjRpGAUM4iYHiNzi3fijJaU5v6OL/sMIYgDS4SNZkdCBZ11GHi0WYHReiDE7mMVeXm8j%2BaHMBoQ7WljfzkIIPYqhVQVK0NRoICpmMlLMPxoTThpj/qDEPEMCmVNgQP1Oecy5N1PoiykZzc6705EKOvso580LJEXQ0X8gF%2BjDEgv6GrRRBL3mHXepIfFN9Ba0tIMxR2A9uBAA" rel="nofollow noreferrer">gcc.godbolt.org

It compiles on GCC and prints A(1), which means that an instance of B was "constructed" without calling the constructor. If you uncomment C(), then C c(1); no longer compiles (GCC can't find a suitable constructor)

Clang doesn't say anything about using B::A;, but refuses to compile C c(1); (also can't find a suitable constructor).

MSVC stops right at using B::A;, basically saying that you can only inherit constructors from direct bases.

Cppreference doesn't mention inheriting constructors from indirect bases, so it seems to be disallowed.

Is it a GCC & Clang bug, or what's going on here?

Body:
The constructor is not inherited. Primarily because

[namespace.udecl]

3 In a using-declaration used as a member-declaration, each
using-declarator's nested-name-specifier shall name a base class of
the class being defined. If a using-declarator names a constructor,
its nested-name-specifier shall name a direct base class of the class
being defined.

But the kicker is that B::A doesn't even name a constructor at all.

[class.qual]

2 In a lookup in which function names are not ignored and the
nested-name-specifier nominates a class C:

if the name specified after the nested-name-specifier, when looked up in C, is the injected-class-name of C (Clause [class]), or

in a using-declarator of a using-declaration that is a member-declaration, if the name specified after the
nested-name-specifier is the same as the identifier or the
simple-template-id's template-name in the last component of the
nested-name-specifier,

the name is instead considered to name the constructor of class C.
[ Note: For example, the constructor is not an acceptable lookup
result in an elaborated-type-specifier so the constructor would not be
used in place of the injected-class-name.  — end note ] Such a
constructor name shall be used only in the declarator-id of a
declaration that names a constructor or in a using-declaration.
[ Example:

struct A { A(); };
struct B: public A { B(); };

A::A() { }
B::B() { }

B::A ba;            // object of type A
A::A a;             // error, A::A is not a type name
struct A::A a2;     // object of type A

 — end example ]

Neither of the two bullets above applies. So B::A is not the name of the constructor. It's just the injected class name A, which is already available to use in C. I guess it should be just like bringing in any old type definition from a base class. I.e. Clang would let you define

C::A a(0);

Which appears correct. The only utility of this is if B was inheriting from a protected A. In which case the injected class name would also be inaccessible by default, until brought forward with a using declaration. Tinkering with your example on godbolt confirms it.

MSVC is probably too zealous in rejecting this code outright.

As far as which compiler is correct, C++20 introduced aggregate initialization via parenthesized list of values. C is an aggregate, so C c(1); is in fact aggregate initializing c by using 1 to copy-initialize the B sub-object. So no constructor needs to be inherited by C for this code to be valid.

GCC is indeed doing that (because making the c'tors explicit makes it reject the code), while Clang seems to have not implemented P0960 yet.


问:
Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

```<code>            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }
</code>```

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)
```

<p>First three lines of my input file:</p>

```Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360
```

答:
When I do System.out.println(Float.parseFloat("0.353"));, it prints out 0.353 as a float, so it must either be something wrong with your split or maybe there's a hidden character somewhere.

Could you try giving your entire code snippet in hopes of us being able to answer better?

Body:
I am parsing a string to a float in Java.

But it throws this exception. I am quite confused with thisproblem since "0.353" is obviously a number which should be parsed by the parseFloat() method.

Did I miss something? Appreciate your help!

            String FitMappath = PathofFile.path+"FitnessMap.txt";
            FileInputStream in = new FileInputStream(FitMappath);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            //Read File Line By Line
            String line;

            while ((line = br.readLine()) != null) {
                String[] parts = line.split("\\s+");            //Split into three elements
                float fitness = Float.parseFloat(parts[2]);// String to float
            }

Exception in thread "main" java.lang.NumberFormatException: For input string: "0.353"
    at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
    at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:110)
    at java.base/java.lang.Float.parseFloat(Float.java:549)
    at DelFitnessCalculation.<init>(DelFitnessCalculation.java:66)
    at Main.main(Main.java:49)

First three lines of my input file:

Q0085   ATP6    0.353
YDR034C-A   YDR034C-A   0.359
tORF13  tORF13  0.360


问:
Datepicker with AlpineJS
I have been working with some of the code samples for AlpineJS. At first the code would only do the year 2020, and would not move past December 2020.

I have managed to get the code to go past 2020 now, however the dates do not update in the calendar view and I cant see what I am missing.

I have my code on a JSFiddle, can anyone see where I am going wrong, as you can go past December 2020, and select a date which then populates the input field fine.

HTML

```<code><div class="flex items-center justify-center">

<div class="antialiased sans-serif">
<div x-data="app()" x-init="[initDate(), getNoOfDays()]" x-cloak>
  <div class="container mx-auto px-4 py-2 md:py-10">
    <div class="mb-5 w-64">

      <label for="datepicker" class="font-bold mb-1 text-gray-700 block">Select Date</label>
      <div class="relative">
        <input type="hidden" name="date" x-ref="date">
        <input type="text" readonly x-model="datepickerValue" @click="showDatepicker = !showDatepicker" @keydown.escape="showDatepicker = false" class="w-full pl-4 pr-10 py-3 leading-none rounded-lg shadow-sm focus:outline-none focus:shadow-outline text-gray-600 font-medium" placeholder="Select date">

        <div class="absolute top-0 right-0 px-3 py-2">
          <svg class="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>
        </div>

        <!-- <div x-text="no_of_days.length"></div>
                      <div x-text="32 - new Date(year, month, 32).getDate()"></div>
                      <div x-text="new Date(year, month).getDay()"></div> -->

        <div class="bg-white mt-12 rounded-lg shadow p-4 absolute top-0 left-0" style="width: 17rem" x-show.transition="showDatepicker" @click.away="showDatepicker = false">

          <div class="flex justify-between items-center mb-2">
            <div>
              <span x-text="MONTH_NAMES[month]" class="text-lg font-bold text-gray-800"></span>
              <span x-text="year" class="ml-1 text-lg text-gray-600 font-normal"></span>
            </div>
            <div>
              <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="month--; getNoOfDays()">
                <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg>
              </button>
              <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="month++; getNoOfDays()">
                <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg>
              </button>
            </div>
          </div>

          <div class="flex flex-wrap mb-3 -mx-1">
            <template x-for="(day, index) in DAYS" :key="index">
              <div style="width: 14.26%" class="px-1">
                <div x-text="day" class="text-gray-800 font-medium text-center text-xs"></div>
              </div>
            </template>
          </div>

          <div class="flex flex-wrap -mx-1">
            <template x-for="blankday in blankdays">
              <div style="width: 14.28%" class="text-center border p-1 border-transparent text-sm"></div>
            </template>
            <template x-for="(date, dateIndex) in no_of_days" :key="dateIndex">
              <div style="width: 14.28%" class="px-1 mb-1">
                <div @click="getDateValue(date)" x-text="date" class="cursor-pointer text-center text-sm leading-none rounded-full leading-loose transition ease-in-out duration-100" :class="{'bg-blue-500 text-white': isToday(date) == true, 'text-gray-700 hover:bg-blue-200': isToday(date) == false }"></div>
              </div>
            </template>
          </div>
        </div>

      </div>
    </div>

  </div>
</div>
</code>```

Alpine code

```<code>const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

      function app() {
          return {
              showDatepicker: false,
              datepickerValue: '',

              month: '',
              year: '',
              no_of_days: [],
              blankdays: [],
              days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],

              initDate() {
                  let today = new Date();
                  this.month = today.getMonth();
                  this.year = today.getFullYear();
                  this.datepickerValue = new Date(this.year, this.month, today.getDate()).toDateString();
              },

              isToday(date) {
                  const today = new Date();
                  const d = new Date(this.year, this.month, date);

                  return today.toDateString() === d.toDateString() ? true : false;
              },

              getDateValue(date) {
                  let selectedDate = new Date(this.year, this.month, date);
                  this.datepickerValue = selectedDate.toDateString();

                  this.$refs.date.value = selectedDate.getFullYear() +"-"+ ('0'+ selectedDate.getMonth()).slice(-2) +"-"+ ('0' + selectedDate.getDate()).slice(-2);

                  console.log(this.$refs.date.value);

                  this.showDatepicker = false;
              },

              getNoOfDays() {
                  let daysInMonth = new Date(this.year, this.month + 1, 0).getDate();

                  // find where to start calendar day of week
                  let dayOfWeek = new Date(this.year, this.month).getDay();
                  let blankdaysArray = [];
                  for ( var i=1; i <= dayOfWeek; i++) {
                      blankdaysArray.push(i);
                  }

                  let daysArray = [];
                  for ( var i=1; i <= daysInMonth; i++) {
                      daysArray.push(i);
                  }

                  this.blankdays = blankdaysArray;
                  this.no_of_days = daysArray;
              }
          }
      }
</code>```

https://jsfiddle.net/alr3id/8pLh9cze/

答:
when you reach December, you need to set increase the year rather then the month and set the month variable back to 0. Similar thing when you are decreasing the month and you hit January.

```<code><div>
    <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="if(month == 0) {month=11;  year--} else {month--}; getNoOfDays()">
        <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
         </svg>
    </button>
    <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="if (month == 11) {month=0; year++} else {month++}; getNoOfDays()">
        <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
        </svg>
    </button>
</div>
</code>```

Something like https://jsfiddle.net/a0726tjw/3/.

It's still returning the odd error about date being undefined which breaks the order of the days when occurs. There's probably another bug somewhere else but I haven't figured out where yet.

Title: Datepicker with AlpineJS

Body:
I have been working with some of the code samples for AlpineJS. At first the code would only do the year 2020, and would not move past December 2020.

I have managed to get the code to go past 2020 now, however the dates do not update in the calendar view and I cant see what I am missing.

I have my code on a JSFiddle, can anyone see where I am going wrong, as you can go past December 2020, and select a date which then populates the input field fine.

HTML

      Select Date

        <input type="hidden" name="date" x-ref="date">
        <input type="text" readonly x-model="datepickerValue" @click="showDatepicker = !showDatepicker" @keydown.escape="showDatepicker = false" class="w-full pl-4 pr-10 py-3 leading-none rounded-lg shadow-sm focus:outline-none focus:shadow-outline text-gray-600 font-medium" placeholder="Select date">

          <svg class="h-6 w-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
          </svg>

              <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="month--; getNoOfDays()">
                <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                </svg>
              </button>
              <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="month++; getNoOfDays()">
                <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                </svg>
              </button>

            <template x-for="(day, index) in DAYS" :key="index">

            </template>

            <template x-for="blankday in blankdays">

            </template>
            <template x-for="(date, dateIndex) in no_of_days" :key="dateIndex">

            </template>

Alpine code

const MONTH_NAMES = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
      const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

      function app() {
          return {
              showDatepicker: false,
              datepickerValue: '',

              month: '',
              year: '',
              no_of_days: [],
              blankdays: [],
              days: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],

              initDate() {
                  let today = new Date();
                  this.month = today.getMonth();
                  this.year = today.getFullYear();
                  this.datepickerValue = new Date(this.year, this.month, today.getDate()).toDateString();
              },

              isToday(date) {
                  const today = new Date();
                  const d = new Date(this.year, this.month, date);

                  return today.toDateString() === d.toDateString() ? true : false;
              },

              getDateValue(date) {
                  let selectedDate = new Date(this.year, this.month, date);
                  this.datepickerValue = selectedDate.toDateString();

                  this.$refs.date.value = selectedDate.getFullYear() +"-"+ ('0'+ selectedDate.getMonth()).slice(-2) +"-"+ ('0' + selectedDate.getDate()).slice(-2);

                  console.log(this.$refs.date.value);

                  this.showDatepicker = false;
              },

              getNoOfDays() {
                  let daysInMonth = new Date(this.year, this.month + 1, 0).getDate();

                  // find where to start calendar day of week
                  let dayOfWeek = new Date(this.year, this.month).getDay();
                  let blankdaysArray = [];
                  for ( var i=1; i <= dayOfWeek; i++) {
                      blankdaysArray.push(i);
                  }

                  let daysArray = [];
                  for ( var i=1; i <= daysInMonth; i++) {
                      daysArray.push(i);
                  }

                  this.blankdays = blankdaysArray;
                  this.no_of_days = daysArray;
              }
          }
      }

https://jsfiddle.net/alr3id/8pLh9cze/

Body:
when you reach December, you need to set increase the year rather then the month and set the month variable back to 0. Similar thing when you are decreasing the month and you hit January.

<div>
    <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="if(month == 0) {month=11;  year--} else {month--}; getNoOfDays()">
        <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
         </svg>
    </button>
    <button type="button" class="transition ease-in-out duration-100 inline-flex cursor-pointer hover:bg-gray-200 p-1 rounded-full" @click="if (month == 11) {month=0; year++} else {month++}; getNoOfDays()">
        <svg class="h-6 w-6 text-gray-500 inline-flex" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
        </svg>
    </button>
</div>

Something like https://jsfiddle.net/a0726tjw/3/.

It's still returning the odd error about date being undefined which breaks the order of the days when occurs. There's probably another bug somewhere else but I haven't figured out where yet.


问:
How can I download and save a file from the Internet using Java?
There is an online file (such as http://www.example.com/information.asp) I need to grab and save to a directory. I know there are several methods for grabbing and reading online files (URLs) line-by-line, but is there a way to just download and save the file using Java?

答:
First method using the new channel

```<code>ReadableByteChannel aq = Channels.newChannel(new url("https//asd/abc.txt").openStream());
FileOutputStream fileOS = new FileOutputStream("C:Users/local/abc.txt")
FileChannel writech = fileOS.getChannel();
</code>```

Second method using FileUtils

```<code>FileUtils.copyURLToFile(new url("https//asd/abc.txt", new local file on system("C":/Users/system/abc.txt"));
</code>```

Third method using

```<code>InputStream xy = new ("https//asd/abc.txt").openStream();
</code>```

This is how we can download file by using basic Java code and other third-party libraries. These are just for quick reference. Please google with the above keywords to get detailed information and other options.

Body:
First method using the new channel

ReadableByteChannel aq = Channels.newChannel(new url("https//asd/abc.txt").openStream());
FileOutputStream fileOS = new FileOutputStream("C:Users/local/abc.txt")
FileChannel writech = fileOS.getChannel();

Second method using FileUtils

FileUtils.copyURLToFile(new url("https//asd/abc.txt", new local file on system("C":/Users/system/abc.txt"));

Third method using

InputStream xy = new ("https//asd/abc.txt").openStream();

This is how we can download file by using basic Java code and other third-party libraries. These are just for quick reference. Please google with the above keywords to get detailed information and other options.


问:
Do I have to reinstall software packages after restoring from EBS Snapshot on AWS
I am having trouble fully understanding the differences between EBS Snapshots and AMI's in AWS.  I understand how to create them and the terminology (Snapshots are backups of Volumes or the disk attached to an EC2 Instance and AMI is the backup of the full EC2 instance with snapshots at given time).  But, I'm not sure what exactly is saved in the snapshot.

Assume I have an EC2 instance with LAMP stack installed on it and some data from the database.  I understand the snapshot will save all my data and website files.  When I create the new EC2 instance and attach the volume backed by my snapshot, do I then have to install Apache, MySQL, and PHP again?  Or is that all saved in the snapshot?  I am not worried about having to redo the security settings, instance type, etc for the new EC2 instance, but am worried all the configuration files are lost unless I have an AMI.

答:
I understand how to create them and the terminology (Snapshots are backups of Volumes or the disk attached to an EC2 Instance and AMI is the backup of the full EC2 instance with snapshots at given time)

This is kinda correct, but not exactly. A better understanding of the concepts may help you in general, so here it goes.

A snapshot represents the state of an EBS volume at an exact point in time, taken atomically, that you can use to create other EBS volumes from. Those new EBS volumes, created from the snapshot, will start with the exact same content as the original EBS volume at the time the snapshot was taken. So, kind of a "backup of volumes").

One extremely important thing about Snapshots, though, that you seem to be missing based on the rest of your question, is that Snapshots are immutable. Once create, the contents of a snapshot cannot change, ever.

An AMI is an Image — it's used to create an instance from. It's a bunch of metadata, which includes the type of hypervisor required, accounts allowed to use it, and ultimately it contains a list of EBS Snapshots that should be used to create volumes, and where exactly to attach the volumes created from those snapshots.

So, while "creating an AMI" is indeed a strategy some people use to create a "backup of the full EC2 instance", it's not exactly the same thing.

When I create the new EC2 instance and attach the volume backed by my snapshot [...]

I think you're confusing some concepts here.

When a new EBS volume is created from a snapshot (either by you creating the EBS volume directly and selecting a snapshot, or by using an AMI, which implicitly means that EBS volumes are going to be created from the Snapshots as specified in the metadata that the AMI represents), there's no relationship between that snapshot and the new volume anymore. Any changes made to the volume are completely independent of the original snapshot. Remember: snapshots are immutable.

So, this notion of "the volume backed by my snapshot" may be quite unhelpful: there's no link between them.

Hoping this is clear, let's move on...

When I create the new EC2 instance [...], do I then have to install Apache, MySQL, and PHP again? Or is that all saved in the snapshot?

The software that will come pre-installed in the EC2 instance is defined by the contents of the snapshots used when the EBS volumes attached to the instance were created.

In other words, if you create an EC2 instance from a standard AMI (not one that you create) that doesn't come with the software pre-installed, then the software won't be installed.

If you create an AMI from your instance before you install the software you want, then the AMI (or, more precisely, the snapshots referenced by the AMI) won't have the software, so any instances created from that AMI won't come with the software.

Now, here's what you are probably looking for:

If you (1) create an instance, then (2) install the software, and only then (3) you create an AMI, in this order, then any new instances created from that AMI will come with the software pre-installed.

The easiest way to fully and truly understand this is to remember that (A) Snapshots are immutable, and (B) AMIs are immutable references to Snapshots.

All that said, while creating a custom AMI is indeed a completely valid and popular approach to the problem you are dealing with, there's another approach that's also completely valid and popular, but that is more flexible, and could be worth investigating.

Instead of having to create and manage AMIs (*), what you could do is use a user data script.

Essentially, what it does is it allows you to have a script, that will execute as root, on the first boot of a newly created instance. This script is often used to install software, update packages, download configuration files, etc.

This way, if you need to change versions of software, or change configuration files, etc, you don't need to go through all the complexity of managing AMIs. Instead, you simply update the script.

For more info on user data, check this out: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html

(*) "manage AMIs": remember that an AMI is an immutable set of metadata which includes reference to Snapshots, which are also immutable. So if you ever need to change some settings, or have new versions of the software be installed, you will need to create new AMIs. This could become something quite complicated and time-consuming. In fact, there's a ton of tools out there, some by AWS, some by other companies, that try to simplify the process of creating and managing AMIs. So just be aware that, while doable, valid, and popular, it's an approach that can get messy!


问:
Why do the lsl and lsr functions cause these flags in the SREG
Given the following assembly code:

```<code>ldi     r26, 0x00
ldi     r27, 0x01
ldi     r30, 0xAC
lsl     r30
lsr     r30
asr     r30
</code>```

Immediately following the lsl operation, the H, S, V, and C SREG flags are raised. I do not understand why. I understand that when the lsl operation shifts the bits to the left, that bit 7 raises the C flag. What I don't understand is why the other three flags are raised.

According to
the atmel instruction manual, lsl effectively multiplies the value by 2. If r30 starts as 0xAC (172), then why does lsl make it 0x58 (88). This is also the point where all of the flags are raised.

After this operation, I understand why everything else does what it does, as lsr and asr both effectively divide the value by 2. After the lsr operation, r30 is 44, and after the asr operation, r30 is 22.

答:
Since your registers are 8 bits, shifting 0xAC left will lose a bit. 0xAC * 2 = 0x158 but the 1 is lost (is in the carry flag). The remainder is of course the 0x58 you are seeing. The flags are documented in the instruction set reference as:

H: Rd3

C: Rd7

N: Set if MSB of the result is set; cleared otherwise.

V: N xor C

S: N xor V

Rd3 is bit #3 of the input operand. It is set, so H = 1.

Rd7 is bit #7 of the input operand. It is set, so C = 1.

MSB of the result is not set, so N = 0.

V = N xor C = 0 xor 1 = 1

S = N xor V = 0 xor 1 = 1

Body:
Given the following assembly code:

ldi     r26, 0x00
ldi     r27, 0x01
ldi     r30, 0xAC
lsl     r30
lsr     r30
asr     r30

Immediately following the lsl operation, the H, S, V, and C SREG flags are raised. I do not understand why. I understand that when the lsl operation shifts the bits to the left, that bit 7 raises the C flag. What I don't understand is why the other three flags are raised.

According to
the atmel instruction manual, lsl effectively multiplies the value by 2. If r30 starts as 0xAC (172), then why does lsl make it 0x58 (88). This is also the point where all of the flags are raised.

After this operation, I understand why everything else does what it does, as lsr and asr both effectively divide the value by 2. After the lsr operation, r30 is 44, and after the asr operation, r30 is 22.