问:
Can't seem to break while loop properly. Comes up with an error message
The code takes data from csv and reads up to row with no data- works well but code ends in error - break not working properly? Carries out necessary function of reading all data but it seems to continue through the while true statement past len(row) > 0 when it should be an empty row where len(row) == 0 - any ideas how to stop error message? Functionality is good but error message is obviously a tad annoying.</p>

```<code>while True:
    len(row) > 0
    row = csvFileArray[rowValue]  # row
    x, y, z, l, m, n, p, q, r = row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]

    x = float(x)
    y = float(y)
    z = float(z)
    l = float(l)
    m = float(m)
    n = float(n)
    p = float(p)
    q = float(q)
    r = float(r)

    y_axis = Vector((l, m, n))
    z_axis = Vector((p, q, r))

    x_axis = y_axis.cross(z_axis).normalized()

    M = Matrix((x_axis, y_axis, z_axis)).transposed()

    M = M.to_4x4()

    M.translation = scale * Vector((x, y, z))

    #test
    print(M)
    print(x_axis, y_axis, z_axis)
    bpy.ops.object.empty_add()
    mt = context.object
    mt.empty_display_type = 'ARROWS'
    mt.matrix_world = M

    rowValue = rowValue + 1

    if len(row) == 0:
        break
</code>```

答:
Change the position of the break condition and change it to:

```<code>    if len(row) == 0:
        break
</code>```

to

```<code>    if len(row) <= 0:
        break
</code>```

Edited code:

```<code>while True:

    row = csvFileArray[rowValue]  # row
    if len(row) <= 0:
        break
    x, y, z, l, m, n, p, q, r = row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]

    x = float(x)
    y = float(y)
    z = float(z)
    l = float(l)
    m = float(m)
    n = float(n)
    p = float(p)
    q = float(q)
    r = float(r)

    y_axis = Vector((l, m, n))
    z_axis = Vector((p, q, r))

    x_axis = y_axis.cross(z_axis).normalized()

    M = Matrix((x_axis, y_axis, z_axis)).transposed()

    M = M.to_4x4()

    M.translation = scale * Vector((x, y, z))

    #test
    print(M)
    print(x_axis, y_axis, z_axis)
    bpy.ops.object.empty_add()
    mt = context.object
    mt.empty_display_type = 'ARROWS'
    mt.matrix_world = M

    rowValue = rowValue + 1
    # Printing the row variable might help in figuring out the error.
</code>```

Body:
The code takes data from csv and reads up to row with no data- works well but code ends in error - break not working properly? Carries out necessary function of reading all data but it seems to continue through the while true statement past len(row) > 0 when it should be an empty row where len(row) == 0 - any ideas how to stop error message? Functionality is good but error message is obviously a tad annoying.

while True:
    len(row) > 0
    row = csvFileArray[rowValue]  # row
    x, y, z, l, m, n, p, q, r = row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]

    x = float(x)
    y = float(y)
    z = float(z)
    l = float(l)
    m = float(m)
    n = float(n)
    p = float(p)
    q = float(q)
    r = float(r)

    y_axis = Vector((l, m, n))
    z_axis = Vector((p, q, r))

    x_axis = y_axis.cross(z_axis).normalized()

    M = Matrix((x_axis, y_axis, z_axis)).transposed()

    M = M.to_4x4()

    M.translation = scale * Vector((x, y, z))

    #test
    print(M)
    print(x_axis, y_axis, z_axis)
    bpy.ops.object.empty_add()
    mt = context.object
    mt.empty_display_type = 'ARROWS'
    mt.matrix_world = M

    rowValue = rowValue + 1

    if len(row) == 0:
        break

Body:
Change the position of the break condition and change it to:

    if len(row) == 0:
        break

to

    if len(row) <= 0:
        break

Edited code:

while True:

    row = csvFileArray[rowValue]  # row
    if len(row) <= 0:
        break
    x, y, z, l, m, n, p, q, r = row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]

    x = float(x)
    y = float(y)
    z = float(z)
    l = float(l)
    m = float(m)
    n = float(n)
    p = float(p)
    q = float(q)
    r = float(r)

    y_axis = Vector((l, m, n))
    z_axis = Vector((p, q, r))

    x_axis = y_axis.cross(z_axis).normalized()

    M = Matrix((x_axis, y_axis, z_axis)).transposed()

    M = M.to_4x4()

    M.translation = scale * Vector((x, y, z))

    #test
    print(M)
    print(x_axis, y_axis, z_axis)
    bpy.ops.object.empty_add()
    mt = context.object
    mt.empty_display_type = 'ARROWS'
    mt.matrix_world = M

    rowValue = rowValue + 1
    # Printing the row variable might help in figuring out the error.


来源: stackexchange

问:
Add swap memory with ansible
I'm working on a project where having swap memory on my servers is a needed to avoid some python long running processes to go out of memory and realized for the first time that my ubuntu vagrant boxes and AWS ubuntu instances didn't already have one set up.

In https://github.com/ansible/ansible/issues/5241 a possible built in solution was discussed but never implemented, so I'm guessing this should be a pretty common task to automatize.

How would you set up a file based swap memory with ansible in an idempotent way? What modules or variables does ansible provide help with this setup (like ansible_swaptotal_mb variable) ?

答:
What works for me is to add 4Gib swap through the playbook.

Check this:

.

ContentLicense: CC BY-SA 3.0

Title: Add swap memory with ansible

ContentLicense: CC BY-SA 4.0


问:
What is the reason for getting error 1054?
Getting this error while inserting data into the table.

Error Code: 1054. Unknown column '1' in 'field list'

I'm using MySQL Server 5.6.*.

I already looked at a lot of threads on StackOverflow and a lot of articles on the Internet, but still, I just don’t understand how to make this query work for me.

I've already tried:

not to set the PlayerID value myself

to leave it totally out from the query, but then I get another error 1064

```<code>CREATE TABLE IF NOT EXISTS `PLAYERS` (
      `PlayerID` INT NOT NULL AUTO_INCREMENT,
      `FirstName` VARCHAR(32) NOT NULL,
      `LastName` VARCHAR(32) NOT NULL,
      `NickName` VARCHAR(32) NOT NULL,
      `Gender` CHAR(1) NULL,
      `BirthDate` DATE NULL,
      `TeamID` INT NULL,
      `CountryID` INT NOT NULL,
      INDEX `FirstName_idx` (`FirstName` ASC),
      INDEX `LastName_idx` (`LastName` ASC),
      INDEX `NickName_idx` (`NickName` ASC),
      INDEX `TeamID_idx` (`TeamID` ASC),
      INDEX `CountryID_idx` (`CountryID` ASC),
      PRIMARY KEY (`PlayerID`),
      CONSTRAINT `TeamID`
        FOREIGN KEY (`TeamID`)
        REFERENCES `CSGO`.`TEAMS` (`TeamID`)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
      CONSTRAINT `PlayerCountryID`
        FOREIGN KEY (`CountryID`)
        REFERENCES `CSGO`.`COUNTRIES` (`CountryID`)
        ON DELETE CASCADE
        ON UPDATE CASCADE)
</code>```

```<code>INSERT INTO `PLAYERS` (`PlayerID`, `FirstName`, `LastName`, `NickName`, `Gender`, `BirthDate`, `TeamID`, `CountryID`)
   VALUES (1, 'Fatih', 'Dayik', 'gob b', 'M', '1987-07-10', NULL, 80);
INSERT INTO `PLAYERS` (`PlayerID`, `FirstName`, `LastName`, `NickName`, `Gender`, `BirthDate`, `TeamID`, `CountryID`)
   VALUES (2, 'Nikola', 'Ninic', 'LEGIJA', 'M', '1990-11-15', NULL, 216);
</code>```

DB STRUCTURE HERE

答:
I managed to find out the reason which occurs that error code.

I exported all inserts of Players table to an external CSV-file and found the following issue.

There were some hidden characters just before 1 that Notepad++ didn't show up.
Removing extra characters resolved the situation.

Body:
Getting this error while inserting data into the table.

Error Code: 1054. Unknown column '1' in 'field list'

I'm using MySQL Server 5.6.*.

I already looked at a lot of threads on StackOverflow and a lot of articles on the Internet, but still, I just don’t understand how to make this query work for me.

I've already tried:

not to set the PlayerID value myself

to leave it totally out from the query, but then I get another error 1064

CREATE TABLE IF NOT EXISTS `PLAYERS` (
      `PlayerID` INT NOT NULL AUTO_INCREMENT,
      `FirstName` VARCHAR(32) NOT NULL,
      `LastName` VARCHAR(32) NOT NULL,
      `NickName` VARCHAR(32) NOT NULL,
      `Gender` CHAR(1) NULL,
      `BirthDate` DATE NULL,
      `TeamID` INT NULL,
      `CountryID` INT NOT NULL,
      INDEX `FirstName_idx` (`FirstName` ASC),
      INDEX `LastName_idx` (`LastName` ASC),
      INDEX `NickName_idx` (`NickName` ASC),
      INDEX `TeamID_idx` (`TeamID` ASC),
      INDEX `CountryID_idx` (`CountryID` ASC),
      PRIMARY KEY (`PlayerID`),
      CONSTRAINT `TeamID`
        FOREIGN KEY (`TeamID`)
        REFERENCES `CSGO`.`TEAMS` (`TeamID`)
        ON DELETE CASCADE
        ON UPDATE CASCADE,
      CONSTRAINT `PlayerCountryID`
        FOREIGN KEY (`CountryID`)
        REFERENCES `CSGO`.`COUNTRIES` (`CountryID`)
        ON DELETE CASCADE
        ON UPDATE CASCADE)

INSERT INTO `PLAYERS` (`PlayerID`, `FirstName`, `LastName`, `NickName`, `Gender`, `BirthDate`, `TeamID`, `CountryID`)
   VALUES (1, 'Fatih', 'Dayik', 'gob b', 'M', '1987-07-10', NULL, 80);
INSERT INTO `PLAYERS` (`PlayerID`, `FirstName`, `LastName`, `NickName`, `Gender`, `BirthDate`, `TeamID`, `CountryID`)
   VALUES (2, 'Nikola', 'Ninic', 'LEGIJA', 'M', '1990-11-15', NULL, 216);

DB STRUCTURE HERE


问:
Split a data.table at position
I want to calculate the mean of a column in a data.table way by using row numbers or a vector with position.

Here is a sample data and a postion vector:

```<code>x <- data.table(a = c(1,2,3,4,5,6,7,8))
pos <- c(3,5)
</code>```

I tried:

```<code>x[mean(a), by = pos]
</code>```

So i want the mean from row 1:2, 3:4 and 5:8.

答:
Here is an option:

```<code>x[, mean(a), cumsum(replace(rep(0, nrow(x)), pos, 1L))]
</code>```

output:

```<code>   cumsum  V1
1:      0 1.5
2:      1 3.5
3:      2 6.5
</code>```

Title: Split a data.table at position

Body:
I want to calculate the mean of a column in a data.table way by using row numbers or a vector with position.

Here is a sample data and a postion vector:

x <- data.table(a = c(1,2,3,4,5,6,7,8))
pos <- c(3,5)

I tried:

x[mean(a), by = pos]

So i want the mean from row 1:2, 3:4 and 5:8.

Body:
Here is an option:

x[, mean(a), cumsum(replace(rep(0, nrow(x)), pos, 1L))]

output:

   cumsum  V1
1:      0 1.5
2:      1 3.5
3:      2 6.5


问:
React: TypeError: dispatch is not a function
I want to fetch from redux. I am following this tutorial: https://codesandbox.io/s/react-redux-application-hewdb?file=/src/pages/PostsPage.js

But when i used it in my code that is:

```<code>import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import {fetchInterview} from '../actions/interviewActions'

const DetailInterview = (props, { dispatch, loading, interviews, hasErrors }) => {

  console.log("test interview",interviews)
  useEffect(() => {
    const { match: { params: { id } } } = props;
    dispatch(fetchInterview(id))
  }, [dispatch])

  const interviewslist = interviews

  console.log('interview: ', interviews)

  return (
    <div>
      <h3>All participants</h3>
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Interview id</th>
            <th>Partcipants id</th>
            <th>Time</th>
          </tr>
        </thead>
        <tbody>
          {
            console.log('interviews:sad ', interviews)
          }
          {
            interviews? interviews.map((interview) => {
              console.log('sadassad',interview)
              console.log('sadaghahhgsghssad',interviews)
              return (
                <tr key={interview.id}>
                  <td>{interview.id}</td>
                  <td>{interview.interview_id}</td>
                  <td>
                    {/* <Link to={`/posts/${post.id}`}> */}
                    {interview.participant_id}
                    {/* </Link> */}
                  </td>
                  <td>{interview.created_at}</td>
                </tr>
              )
            }) : null
          }
        </tbody>
      </table>
    </div>
  );
}

// export default DetailInterview;

const mapStateToProps = state => ({
  loading: state.interview.loading,
  interviews: state.interview.interview,
  hasErrors: state.interview.hasErrors,
})
export default connect(mapStateToProps)(DetailInterview)
</code>```

I get an error: Uncaught TypeError: dispatch is not a function

Could not understand what is the error behind this.

答:
You are destructuring values from the second argument of DetailInterview whereas you should do that from props as values from mapStateToProps and connect are available as props to the connected component</p>

```<code>const DetailInterview = (props) => {
    const { dispatch, loading, interviews, hasErrors } = props;
    ...
}
</code>```

Body:
I want to fetch from redux. I am following this tutorial: https://codesandbox.io/s/react-redux-application-hewdb?file=/src/pages/PostsPage.js

But when i used it in my code that is:

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import {fetchInterview} from '../actions/interviewActions'

const DetailInterview = (props, { dispatch, loading, interviews, hasErrors }) => {

  console.log("test interview",interviews)
  useEffect(() => {
    const { match: { params: { id } } } = props;
    dispatch(fetchInterview(id))
  }, [dispatch])

  const interviewslist = interviews

  console.log('interview: ', interviews)

  return (

All participants

            ID
            Interview id
            Partcipants id
            Time

          {
            console.log('interviews:sad ', interviews)
          }
          {
            interviews? interviews.map((interview) => {
              console.log('sadassad',interview)
              console.log('sadaghahhgsghssad',interviews)
              return (

                  {interview.id}
                  {interview.interview_id}

                    {/* <Link to={`/posts/${post.id}`}> */}
                    {interview.participant_id}
                    {/* </Link> */}

                  {interview.created_at}

              )
            }) : null
          }

  );
}

// export default DetailInterview;

const mapStateToProps = state => ({
  loading: state.interview.loading,
  interviews: state.interview.interview,
  hasErrors: state.interview.hasErrors,
})
export default connect(mapStateToProps)(DetailInterview)

I get an error: Uncaught TypeError: dispatch is not a function

Could not understand what is the error behind this.

Body:
You are destructuring values from the second argument of DetailInterview whereas you should do that from props as values from mapStateToProps and connect are available as props to the connected component

const DetailInterview = (props) => {
    const { dispatch, loading, interviews, hasErrors } = props;
    ...
}


问:
NGINX do not pass response header
I have a  java spring application running on port 8080, this app should return a header 'x-auth-token', this app run behind nginx reverse proxy.

The application correctly produce the header, When i request directly to it (bypassing nginx):

http://169.54.76.123:8080

it responds with the header in the set of response headers

but when i make the request through the nginx reverse proxy, the header does not appear

https://169.54.76.123

nginx handles ssl termination.

my nginx conf file

```<code>upstream loadbalancer {
    server 169.54.76.123:8080 ;
}

server {
    listen      169.54.76.123:80;
    server_name api.ecom.com;
    return 301 https://api.ecom.com$request_uri;
}
server {
    listen 169.54.76.123:443 ssl;
    keepalive_timeout   70;
    server_name api.ecom.com;

    ssl_certificate /etc/ssl/api_chained.cert ;
    ssl_certificate_key /etc/ssl/api.key ;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 SSLv3 SSLv2;
    ssl_ciphers         ALL:!ADH:RC4+RSA:HIGH:!aNULL:!MD5;

    charset utf-8;

    location / {
        proxy_pass http://loadbalancer/$request_uri ;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
</code>```

The question is: Why nGinx do not pass the 'x-auth-token' to the response?

How to include it into the response?

I tried to get the value in a variable, but it seems that nGinx do not have it:

I used $sent_http_x_auth_token  and $upstream_htto_x_auth_token but these variables does not contain any values (i think)

I tried adding the header myself using these variables:

add_header x-auth-token $sent_http_x_auth_token; with no success

also tried:

add_header x-auth-token $upstream_http_x_auth_token; with no success either.

also, I tried:

proxy_pass_header x-auth-token;

with no success

What is the problem? How can i debug it?
which part prevents or blocks the 'x-auth-header'? the upstream or the proxy or what?

Thanks for any help

答:
The sent_ prefix should not be there.
The correct way to log customer headers is to prefix them with http_ and then write the customer header all lowercase and convert dashes (-) to underscores (_). For example 'Custom-Header' would be http_custom_header

So the correct way to log this is:

```<code>log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_x_auth_token"';

access_log  logs/access.log  main;
</code>```

Also please be aware that if your header contains underscores you will need to explicitly allow this by adding this in your nginx config:

```<code>underscores_in_headers on
</code>```

If you want to test your custom header, you can use curl:

```<code>curl -v -H "Custom-Header: any value that you want" http://www.yourdomain.com/path/to/endpoint
</code>```

The -H will add the header and -v will show you both the request and response headers that are sent

Title: NGINX do not pass response header

Body:
I have a  java spring application running on port 8080, this app should return a header 'x-auth-token', this app run behind nginx reverse proxy.

The application correctly produce the header, When i request directly to it (bypassing nginx):

http://169.54.76.123:8080

it responds with the header in the set of response headers

but when i make the request through the nginx reverse proxy, the header does not appear

https://169.54.76.123

nginx handles ssl termination.

my nginx conf file

upstream loadbalancer {
    server 169.54.76.123:8080 ;
}

server {
    listen      169.54.76.123:80;
    server_name api.ecom.com;
    return 301 https://api.ecom.com$request_uri;
}
server {
    listen 169.54.76.123:443 ssl;
    keepalive_timeout   70;
    server_name api.ecom.com;

    ssl_certificate /etc/ssl/api_chained.cert ;
    ssl_certificate_key /etc/ssl/api.key ;
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2 SSLv3 SSLv2;
    ssl_ciphers         ALL:!ADH:RC4+RSA:HIGH:!aNULL:!MD5;

    charset utf-8;

    location / {
        proxy_pass http://loadbalancer/$request_uri ;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

The question is: Why nGinx do not pass the 'x-auth-token' to the response?

How to include it into the response?

I tried to get the value in a variable, but it seems that nGinx do not have it:

I used $sent_http_x_auth_token  and $upstream_htto_x_auth_token but these variables does not contain any values (i think)

I tried adding the header myself using these variables:

add_header x-auth-token $sent_http_x_auth_token; with no success

also tried:

add_header x-auth-token $upstream_http_x_auth_token; with no success either.

also, I tried:

proxy_pass_header x-auth-token;

with no success

What is the problem? How can i debug it?
which part prevents or blocks the 'x-auth-header'? the upstream or the proxy or what?

Thanks for any help

Body:
The sent_ prefix should not be there.
The correct way to log customer headers is to prefix them with http_ and then write the customer header all lowercase and convert dashes (-) to underscores (_). For example 'Custom-Header' would be http_custom_header

So the correct way to log this is:

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_x_auth_token"';

access_log  logs/access.log  main;

Also please be aware that if your header contains underscores you will need to explicitly allow this by adding this in your nginx config:

underscores_in_headers on

If you want to test your custom header, you can use curl:

curl -v -H "Custom-Header: any value that you want" http://www.yourdomain.com/path/to/endpoint

The -H will add the header and -v will show you both the request and response headers that are sent


问:
Select two tables between dates?
I get this error:

Incorrect syntax near '2020-05-29'.

How to fix this?

```<code>SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate BETWEEN '2020-05-28' AND BorrowerDetails.DueDate '2020-05-29'
</code>```

答:
BETWEEN doesn't work in that format. You need to change your data format or use epoch time for these dates.

```<code>SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate >= 20200528
AND BorrowerDetails.DueDate <= 20200529;
</code>```

Don't forget to remove single quotes . We are comparing it like numbers , not like strings.

Title: Select two tables between dates?

Body:
I get this error:

Incorrect syntax near '2020-05-29'.

How to fix this?

SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate BETWEEN '2020-05-28' AND BorrowerDetails.DueDate '2020-05-29'

Body:
BETWEEN doesn't work in that format. You need to change your data format or use epoch time for these dates.

SELECT Borrower.BorrowedDate, BorrowerDetails.DueDate
FROM Borrower, BorrowerDetails
WHERE Borrower.BorrowedDate >= 20200528
AND BorrowerDetails.DueDate <= 20200529;

Don't forget to remove single quotes . We are comparing it like numbers , not like strings.


问:
Set up WordPress in a pc running XAMPP and IIS
I'm trying to install WordPress on my laptop I've already installed XAMPP and have Apache and MySQL running, I downloaded WordPress and extracted it inside htdocs, my laptop already had IIS installed.

When I go to localhost/WordPress I get 404 -Not found, looking at detailed info of the error the Physical path is set to C:\inetpub\wwwroot\WordPress and the label of the chrome tab is "IIS 8.5 detailed Error".

This makes me think that my localhost is set to run with IIS and not with XAMPP.

How can I change my localhost to run with XAMPP htdocs instead of IIS wwwroot?

答:
Download the latest WordPress package from the official website and extract the contents into the XAMPP default website directory.

Basically, XAMPP sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.
You could get more details by checking the below link.

How do I test a website using XAMPP?

Then stop IIS's website using port 80，try it again.

Have a look at the handy guide for installing WordPress.

https://wordpress.org/support/article/how-to-install-wordpress/


问:
Button not being displayed in window
I'm trying to add three buttons to a window. I've tried it without classing and it works fine. But when I add it in a class, it only show me an empty window. What am I doing wrong?

PS: I'm still in the process of learning the ropes in python.

```<code>from tkinter import filedialog,Button,Frame,Tk

class Textify:

    def __init__(self,master):
        self.master = master
        self.initializeOutlineFrame

    def initializeOutlineFrame(self):
        self.convertImageButton = Button(master,text="Convert Image",command=self.browseIMG,width=80,height=30)
        self.convertImageButton.pack()
        self.convertPdfButton = Button(master,text="Convert pdf",command=self.browsePDF)
        self.convertPdfButton.pack()
        self.batchConvertButton = Button(master,text="Convert multiple files",command=self.browseAllFiles)
        self.batchConvertButton.pack()

    def browsePDF(self):
        filename = filedialog.askopenfilename(initialdir = "/",
        title = "Select a File",filetypes = (("pdf files","*.pdf*"),("all files", "*.*")))

    def browseIMG(self):
        filename = filedialog.askopenfilename(initialdir = "/",
        title = "Select a File",filetypes = (("jpg files","*.JPG*"),("png files","*.PNG*")))

    def browseAllFiles(self):
        filename = filedialog.askopenfilename(initialdir = "/",
        title = "Select files",filetypes = (("jpg files","*.JPG*"),("png files","*.PNG*"),("pdf files","*.pdf*")))

window = Tk()
window.title("Textify")
window.geometry("450x450")
app = Textify(window)
window.mainloop()
</code>```

答:
Use initializeOutlineFrame() instead of initializeOutlineFrame.

In the def initializeOutlineFrame(self, master), change all master into self.master.

Be careful ! width=80,height=30 doesn't define the size in pixels, but in characters. So at this stade, if you run the code, you are going to see a giant button and not the others buttons. Remove or change the values, for example like width=17,height=3.

[optional] You can grid buttons instead of pack for adding space around. It looks better:

```<code>def initializeOutlineFrame(self):

    self.convertImageButton = Button(self.master, text="Convert Image", \
    command=self.browseIMG, width=17, height=3)
    self.convertImageButton.grid(column=0, row=0, padx=10, pady=10)

    self.convertPdfButton = Button(self.master, text="Convert pdf", \
    command=self.browsePDF, width=17, height=3)
    self.convertPdfButton.grid(column=1, row=0, padx=10, pady=10)

    self.batchConvertButton = Button(self.master, text="Convert multiple files", \
    command=self.browseAllFiles, width=17, height=3)
    self.batchConvertButton.grid(column=2, row=0, padx=10, pady=10)
</code>```

Title: Button not being displayed in window

Body:
I'm trying to add three buttons to a window. I've tried it without classing and it works fine. But when I add it in a class, it only show me an empty window. What am I doing wrong?

PS: I'm still in the process of learning the ropes in python.

from tkinter import filedialog,Button,Frame,Tk

class Textify:

    def __init__(self,master):
        self.master = master
        self.initializeOutlineFrame

    def initializeOutlineFrame(self):
        self.convertImageButton = Button(master,text="Convert Image",command=self.browseIMG,width=80,height=30)
        self.convertImageButton.pack()
        self.convertPdfButton = Button(master,text="Convert pdf",command=self.browsePDF)
        self.convertPdfButton.pack()
        self.batchConvertButton = Button(master,text="Convert multiple files",command=self.browseAllFiles)
        self.batchConvertButton.pack()

    def browsePDF(self):
        filename = filedialog.askopenfilename(initialdir = "/",
        title = "Select a File",filetypes = (("pdf files","*.pdf*"),("all files", "*.*")))

    def browseIMG(self):
        filename = filedialog.askopenfilename(initialdir = "/",
        title = "Select a File",filetypes = (("jpg files","*.JPG*"),("png files","*.PNG*")))

    def browseAllFiles(self):
        filename = filedialog.askopenfilename(initialdir = "/",
        title = "Select files",filetypes = (("jpg files","*.JPG*"),("png files","*.PNG*"),("pdf files","*.pdf*")))

window = Tk()
window.title("Textify")
window.geometry("450x450")
app = Textify(window)
window.mainloop()

Body:
Use initializeOutlineFrame() instead of initializeOutlineFrame.

In the def initializeOutlineFrame(self, master), change all master into self.master.

Be careful ! width=80,height=30 doesn't define the size in pixels, but in characters. So at this stade, if you run the code, you are going to see a giant button and not the others buttons. Remove or change the values, for example like width=17,height=3.

[optional] You can grid buttons instead of pack for adding space around. It looks better:

def initializeOutlineFrame(self):

    self.convertImageButton = Button(self.master, text="Convert Image", \
    command=self.browseIMG, width=17, height=3)
    self.convertImageButton.grid(column=0, row=0, padx=10, pady=10)

    self.convertPdfButton = Button(self.master, text="Convert pdf", \
    command=self.browsePDF, width=17, height=3)
    self.convertPdfButton.grid(column=1, row=0, padx=10, pady=10)

    self.batchConvertButton = Button(self.master, text="Convert multiple files", \
    command=self.browseAllFiles, width=17, height=3)
    self.batchConvertButton.grid(column=2, row=0, padx=10, pady=10)


问:
Am i supposed to keep Sequelize models and migrations in sync?
I'm new to Sequelize.js and Databases in general, i haven't used migrations before, but i know that they can be used to make changes to the tables structure in a non-destructive way.

However i'm not sure where to declare column options (notNull, references, validate, ENUM values, etc...)

Should i declare such options in the the model file, or migration file? or both?

Wouldn't adding the options to both model and migration cause duplicate code?

(keep in mind that i'm talking about the initial migrations that create tables to the database, not the migrations that add columns and stuff...)

Any help would be appreciated!

答:
I see three options you can take. The first two options might be edge cases but it helps to understand.

Destructive option

You want to prototype a project and you don't mind losing your data, then you could potentially do not care about migration files and synchronize your database according to your model with:

await sequelize.sync({ force: true });
```
<p>It will execute on all your models:</p>
```DROP TABLE IF EXISTS "your_model" CASCADE;
CREATE TABLE IF NOT EXISTS "your_model" (...)
```
<p>This command can be executed at the start of your application for example.</p>
<hr />
<h2> Static option</h2>
<p>As you mentioned you don't want to add columns and stuff, it's probably a good option.</p>
<p>Now if you don't want to lose data, you could simply use the sync method without the force option:</p>
<pre class="lang-js prettyprint-override"><code>await sequelize.sync({ });
</code>```

It will only generate:

```<code>CREATE TABLE IF NOT EXISTS "your_model" (...)
</code>```

Hence, your tables are created according to your models and you don't have to create migration files.

However, if you want to modify your model and it's the most frequent usecase, the new column will not be generated in the table dynamically that's why you need migration scripts.

Flexible option

You will have to define both migration file and your model. That's what the cli does. Here is an example:

```<code># npx sequelize-cli init or create migrations and models folders
npx sequelize-cli model:generate --name User --attributes firstName:string,email:string
</code>```

Now you will have two more files:

// migrations/<date>-create-user.js
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      firstName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    // I usually remove this and create the table only if not exists
    return queryInterface.dropTable('Users');
  }
};
```
<pre class="lang-js prettyprint-override"><code>// models/users.js
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};
</code>```

You could refactor the code from the migration and the model, however it will be rather cumbersome because some migration files will only add one column, so merging all of them into the model might probably be less clear.

Body:
I see three options you can take. The first two options might be edge cases but it helps to understand.

Destructive option

You want to prototype a project and you don't mind losing your data, then you could potentially do not care about migration files and synchronize your database according to your model with:

await sequelize.sync({ force: true });

It will execute on all your models:

DROP TABLE IF EXISTS "your_model" CASCADE;
CREATE TABLE IF NOT EXISTS "your_model" (...)

This command can be executed at the start of your application for example.

 Static option

As you mentioned you don't want to add columns and stuff, it's probably a good option.

Now if you don't want to lose data, you could simply use the sync method without the force option:

await sequelize.sync({ });

It will only generate:

CREATE TABLE IF NOT EXISTS "your_model" (...)

Hence, your tables are created according to your models and you don't have to create migration files.

However, if you want to modify your model and it's the most frequent usecase, the new column will not be generated in the table dynamically that's why you need migration scripts.

Flexible option

You will have to define both migration file and your model. That's what the cli does. Here is an example:

# npx sequelize-cli init or create migrations and models folders
npx sequelize-cli model:generate --name User --attributes firstName:string,email:string

Now you will have two more files:

// migrations/<date>-create-user.js
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      firstName: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    // I usually remove this and create the table only if not exists
    return queryInterface.dropTable('Users');
  }
};

// models/users.js
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    email: DataTypes.STRING
  }, {});
  User.associate = function(models) {
    // associations can be defined here
  };
  return User;
};

You could refactor the code from the migration and the model, however it will be rather cumbersome because some migration files will only add one column, so merging all of them into the model might probably be less clear.


问:
how to filter an object with RegExp and return a new object
I have an object:

```<code>object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
bhsn: 7,
oki: 9
}

</code>```

My goal is to get a new object which contains only the keys with "dE", that means:

```<code>object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
}
</code>```

is the object that I expected.

What I have tried is,
firstly I got all key from this object with

```<code>Object.keys(object);
</code>```

and then I used a RegExp to check if properties in the object with relevant keys.
if not I use

```<code>delete object[key];
</code>```

Any solutions?

答:
You can just use Object.entries() to deconstruct the object, filter() it, and reconstruct it with Object.fromEntries():

const o = {
  dEabc: 1,
  dEasdf: 2,
  dEjfhs: 5,
  bhsn: 7,
  oki: 9
};

const result = Object.fromEntries(Object.entries(o).filter(([k]) => k.includes('dE')));

console.log(result);```

No need for a regex for an expression this simple.

Body:
I have an object:

object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
bhsn: 7,
oki: 9
}

My goal is to get a new object which contains only the keys with "dE", that means:

object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
}

is the object that I expected.

What I have tried is,
firstly I got all key from this object with

Object.keys(object);

and then I used a RegExp to check if properties in the object with relevant keys.
if not I use

delete object[key];

Any solutions?

Body:
You can just use Object.entries() to deconstruct the object, filter() it, and reconstruct it with Object.fromEntries():

const o = {
  dEabc: 1,
  dEasdf: 2,
  dEjfhs: 5,
  bhsn: 7,
  oki: 9
};

const result = Object.fromEntries(Object.entries(o).filter(([k]) => k.includes('dE')));

console.log(result);

No need for a regex for an expression this simple.


问:
How to jump back to the top of the code after if statement C language
I'm trying to make my program to start again from the beginning after user has selected an option from a menu.
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu What would you like to do? and not to just restart just the if statement.

Should I add a for loop inside of the if statement to accomplish this? thanks for the help.

```<code> printf("What would you like to do?\n");
    printf("      1 - Donate\n");
    printf("      2 - Invest\n");
    printf("      3 - Print balance\n");
    printf("      4 - Exit\n");
    printf("\n");

    //scans menu choice
    scanf("%d", &menu_option);

    if(menu_option==1)
    {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
    }
</code>```

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

int main()

{
 int menu_option;
 double donation;
 int donations_made = 0;
 int current_Balance = 0;
 int initial_Balance = 0;

 for (;;)
 {

    printf("What would you like to do?\n");
    printf("      1 - Donate\n");
    printf("      2 - Invest\n");
    printf("      3 - Print balance\n");
    printf("      4 - Exit\n");
    printf("\n");

    //scans menu choice
    scanf("%d", &menu_option);

            if (menu_option==1)
            {
                   printf("How much do you want to donate?\n");
                   scanf("%lf", &donation);
                   donations_made++;
                   current_Balance = initial_Balance + donation;
             }
        else if (menu_option == 4)
                 break;

   }
}
</code>```

Body:
I'm trying to make my program to start again from the beginning after user has selected an option from a menu.
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu What would you like to do? and not to just restart just the if statement.

Should I add a for loop inside of the if statement to accomplish this? thanks for the help.

 printf("What would you like to do?\n");
    printf("      1 - Donate\n");
    printf("      2 - Invest\n");
    printf("      3 - Print balance\n");
    printf("      4 - Exit\n");
    printf("\n");

    //scans menu choice
    scanf("%d", &menu_option);

    if(menu_option==1)
    {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
    }


问:
BizTalk Mapping
I need to convert the input XML to output as shown below

Input

```<code><root>
          <MOD_FACTOR>10</MOD_FACTOR>
          <X_MOD_FACTOR>20</X_MOD_FACTOR>
</root>

Ouput
------
<root>
          <Data>
                   <Name> MOD_FACTOR</Name>
                   <Value>10</Value>
          </Data>
<Data>
                    <Name>X_MOD_FACTOR</Name>
                   <Value>20</Value>
          </Data>
</root>
</code>```

What is the best way to do this?

答: You should look at the "Looping functoid" examples. They show a very similar problem.</p>

Title: BizTalk Mapping

Body:
I need to convert the input XML to output as shown below

Input

<root>
          <MOD_FACTOR>10</MOD_FACTOR>
          <X_MOD_FACTOR>20</X_MOD_FACTOR>
</root>

Ouput
------
<root>
          <Data>
                   <Name> MOD_FACTOR</Name>
                   <Value>10</Value>
          </Data>
<Data>
                    <Name>X_MOD_FACTOR</Name>
                   <Value>20</Value>
          </Data>
</root>

What is the best way to do this?


问:
Angular 8 Typescript How to set value of export const from another component?
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

```<code>var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];
</code>```

答:
I have another suggestion for this, you make your ts file injectable and create method to update the value of your variable and use that method in your another component to update the value.
 your service would look something like this.

```<code>@Injectable()
export class MyService {

 bdg_m_1 : string = '10';
 navItems: INavData[] = [
     {
        name: "Menu 1",
        url: "/menu_1",
        icon: "icon-speedometer",
        badge: {
          variant: 'info',
          text: bdg_m_1,
      }
   },
   ];
  constructor(){}
  setValue(value: string){
           this.bdg_m_1 = value;
     }
  getNavItems(){
  return this.navItems;
    }
   }
</code>```

And get instance of this service in your another component and call the method setValue to change the value of bdg_m_1.

So add following code in your component:

```<code>constructor(private myService: MyService){
   this.myService.setValue('abc');
  }
</code>```

Body:
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];

Body:
I have another suggestion for this, you make your ts file injectable and create method to update the value of your variable and use that method in your another component to update the value.
 your service would look something like this.

@Injectable()
export class MyService {

 bdg_m_1 : string = '10';
 navItems: INavData[] = [
     {
        name: "Menu 1",
        url: "/menu_1",
        icon: "icon-speedometer",
        badge: {
          variant: 'info',
          text: bdg_m_1,
      }
   },
   ];
  constructor(){}
  setValue(value: string){
           this.bdg_m_1 = value;
     }
  getNavItems(){
  return this.navItems;
    }
   }

And get instance of this service in your another component and call the method setValue to change the value of bdg_m_1.

So add following code in your component:

constructor(private myService: MyService){
   this.myService.setValue('abc');
  }


问:
localhost is currently unable to handle this request.HTTP ERROR 500
localhost is currently unable to handle this request.HTTP ERROR 500

PHP Fatal error:  Allowed memory size of 2147483648 bytes exhausted (tried to allocate 16384 bytes) in C:\xampp\htdocs\laravel\storage\framework\views\9ce6cdaa24325154033f80a71530d196495aafb3.php on line 2

答:
Unless you're intentionally working with multi-gigabyte data sets, you should not be exhausting 2 gigabytes of memory in a PHP script. While it's not ALWAYS a sign of unintended code execution, it USUALLY is.

Chances are you have some infinite loop or process that is just creating tons of data in memory. Look for while() loops in your code that create variables or append data to arrays or objects or append a string to a variable.

DO NOT just try to override the memory limit. That's like trying to deal with a serial killer by giving him more victims and hoping he runs out of steam.


问:
IntelliJ: Error:java: error: release version 5 not supported
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

```<code>Error:java: error: release version 5 not supported
</code>```

Running java --version by terminal I get the following output:

```<code>openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)
</code>```

Running javac --version by terminal I get the following output:

```<code>javac 11.0.5
</code>```

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

```<code>Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype
</code>```

Changing it to version 1.11 I get this error instead:

```<code>Error:java: Source option 5 is no longer supported. Use 6 or later.
</code>```

What do you think is the problem? How may I solve it?

答:
By default, your "Project bytecode version isn't set in maven project.

It thinks that your current version is 5.

Solution 1:

Just go to "Project Settings>Build, Execution...>compiler>java compiler" and then change your bytecode version to your current java version.

Solution 2:

Adding below build plugin in POM file:

 <properties>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
```

Body:
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

Error:java: error: release version 5 not supported

Running java --version by terminal I get the following output:

openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)

Running javac --version by terminal I get the following output:

javac 11.0.5

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype

Changing it to version 1.11 I get this error instead:

Error:java: Source option 5 is no longer supported. Use 6 or later.

What do you think is the problem? How may I solve it?


问:
How to run Tasks such that the last one started (not completed) wins?
I'm trying to implement a responsive search text box, where the search results are updated as the user types in the search text. I'm trying to do this using Tasks, but I'm finding that sometimes a previous search finishes after a later search, thereby replacing the new results with old results.

One quick fix is to delay starting the search after the user has stopped typing for half a second or so. However, I think this only hides the problem. I'd like to find a general solution.

So far, I've come up with the following class:

```<code>public class LastAddedTaskStrategy<T>
{
    private DateTime latest;

    public T Result { get; private set; }

    public async Task Add(Task<T> t)
    {
        var timestamp = DateTime.Now;
        latest = timestamp;

        var currentResult = await t;

        if (timestamp >= latest)
            Result = currentResult;
    }
}
</code>```

The idea is that you can add (and await) as many Tasks as you want (e.g., searches), but only the results of the last added (not last completed) Task wins. So if a previous search finishes after a later search, the Results property won't be updated because it's an old result.

Is this a good solution or is there something better?

答:
Here is an extension method for System.Windows.Forms controls, that subscribes to their TextChanged event. Every time the event is fired an asynchronous method is invoked, and the result of this method is propagated to a handler. The result is propagated only under the condition that the asynchronous method will not be preempted before its completion.

```<code>public static void OnTextChangedExecute<TResult>(this Control control,
    Func<CancellationToken, Task<TResult>> function,
    Action<TResult> handler)
{
    CancellationTokenSource activeCTS = null;
    control.TextChanged += Event_Handler;

    async void Event_Handler(object sender, EventArgs args)
    {
        activeCTS?.Cancel();
        TResult result;
        using (var cts = new CancellationTokenSource())
        {
            activeCTS = cts;
            try
            {
                result = await function(cts.Token);
                cts.Token.ThrowIfCancellationRequested();
            }
            catch (OperationCanceledException)
                when (cts.Token.IsCancellationRequested)
            {
                return; // Preempted, don't invoke the handler.
            }
            finally
            {
                if (activeCTS == cts) activeCTS = null;
            }
        }
        handler(result);
    }
}
</code>```

Usage example:

```<code>public Form1()
{
    InitializeComponent();
    TextBox1.OnTextChangedExecute(
        ct => SearchAsync(TextBox1.Text, ct), TextBox1_SearchCompleted);
}

async Task<int> SearchAsync(string text, CancellationToken token)
{
    await Task.Delay(1000, token); // Simulate some cancelable I/O operation
    return Int32.Parse(text);
}

void TextBox1_SearchCompleted(int result)
{
    MessageBox.Show($"Result: {result}");
}
</code>```

The OnTextChangedExecute method is not thread-safe. It is intended to be called from the UI thread only. It depends on the existence
of a WindowsFormsSynchronizationContext to work properly.

Body:
I'm trying to implement a responsive search text box, where the search results are updated as the user types in the search text. I'm trying to do this using Tasks, but I'm finding that sometimes a previous search finishes after a later search, thereby replacing the new results with old results.

One quick fix is to delay starting the search after the user has stopped typing for half a second or so. However, I think this only hides the problem. I'd like to find a general solution.

So far, I've come up with the following class:

public class LastAddedTaskStrategy<T>
{
    private DateTime latest;

    public T Result { get; private set; }

    public async Task Add(Task<T> t)
    {
        var timestamp = DateTime.Now;
        latest = timestamp;

        var currentResult = await t;

        if (timestamp >= latest)
            Result = currentResult;
    }
}

The idea is that you can add (and await) as many Tasks as you want (e.g., searches), but only the results of the last added (not last completed) Task wins. So if a previous search finishes after a later search, the Results property won't be updated because it's an old result.

Is this a good solution or is there something better?

Body:
Here is an extension method for System.Windows.Forms controls, that subscribes to their TextChanged event. Every time the event is fired an asynchronous method is invoked, and the result of this method is propagated to a handler. The result is propagated only under the condition that the asynchronous method will not be preempted before its completion.

public static void OnTextChangedExecute<TResult>(this Control control,
    Func<CancellationToken, Task<TResult>> function,
    Action<TResult> handler)
{
    CancellationTokenSource activeCTS = null;
    control.TextChanged += Event_Handler;

    async void Event_Handler(object sender, EventArgs args)
    {
        activeCTS?.Cancel();
        TResult result;
        using (var cts = new CancellationTokenSource())
        {
            activeCTS = cts;
            try
            {
                result = await function(cts.Token);
                cts.Token.ThrowIfCancellationRequested();
            }
            catch (OperationCanceledException)
                when (cts.Token.IsCancellationRequested)
            {
                return; // Preempted, don't invoke the handler.
            }
            finally
            {
                if (activeCTS == cts) activeCTS = null;
            }
        }
        handler(result);
    }
}

Usage example:

public Form1()
{
    InitializeComponent();
    TextBox1.OnTextChangedExecute(
        ct => SearchAsync(TextBox1.Text, ct), TextBox1_SearchCompleted);
}

async Task<int> SearchAsync(string text, CancellationToken token)
{
    await Task.Delay(1000, token); // Simulate some cancelable I/O operation
    return Int32.Parse(text);
}

void TextBox1_SearchCompleted(int result)
{
    MessageBox.Show($"Result: {result}");
}

The OnTextChangedExecute method is not thread-safe. It is intended to be called from the UI thread only. It depends on the existence
of a WindowsFormsSynchronizationContext to work properly.


问:
Prevent open in new tab/window
I have a website that has a music player in one of the corners. Because I didn't want the music to stop everytime the user changes part of the website, I used an iFrame for the content. So when someone clicks the menu buttons, all that changes is the source of the iFrame.

Now the only problem is if someone tries to open one of the sub-pages in a new tab/window. All they get is black text on a white background, with the content that was supposed to be in the iFrame.

Is there any way to prevent this?

Oh, and the page this is about is www.sinjabe.com  if that helps.

Thanks

答:
Put this on your sub pages:

```<code><script type="text/javascript">
    if (window.location == window.parent.location)
    this.window.location = 'main_site.html';
</script>
</code>```

-- Give credit for this one @George Cummins for writting such a short conditional statment :)

This will redirect any direct incomming trafic on your subpages to your main page. I must warn you though, that iframes for displaying such content are highly SEO unefficient, and URL useless in terms of history mapping (back button will not work) and link sharing, because the main URL doesn't change while you click on menu buttons.

Title: Prevent open in new tab/window

Body:
Put this on your sub pages:

<script type="text/javascript">
    if (window.location == window.parent.location)
    this.window.location = 'main_site.html';
</script>

-- Give credit for this one @George Cummins for writting such a short conditional statment :)

This will redirect any direct incomming trafic on your subpages to your main page. I must warn you though, that iframes for displaying such content are highly SEO unefficient, and URL useless in terms of history mapping (back button will not work) and link sharing, because the main URL doesn't change while you click on menu buttons.


问:
How do I call a
 id inside of a div?
So I'm trying to create a Message of the Day.
DIV code

```<code><div class="motd" id="shadowbox">
    <h4 class="rainbow_text_animated" style="text-align: center;" >Message of the Day</h4>
    <p id="MOTDText" style="text-align: center;">nil</p>
    </div>
</code>```

Script

```<code> function motdupdate() {
    var dailymessages = ["message1", "message2", "message3", "message4", "message5", "message6", "message7"]
    var today = new Date();
    if (today.getDay() == 0 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[0];
    else if (today.getDay() == 1 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[1];
    else if (today.getDay() == 2 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[2];
    else if (today.getDay() == 3 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[3];
    else if (today.getDay() == 4 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[4];
    else if (today.getDay() == 5 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[5];
    else if (today.getDay() == 6 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[6];
 }
</code>```

The problem is, it keeps giving me this error:

```<code>index.html:59 Uncaught ReferenceError: motd is not defined
    at motdupdate (index.html:59)
    at <anonymous>:1:1
</code>```

How do I fix this?

答:
```<code>getElementById(motd.MOTDText)
</code>```

should be

```<code>getElementById("MOTDText").innerHTML = dailymessages[6];
</code>```

They all should be changed to this for it to work.

Title: How do I call a <p> id inside of a div?

Body:
So I'm trying to create a Message of the Day.
DIV code

Message of the Day

nil

Script

 function motdupdate() {
    var dailymessages = ["message1", "message2", "message3", "message4", "message5", "message6", "message7"]
    var today = new Date();
    if (today.getDay() == 0 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[0];
    else if (today.getDay() == 1 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[1];
    else if (today.getDay() == 2 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[2];
    else if (today.getDay() == 3 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[3];
    else if (today.getDay() == 4 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[4];
    else if (today.getDay() == 5 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[5];
    else if (today.getDay() == 6 ) document.getElementById(motd.MOTDText).innerHTML = dailymessages[6];
 }

The problem is, it keeps giving me this error:

index.html:59 Uncaught ReferenceError: motd is not defined
    at motdupdate (index.html:59)
    at <anonymous>:1:1

How do I fix this?

Body:
getElementById(motd.MOTDText)

should be

getElementById("MOTDText").innerHTML = dailymessages[6];

They all should be changed to this for it to work.


问:
How to properly build keycloak from source code
I need to build a custom version of Keycloak in order to perform another action when password reset happens.
In order to do this, I followed the steps described in the Readme file on the git repository:

Check java version, maven version, git version (openjdk 11, amazon corretto, maven 3.6.3)

Run "git clone https://github.com/keycloak/keycloak.git"

Switch to the newly created directory

Run "mvn install"

Some tests failed in module keycloak-saml-core:

```<code>org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest
[ERROR] testSaml20AuthnResponseNonAsciiNameDefaultLatin2(org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest)  Time elapsed: 0.008 s  <<< ERROR!
ParsingException [location=null]org.keycloak.saml.common.exceptions.ParsingException: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[9,91]
Message: Invalid byte 2 of 3-byte UTF-8 sequence.
    at org.keycloak.saml.common.DefaultPicketLinkLogger.parserException(DefaultPicketLinkLogger.java:420)
    at org.keycloak.saml.common.util.StaxParserUtil.getElementText(StaxParserUtil.java:492)
    at org.keycloak.saml.processing.core.parsers.util.SAMLParserUtil.parseNameIDType(SAMLParserUtil.java:57)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLSubjectParser.processSubElement(SAMLSubjectParser.java:58)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLSubjectParser.processSubElement(SAMLSubjectParser.java:36)
    at org.keycloak.saml.common.parsers.AbstractStaxParser.parse(AbstractStaxParser.java:97)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLAssertionParser.processSubElement(SAMLAssertionParser.java:69)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLAssertionParser.processSubElement(SAMLAssertionParser.java:34)
    at org.keycloak.saml.common.parsers.AbstractStaxParser.parse(AbstractStaxParser.java:97)
    at org.keycloak.saml.processing.core.parsers.saml.protocol.SAMLResponseParser.processSubElement(SAMLResponseParser.java:77)
    at org.keycloak.saml.processing.core.parsers.saml.protocol.SAMLResponseParser.processSubElement(SAMLResponseParser.java:38)
    at org.keycloak.saml.common.parsers.AbstractStaxParser.parse(AbstractStaxParser.java:97)
    at org.keycloak.saml.processing.core.parsers.saml.SAMLParser.parse(SAMLParser.java:123)
    at org.keycloak.saml.common.parsers.AbstractParser.parse(AbstractParser.java:98)
    at org.keycloak.saml.common.parsers.AbstractParser.parse(AbstractParser.java:102)
    at org.keycloak.saml.processing.api.saml.v2.response.SAML2Response.getSAML2ObjectFromStream(SAML2Response.java:389)
    at org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest.assertParsed(SAMLParserTest.java:141)
    at org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest.testSaml20AuthnResponseNonAsciiNameDefaultLatin2(SAMLParserTest.java:262)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[9,91]
Message: Invalid byte 2 of 3-byte UTF-8 sequence.
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:652)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.getElementText(XMLStreamReaderImpl.java:902)
    at java.xml/com.sun.xml.internal.stream.XMLEventReaderImpl.getElementText(XMLEventReaderImpl.java:187)
    at java.xml/javax.xml.stream.util.EventReaderDelegate.getElementText(EventReaderDelegate.java:110)
    at org.keycloak.saml.common.util.StaxParserUtil.getElementText(StaxParserUtil.java:490)
    ... 44 more
</code>```

After this, I tried running the project directly from Intellij, but received the following error:

```<code>org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat.class]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/keycloak/adapters/tomcat/KeycloakAuthenticatorValve
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:139) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536) ~[spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.keycloak.SpringBootAdapterApplication.main(SpringBootAdapterApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat.class]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/keycloak/adapters/tomcat/KeycloakAuthenticatorValve
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:201) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:164) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:136) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    ... 8 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/keycloak/adapters/tomcat/KeycloakAuthenticatorValve
    at org.keycloak.adapters.springboot.KeycloakAutoConfiguration$1.customize(KeycloakAutoConfiguration.java:59) ~[classes/:na]
    at org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizerBeanPostProcessor.postProcessBeforeInitialization(EmbeddedServletContainerCustomizerBeanPostProcessor.java:73) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizerBeanPostProcessor.postProcessBeforeInitialization(EmbeddedServletContainerCustomizerBeanPostProcessor.java:59) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1622) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    ... 16 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.keycloak.adapters.tomcat.KeycloakAuthenticatorValve
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_191]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_191]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[na:1.8.0_191]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_191]
    ... 22 common frames omitted

Process finished with exit code 1
</code>```

I also tried skipping the tests with mvn install -DskipTests and the build succeeded, but I am not aware of the location of the newly created jar file containing the result of the build.
Also, changing java version from 11 to 8 did not seem to affect the errors that would occur.
Switching to a fresh linux virtual machine did not really affect things, but tests would still fail for some unknown/unspecified reason, but in the test suites, not in the saml package.

Please note that this is the version as-is from the repository, with no changes done by me.

答:
I found a maven command that reliably solves this issue for me:</p>

```<code>mvn clean install -Pdistribution -DskipTests
</code>```

Body:
I need to build a custom version of Keycloak in order to perform another action when password reset happens.
In order to do this, I followed the steps described in the Readme file on the git repository:

Check java version, maven version, git version (openjdk 11, amazon corretto, maven 3.6.3)

Run "git clone https://github.com/keycloak/keycloak.git"

Switch to the newly created directory

Run "mvn install"

Some tests failed in module keycloak-saml-core:

org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest
[ERROR] testSaml20AuthnResponseNonAsciiNameDefaultLatin2(org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest)  Time elapsed: 0.008 s  <<< ERROR!
ParsingException [location=null]org.keycloak.saml.common.exceptions.ParsingException: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[9,91]
Message: Invalid byte 2 of 3-byte UTF-8 sequence.
    at org.keycloak.saml.common.DefaultPicketLinkLogger.parserException(DefaultPicketLinkLogger.java:420)
    at org.keycloak.saml.common.util.StaxParserUtil.getElementText(StaxParserUtil.java:492)
    at org.keycloak.saml.processing.core.parsers.util.SAMLParserUtil.parseNameIDType(SAMLParserUtil.java:57)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLSubjectParser.processSubElement(SAMLSubjectParser.java:58)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLSubjectParser.processSubElement(SAMLSubjectParser.java:36)
    at org.keycloak.saml.common.parsers.AbstractStaxParser.parse(AbstractStaxParser.java:97)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLAssertionParser.processSubElement(SAMLAssertionParser.java:69)
    at org.keycloak.saml.processing.core.parsers.saml.assertion.SAMLAssertionParser.processSubElement(SAMLAssertionParser.java:34)
    at org.keycloak.saml.common.parsers.AbstractStaxParser.parse(AbstractStaxParser.java:97)
    at org.keycloak.saml.processing.core.parsers.saml.protocol.SAMLResponseParser.processSubElement(SAMLResponseParser.java:77)
    at org.keycloak.saml.processing.core.parsers.saml.protocol.SAMLResponseParser.processSubElement(SAMLResponseParser.java:38)
    at org.keycloak.saml.common.parsers.AbstractStaxParser.parse(AbstractStaxParser.java:97)
    at org.keycloak.saml.processing.core.parsers.saml.SAMLParser.parse(SAMLParser.java:123)
    at org.keycloak.saml.common.parsers.AbstractParser.parse(AbstractParser.java:98)
    at org.keycloak.saml.common.parsers.AbstractParser.parse(AbstractParser.java:102)
    at org.keycloak.saml.processing.api.saml.v2.response.SAML2Response.getSAML2ObjectFromStream(SAML2Response.java:389)
    at org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest.assertParsed(SAMLParserTest.java:141)
    at org.keycloak.saml.processing.core.parsers.saml.SAMLParserTest.testSaml20AuthnResponseNonAsciiNameDefaultLatin2(SAMLParserTest.java:262)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:365)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:273)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:238)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:159)
    at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:383)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:344)
    at org.apache.maven.surefire.booter.ForkedBooter.execute(ForkedBooter.java:125)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:417)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[9,91]
Message: Invalid byte 2 of 3-byte UTF-8 sequence.
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:652)
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.getElementText(XMLStreamReaderImpl.java:902)
    at java.xml/com.sun.xml.internal.stream.XMLEventReaderImpl.getElementText(XMLEventReaderImpl.java:187)
    at java.xml/javax.xml.stream.util.EventReaderDelegate.getElementText(EventReaderDelegate.java:110)
    at org.keycloak.saml.common.util.StaxParserUtil.getElementText(StaxParserUtil.java:490)
    ... 44 more

After this, I tried running the project directly from Intellij, but received the following error:

org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat.class]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/keycloak/adapters/tomcat/KeycloakAuthenticatorValve
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:139) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:536) ~[spring-context-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1118) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1107) [spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.keycloak.SpringBootAdapterApplication.main(SpringBootAdapterApplication.java:10) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tomcatEmbeddedServletContainerFactory' defined in class path resource [org/springframework/boot/autoconfigure/web/EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat.class]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/keycloak/adapters/tomcat/KeycloakAuthenticatorValve
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:562) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:481) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:201) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:164) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:136) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    ... 8 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/keycloak/adapters/tomcat/KeycloakAuthenticatorValve
    at org.keycloak.adapters.springboot.KeycloakAutoConfiguration$1.customize(KeycloakAutoConfiguration.java:59) ~[classes/:na]
    at org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizerBeanPostProcessor.postProcessBeforeInitialization(EmbeddedServletContainerCustomizerBeanPostProcessor.java:73) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizerBeanPostProcessor.postProcessBeforeInitialization(EmbeddedServletContainerCustomizerBeanPostProcessor.java:59) ~[spring-boot-1.5.20.RELEASE.jar:1.5.20.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:407) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1622) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) ~[spring-beans-4.3.23.RELEASE.jar:4.3.23.RELEASE]
    ... 16 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.keycloak.adapters.tomcat.KeycloakAuthenticatorValve
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382) ~[na:1.8.0_191]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_191]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[na:1.8.0_191]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_191]
    ... 22 common frames omitted

Process finished with exit code 1

I also tried skipping the tests with mvn install -DskipTests and the build succeeded, but I am not aware of the location of the newly created jar file containing the result of the build.
Also, changing java version from 11 to 8 did not seem to affect the errors that would occur.
Switching to a fresh linux virtual machine did not really affect things, but tests would still fail for some unknown/unspecified reason, but in the test suites, not in the saml package.

Please note that this is the version as-is from the repository, with no changes done by me.

Body:
I found a maven command that reliably solves this issue for me:

mvn clean install -Pdistribution -DskipTests


问:
Concatenate dataframes while making sure boolean value is not converted into integer
I have df1 and df2 that I want to combine into one dataframe in a for loop. The 2 dataframes are identical
df1 looks like this

```<code>id booleanValue
0     True
1     False
</code>```

df2 looks like this

```<code>id booleanValue
2     True
3     np.nan
</code>```

I did

```<code>total_df = pd.Dataframe()
total_df = pd.concat([total_df, df1], ignore_index=True, sort=False)
</code>```

I was hoping to get

```<code>id booleanValue
0     True
1     False
2     True
3     NaN
</code>```

but I got

```<code>id booleanValue
0     0.0
1     1.0
2     0.0
3     0.0
</code>```

Is there a way to concatenate so that boolean value doesn't get converted into integer and np.nan will remain as np.nan?

答:
Your solution working nice, only is necessary upgrade pandas, because Nullable Boolean Data Type working from pandas 1.0.0+:

```<code>df1['booleanValue'] = df1['booleanValue'].astype('boolean')
df2['booleanValue'] = df2['booleanValue'].astype('boolean')

total_df = pd.concat([df1, df2], ignore_index=True, sort=False)
print (total_df.dtypes)
id                int64
booleanValue    boolean
dtype: object

print (total_df)
   id  booleanValue
0   0          True
1   1         False
2   2          True
3   3          <NA>
</code>```

Solution if not convert to boolean - get object dtype:

```<code>total_df = pd.concat([df1, df2], ignore_index=True, sort=False)
print (total_df)
   id booleanValue
0   0         True
1   1        False
2   2         True
3   3          NaN

print (total_df.dtypes)
id               int64
booleanValue    object
dtype: object
</code>```

Body:
I have df1 and df2 that I want to combine into one dataframe in a for loop. The 2 dataframes are identical
df1 looks like this

id booleanValue
0     True
1     False

df2 looks like this

id booleanValue
2     True
3     np.nan

I did

total_df = pd.Dataframe()
total_df = pd.concat([total_df, df1], ignore_index=True, sort=False)

I was hoping to get

id booleanValue
0     True
1     False
2     True
3     NaN

but I got

id booleanValue
0     0.0
1     1.0
2     0.0
3     0.0

Is there a way to concatenate so that boolean value doesn't get converted into integer and np.nan will remain as np.nan?

Body:
Your solution working nice, only is necessary upgrade pandas, because Nullable Boolean Data Type working from pandas 1.0.0+:

df1['booleanValue'] = df1['booleanValue'].astype('boolean')
df2['booleanValue'] = df2['booleanValue'].astype('boolean')

total_df = pd.concat([df1, df2], ignore_index=True, sort=False)
print (total_df.dtypes)
id                int64
booleanValue    boolean
dtype: object

print (total_df)
   id  booleanValue
0   0          True
1   1         False
2   2          True
3   3          <NA>

Solution if not convert to boolean - get object dtype:

total_df = pd.concat([df1, df2], ignore_index=True, sort=False)
print (total_df)
   id booleanValue
0   0         True
1   1        False
2   2         True
3   3          NaN

print (total_df.dtypes)
id               int64
booleanValue    object
dtype: object


答:
First of all i think today.getDay() will never be equal to 0.
I do not understand why you want to call like that because in common ids must be unique so you may not depend on div.
Try it like this:</p>

```<code>function motdupdate() {
    var dailymessages = ["message1", "message2", "message3", "message4", "message5", "message6", "message7"]
    var today = new Date();
     document.getElementById("MOTDText").innerHTML = dailymessages[ parseInt(today.getDay() - 1)];
 }
</code>```

Title: How do I call a <p> id inside of a div?

Body:
First of all i think today.getDay() will never be equal to 0.
I do not understand why you want to call like that because in common ids must be unique so you may not depend on div.
Try it like this:

function motdupdate() {
    var dailymessages = ["message1", "message2", "message3", "message4", "message5", "message6", "message7"]
    var today = new Date();
     document.getElementById("MOTDText").innerHTML = dailymessages[ parseInt(today.getDay() - 1)];
 }