问:
Google Apps Script to Microsoft SQL Server clarification of whitelist certain IP ranges in database settings
Clarification of Google instructions for setting up Jdbc.getConnection to Microsoft SQL Server it says:

In order to create a database connection using the JDBC service you must whitelist certain IP ranges in your database settings to allow Apps Script to access it.

My database is on a server that also has other databases. I've looked all through the database settings of the database I created using (SQL Server Management Studio) where I built the database. I asked the database person they told me "the server is set to allow remote connections" and I can see in the database properties under Connections the checkbox is checked for "Allow remote connections to this server" - that does not seem to make a difference. When I run my code - it does not error and it does not connect - it tells me either my connection string or login/password is incorrect. I reviewed the instructions and googled that message and number of folks also mentioned seeing the same message and they said they had to add the list of whitelist IPs per the Google instructions.

These are the address ranges you'll need to whitelist:

```<code>64.18.0.0 - 64.18.15.255
64.233.160.0 - 64.233.191.255
66.102.0.0 - 66.102.15.255
66.249.80.0 - 66.249.95.255
72.14.192.0 - 72.14.255.255
74.125.0.0 - 74.125.255.255
173.194.0.0 - 173.194.255.255
207.126.144.0 - 207.126.159.255
209.85.128.0 - 209.85.255.255
216.239.32.0 - 216.239.63.255
</code>```

I've looked at every single property in the database nothing says "IP" or "address" is this a permissions issue or something that is accessed from a menu I don't have access to?

Could you please share with me where this "database whitelist" is to be entered for the database?

When I find it, will I be able to whitelist (allow access) the list of IPs above without causing an issue to any other databases on the server? I'm not sure if a shared server would be different than a dedicated server.

Also, I have asked and the network people tell me these IPs are not being blocked, but the Google instructions specifically say database settings, so I suspect Google is expecting something pretty specific to be set up.

Lastly, when I remote desktop to the database server I am not able to locate any kind of "Administrative Tools" menu to search under that.

Thanks for bearing with all the "newbie" questions.

For reference this is working code per the solution below.

```<code>function myFunction() {

var address = 'IPaddress\\instance';
var user = 'UserName';
var userPwd = 'ItsASecret';
var queryDb = 'DatabaseName';
var dbUrl = 'jdbc:sqlserver://' + address + ':1433;databaseName=' + queryDb;

var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var start = new Date();
var stmt = conn.createStatement();

stmt.setMaxRows(100);
var results = stmt.executeQuery("select * from dbo.tablename");

var sheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetTab = sheet.getSheetByName('Sheet1');
var cell = sheetTab.getRange('A1');
var numCols = results.getMetaData().getColumnCount();
var numRows = sheetTab.getLastRow();
var headers ;
var row =0;

for(var i = 1; i <= numCols; i++){
  headers = results.getMetaData().getColumnName(i);
    cell.offset(row, i-1).setValue(headers);
    }

while (results.next()) {
  var rowString = '';
  for (var col = 0; col < numCols; col++) {
    rowString += results.getString(col + 1) + '\t';
    cell.offset(row +1, col).setValue(results.getString(col +1 ));
  }
  row++
  Logger.log(rowString)
}

results.close();
stmt.close();
conn.close();
}
</code>```

答:
As it turns out after getting a different network person involved the port was not active on the server - even though the settings in the server itself looked like the port was set up to be used.

```<code>var dbUrl = 'jdbc:sqlserver://' + address + ':1433;databaseName=' + queryDb;
</code>```

This command (I ran it from a PowerShell command prompt) is very helpful for checking that detail out:

```<code>Test-NetConnection -Port 800 -ComputerName 1xx.1xx.0.1 -InformationLevel Detailed
</code>```

I want to also point out in my situation. I did not have to whitelist anything. Once the network person set up the address to use for the external connection and the port issue was resolved - (the port also had to be set to dedicated) everything flowed right through.

Body:
Clarification of Google instructions for setting up Jdbc.getConnection to Microsoft SQL Server it says:

In order to create a database connection using the JDBC service you must whitelist certain IP ranges in your database settings to allow Apps Script to access it.

My database is on a server that also has other databases. I've looked all through the database settings of the database I created using (SQL Server Management Studio) where I built the database. I asked the database person they told me "the server is set to allow remote connections" and I can see in the database properties under Connections the checkbox is checked for "Allow remote connections to this server" - that does not seem to make a difference. When I run my code - it does not error and it does not connect - it tells me either my connection string or login/password is incorrect. I reviewed the instructions and googled that message and number of folks also mentioned seeing the same message and they said they had to add the list of whitelist IPs per the Google instructions.

These are the address ranges you'll need to whitelist:

64.18.0.0 - 64.18.15.255
64.233.160.0 - 64.233.191.255
66.102.0.0 - 66.102.15.255
66.249.80.0 - 66.249.95.255
72.14.192.0 - 72.14.255.255
74.125.0.0 - 74.125.255.255
173.194.0.0 - 173.194.255.255
207.126.144.0 - 207.126.159.255
209.85.128.0 - 209.85.255.255
216.239.32.0 - 216.239.63.255

I've looked at every single property in the database nothing says "IP" or "address" is this a permissions issue or something that is accessed from a menu I don't have access to?

Could you please share with me where this "database whitelist" is to be entered for the database?

When I find it, will I be able to whitelist (allow access) the list of IPs above without causing an issue to any other databases on the server? I'm not sure if a shared server would be different than a dedicated server.

Also, I have asked and the network people tell me these IPs are not being blocked, but the Google instructions specifically say database settings, so I suspect Google is expecting something pretty specific to be set up.

Lastly, when I remote desktop to the database server I am not able to locate any kind of "Administrative Tools" menu to search under that.

Thanks for bearing with all the "newbie" questions.

For reference this is working code per the solution below.

function myFunction() {

var address = 'IPaddress\\instance';
var user = 'UserName';
var userPwd = 'ItsASecret';
var queryDb = 'DatabaseName';
var dbUrl = 'jdbc:sqlserver://' + address + ':1433;databaseName=' + queryDb;

var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var start = new Date();
var stmt = conn.createStatement();

stmt.setMaxRows(100);
var results = stmt.executeQuery("select * from dbo.tablename");

var sheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetTab = sheet.getSheetByName('Sheet1');
var cell = sheetTab.getRange('A1');
var numCols = results.getMetaData().getColumnCount();
var numRows = sheetTab.getLastRow();
var headers ;
var row =0;

for(var i = 1; i <= numCols; i++){
  headers = results.getMetaData().getColumnName(i);
    cell.offset(row, i-1).setValue(headers);
    }

while (results.next()) {
  var rowString = '';
  for (var col = 0; col < numCols; col++) {
    rowString += results.getString(col + 1) + '\t';
    cell.offset(row +1, col).setValue(results.getString(col +1 ));
  }
  row++
  Logger.log(rowString)
}

results.close();
stmt.close();
conn.close();
}

Body:
As it turns out after getting a different network person involved the port was not active on the server - even though the settings in the server itself looked like the port was set up to be used.

var dbUrl = 'jdbc:sqlserver://' + address + ':1433;databaseName=' + queryDb;

This command (I ran it from a PowerShell command prompt) is very helpful for checking that detail out:

Test-NetConnection -Port 800 -ComputerName 1xx.1xx.0.1 -InformationLevel Detailed

I want to also point out in my situation. I did not have to whitelist anything. Once the network person set up the address to use for the external connection and the port issue was resolved - (the port also had to be set to dedicated) everything flowed right through.


来源: stackexchange

问:
Problems with i18next language detection and integration with hapi
I'm trying to write a new language detector plugin for i18next for integration with hapi.  There's an existing hapi-i18next plugin that is quite old (it uses an extemely old version of i18next, 1.7.10 ) and so mostly useless. And the i18next API docs are pretty vague about how to write new plugins and exactly what the language detection process is.  Does it run every time the t() function runs? should it be asynchronous?  Has anybody else out there recently integrated hapi with i18next? I realize this is rather general but i'm not sure where else to turn.</p>

答: What I ended up doing is writing a hapi server extension rather than a plugin, and a module that runs at startup that decorates the hapi server object with the initialized i18next object.  The extension is installed to run onPreHandler and it basically clones the i18next object, attaches that instance to the request object, and detects the language (from the request header or from a query parameter), then sets the cloned instance to that language.  This way, whenever a route handler uses the t() function attached to the instance that's attached to the current request, we know we'll be translating into the right language.  Note that this is still for Hapi 16 (I need to port to 17/18 soon)...

ContentLicense: CC BY-SA 4.0


问:
Crystal Reports - "The report you requested requires further information"
I have some Crystal Reports that were created using Crystal (external to Visual Studio) and are now loaded in the VS project. Before the report is previewed I set up the report database information like this in the report and all subreports.

```<code>        var connectionInfo = new ConnectionInfo();
        connectionInfo.ServerName = "192.168.x.xxx";
        connectionInfo.DatabaseName = "xxxx";
        connectionInfo.Password = "xxxx";
        connectionInfo.UserID = "xxxx";
        connectionInfo.Type = ConnectionInfoType.SQL;
        connectionInfo.IntegratedSecurity = false;

        TableLogOnInfo logon = table.LogOnInfo;
        table.LogOnInfo.ConnectionInfo = connectionInfo;
        table.ApplyLogOnInfo(logon);
</code>```

The report displays correctly when it is initially previewed but when I go to the next page in the report preview I get the message, "The report you requested requires further information" and are prompted for the database login information again. Once I have entered it here I am no longer prompted. It appears that the initial ConnectionInfo I set up is not sticking past the first page.

I am using Crystal XI and Visual Studio 2008.

答:
The future is nigh but Crystal Reports persists.

I was receiving this "error" from our crystal reports viewer.  My problem was a dynamically generated query that was being created with consecutive ORs.  The invalid SQL somehow elevated this "The report you requested requires further information" dialog box.

I fixed the query generation logic and do not see the dialog box anymore.

ContentLicense: CC BY-SA 2.5

Body:
I have some Crystal Reports that were created using Crystal (external to Visual Studio) and are now loaded in the VS project. Before the report is previewed I set up the report database information like this in the report and all subreports.

        var connectionInfo = new ConnectionInfo();
        connectionInfo.ServerName = "192.168.x.xxx";
        connectionInfo.DatabaseName = "xxxx";
        connectionInfo.Password = "xxxx";
        connectionInfo.UserID = "xxxx";
        connectionInfo.Type = ConnectionInfoType.SQL;
        connectionInfo.IntegratedSecurity = false;

        TableLogOnInfo logon = table.LogOnInfo;
        table.LogOnInfo.ConnectionInfo = connectionInfo;
        table.ApplyLogOnInfo(logon);

The report displays correctly when it is initially previewed but when I go to the next page in the report preview I get the message, "The report you requested requires further information" and are prompted for the database login information again. Once I have entered it here I am no longer prompted. It appears that the initial ConnectionInfo I set up is not sticking past the first page.

I am using Crystal XI and Visual Studio 2008.


问:
Does adal4j-1.6.2.jar supported by Java 11 or not
I am going to use the following jar in development of a product:

adal4j-1.6.2.jar

I am using java 11 for product development.

I just want to confirm, whether above mentioned jar is supported in JAVA 11 or not.

Thanks,
Ravi

Searched for Jar support on google

答: MSAL4J, which is the new client MS Identity client library for Java, and has all ADAL4J features and more, does support Java 11. You can get find it on Maven or on GitHub</p>


问:
Express not doing anything but sending HTML file
I'm using an app.post method in Express like so:

```<code>app.post('/race', function(req,res) {
  let raceResponse = {
    user_name: req.body.userName
  }
  console.log('Express has received race.');

  //Socket.IO
  let race = io.of('/race').on('connection', (socket) => {
    console.log('A user has entered the race!');
    socket.on('racePageReady', function() {
      console.log('race page ready recieved');
      socket.emit('racePageInfo', raceResponse);
    });

    socket.on('createRoom', function(roomName) {
      socket.join(roomName);
      let clients = io.sockets.adapter.rooms[roomName].sockets;
      console.log("A room with the name " + roomName + "was created.");
      console.log(clients);
      socket.emit('roomCreated', clients);
    });

    socket.on('joinRoom', function(roomName) {
      socket.join(roomName);
      let clients = io.sockets.adapter.rooms[roomName].sockets;
      console.log('A user joined the room with the name: ' + roomName + ". The user's name is " + raceResponse.user_name);
      console.log(clients);
      socket.emit('roomCreated', clients);
    });
  });

  res.sendFile(path.join(__dirname, '/client/race/index.html'));
}
</code>```

The page is being sent fine, but the console.log and all the other Socket.IO stuff just doesn't happen. I'm finding this peculiar, because I have a different app.post method that works just fine, all console.logging and Socket.IO business happens. Here's the code:

```<code>app.post('/city', function(req,res) {
  let cityResponse = {
    user_name: req.body.userName
  }

  console.log('Express has received city.');

  //Socket.IO
  let city = io.of('/city').on('connection', (socket) => {
    socket.id = Math.random();
    socket.name = cityResponse.user_name;
    SOCKET_LIST[socket.id] = socket; //defined earlier

    User.onConnect(socket); //defined earlier

    socket.on('cityPageReady', function() {
      socket.emit('cityPageInfo', cityResponse);
      console.log('city page ready recieved');
    });

    console.log('A user has connected to the city!');
    console.log("Socket: " + socket);
    console.log("Socket ID: " + socket.id);
    console.log("SOCKET_LIST: ");
    console.log(SOCKET_LIST);

    socket.on('chat message', function(msg, user) {
      console.log('User ' + user + ' sent the message : ' + msg);
      socket.emit('chat message', msg, user);
    });
  });

  res.sendFile(path.join(__dirname, '/client/city/index.html'));
});
</code>```

As far as I can tell, both methods look pretty much the same, except for the Socket.IO stuff in the middle. I'm fairly certain that the io.of method is correct, as it's working for the City page, but not the race.

The only other difference is the way that the two pages are accessed. The City page is accessed through a HTML form with an action attribute, whereas the Race page is accessed through a HTML link (on the City page) with a href attribute.

Both methods are shown below:

CITY

```<code><form id="cityForm" action="http://localhost:4000/city" method="POST">
  User name: <input type="text" name="userName">
  button type="submit" id="formSubmit">Submit</button>
</form>
</code>```

RACE

```<code><div><a href="http://localhost:4000/race"></div>
</code>```

Can anyone see why this peculiar behaviour is occuring? If any other information is needed please let me know so that I can include it.

答:
When clicking an on HTML link, the browser does a GET HTML request. When you submit a Form (with method="POST"), the browser does a POST request.

When using app.post(), you tell express to listen for POST requests. If you want express to listen for GET requests, you should use app.get()

Body:
I'm using an app.post method in Express like so:

app.post('/race', function(req,res) {
  let raceResponse = {
    user_name: req.body.userName
  }
  console.log('Express has received race.');

  //Socket.IO
  let race = io.of('/race').on('connection', (socket) => {
    console.log('A user has entered the race!');
    socket.on('racePageReady', function() {
      console.log('race page ready recieved');
      socket.emit('racePageInfo', raceResponse);
    });

    socket.on('createRoom', function(roomName) {
      socket.join(roomName);
      let clients = io.sockets.adapter.rooms[roomName].sockets;
      console.log("A room with the name " + roomName + "was created.");
      console.log(clients);
      socket.emit('roomCreated', clients);
    });

    socket.on('joinRoom', function(roomName) {
      socket.join(roomName);
      let clients = io.sockets.adapter.rooms[roomName].sockets;
      console.log('A user joined the room with the name: ' + roomName + ". The user's name is " + raceResponse.user_name);
      console.log(clients);
      socket.emit('roomCreated', clients);
    });
  });

  res.sendFile(path.join(__dirname, '/client/race/index.html'));
}

The page is being sent fine, but the console.log and all the other Socket.IO stuff just doesn't happen. I'm finding this peculiar, because I have a different app.post method that works just fine, all console.logging and Socket.IO business happens. Here's the code:

app.post('/city', function(req,res) {
  let cityResponse = {
    user_name: req.body.userName
  }

  console.log('Express has received city.');

  //Socket.IO
  let city = io.of('/city').on('connection', (socket) => {
    socket.id = Math.random();
    socket.name = cityResponse.user_name;
    SOCKET_LIST[socket.id] = socket; //defined earlier

    User.onConnect(socket); //defined earlier

    socket.on('cityPageReady', function() {
      socket.emit('cityPageInfo', cityResponse);
      console.log('city page ready recieved');
    });

    console.log('A user has connected to the city!');
    console.log("Socket: " + socket);
    console.log("Socket ID: " + socket.id);
    console.log("SOCKET_LIST: ");
    console.log(SOCKET_LIST);

    socket.on('chat message', function(msg, user) {
      console.log('User ' + user + ' sent the message : ' + msg);
      socket.emit('chat message', msg, user);
    });
  });

  res.sendFile(path.join(__dirname, '/client/city/index.html'));
});

As far as I can tell, both methods look pretty much the same, except for the Socket.IO stuff in the middle. I'm fairly certain that the io.of method is correct, as it's working for the City page, but not the race.

The only other difference is the way that the two pages are accessed. The City page is accessed through a HTML form with an action attribute, whereas the Race page is accessed through a HTML link (on the City page) with a href attribute.

Both methods are shown below:

CITY

<form id="cityForm" action="http://localhost:4000/city" method="POST">
  User name: <input type="text" name="userName">
  button type="submit" id="formSubmit">Submit</button>
</form>

RACE

Can anyone see why this peculiar behaviour is occuring? If any other information is needed please let me know so that I can include it.


Title: data.table generate sequence with intervals based on the first and last rows of unique ID

Body:
I have a data table like this. How would I generate a sequence with .25 step for each of the row with the same time in that ID number. I am pretty new to R and try to do some data wrangling ...

     id time
 1:  1   14
 2:  1   14
 3:  1   14
 4:  1   14
 5:  1   18
 6:  1   18
 7:  1   22
 8:  1   22
 9:  2    8
10:  2    8
11:  2    8
12:  2    8
13:  2   12
14:  2   15
15:  2   15
16:  2   15
17:  2   19
18:  2   19
19:  2   19
20:  2   19

I would like it to be like this

    id time new_time
 1:  1   14 14.00
 2:  1   14 14.25
 3:  1   14 14.50
 4:  1   14 14.75
 5:  1   18 18.00
 6:  1   18 18.25
 7:  1   22 22.00
 8:  1   22 22.25
 9:  2    8 8.00
10:  2    8 8.25
11:  2    8 8.50
12:  2    8 8.75
13:  2   12 12.00
14:  2   15 15.00
15:  2   15 15.25
16:  2   15 15.50
17:  2   19 19.00
18:  2   19 19.25
19:  2   19 19.50
20:  2   19 19.75

Body:
You can make use of the length.out argument in seq which we set to the group size of each time ( that's the .N in the code below which is a special symbol that data.table provides, see ?.N )

DT[, new_time := seq(first(time), by = 0.25, length.out = .N)  , by=time][]
#    id time new_time
# 1:  1   14    14.00
# 2:  1   14    14.25
# 3:  1   14    14.50
# 4:  1   14    14.75
# 5:  1   18    18.00
# 6:  1   18    18.25
# 7:  1   22    22.00
# 8:  1   22    22.25
# 9:  2    8     8.00
#10:  2    8     8.25
#11:  2    8     8.50
#12:  2    8     8.75
#13:  2   12    12.00
#14:  2   15    15.00
#15:  2   15    15.25
#16:  2   15    15.50
#17:  2   19    19.00
#18:  2   19    19.25
#19:  2   19    19.50
#20:  2   19    19.75

Another option would be rowid (and some calculus)

DT[, new_time := time + (rowid(time) - 1L) * 0.25]

data

library(data.table)
DT <- fread(text = "     id time
  1   14
  1   14
  1   14
  1   14
  1   18
  1   18
  1   22
  1   22
  2    8
  2    8
  2    8
  2    8
  2   12
  2   15
  2   15
  2   15
  2   19
  2   19
  2   19
  2   19")


问:
Collecting the value which have the same name in column and row from data frame
```<code>This is a small example:
a <- c("a", "b", "f", "c", "e")
b <- c("a", "c", "e", "d", "b")
p <- matrix(1:25, nrow = 5, dimnames = list(a, b))
p <- as.data.frame(p)

#data.frame would be like that
    a    c    e    d    b
a   1    6    11   16   21
b   2    7    12   17   22
f   3    8    13   18   23
c   4    9    14   19   24
e   5   10    15   20   25
</code>```

The output what I want:

```<code>  score
a   1
b   22
c   9
e   15
</code>```

This is the code I wrote:

```<code>L <- rownames(p)
output <- NULL
t <- 1
for (i in L) {
  tar_column <- p[i]
  score <- tar_column[t, ]
  tar_score <- matrix(score, nrow = 1, dimnames = list(i, "score"))
  output <- rbind(output, tar_score)
  t <- t+1
}
</code>```

The output I got:

```<code>score
a   1
b   22

Error in `[.data.frame`(p, i) : undefined columns selected
</code>```

The problem is that column name and rowname are not matched perfectly. I think that the if statement can help to skip the variable when it can't be matched to the column name. Could someone help me fix this problem?

答:
Just loop through each column/rowname (using sapply) and use square bracket notation to subset p on both that row and column:

```<code>sapply(c('a','b','c','e'), function(x) p[x,x])
 a  b  c  e
 1 22  9 15
</code>```

If you don't want to specify the variable names beforehand, you can just use either colnames or rownames:

```<code>sapply(colnames(p), function(x) p[x,x])
 a  c  e  d  b
 1  9 15 NA 22
</code>```

If there isn't a matching rowname, this will return NA for that value. If desired, you can drop the NA values by subsetting the result:

```<code>result <- sapply(colnames(p), function(x) p[x,x])
result[!is.na(result)]
 a  c  e  b
 1  9 15 22
</code>```

Body:
This is a small example:
a <- c("a", "b", "f", "c", "e")
b <- c("a", "c", "e", "d", "b")
p <- matrix(1:25, nrow = 5, dimnames = list(a, b))
p <- as.data.frame(p)

#data.frame would be like that
    a    c    e    d    b
a   1    6    11   16   21
b   2    7    12   17   22
f   3    8    13   18   23
c   4    9    14   19   24
e   5   10    15   20   25

The output what I want:

  score
a   1
b   22
c   9
e   15

This is the code I wrote:

L <- rownames(p)
output <- NULL
t <- 1
for (i in L) {
  tar_column <- p[i]
  score <- tar_column[t, ]
  tar_score <- matrix(score, nrow = 1, dimnames = list(i, "score"))
  output <- rbind(output, tar_score)
  t <- t+1
}

The output I got:

score
a   1
b   22

Error in `[.data.frame`(p, i) : undefined columns selected

The problem is that column name and rowname are not matched perfectly. I think that the if statement can help to skip the variable when it can't be matched to the column name. Could someone help me fix this problem?

Body:
Just loop through each column/rowname (using sapply) and use square bracket notation to subset p on both that row and column:

sapply(c('a','b','c','e'), function(x) p[x,x])
 a  b  c  e
 1 22  9 15

If you don't want to specify the variable names beforehand, you can just use either colnames or rownames:

sapply(colnames(p), function(x) p[x,x])
 a  c  e  d  b
 1  9 15 NA 22

If there isn't a matching rowname, this will return NA for that value. If desired, you can drop the NA values by subsetting the result:

result <- sapply(colnames(p), function(x) p[x,x])
result[!is.na(result)]
 a  c  e  b
 1  9 15 22


问:
Why I am getting java.lang.NoSuchMethodError in loading applicationContext in JBoss7.1.EAP
I am getting the following error, when I am trying to deploy an ear into dev server where its published to JBoss7.1.EAP. The error is coming at the start of the server.
This error is not coming when I am trying to deploy in local JBOSS server.
This is coming when I am trying to deploy to remote server.

The application is in Spring5 Hibernate, the ear contains a war file and an ejb jar .

```<code>2019-05-30 18:31:24,597 INFO [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] (ServerService Thread Pool -- 185) Shutting down ExecutorService taskExecutor
2019-05-30 18:31:24,617 ERROR [org.springframework.web.context.ContextLoader] (ServerService Thread Pool -- 185) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name excleXMLRegistrant defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoSuchMethodError: com.sun.xml.bind.v2.model.annotation.AnnotationReader.hasClassAnnotation(Ljava/lang/Object;Ljava/lang/Class;)Z
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1231)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1130)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:756)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:205)
at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:174)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:239)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:99)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.NoSuchMethodError: com.sun.xml.bind.v2.model.annotation.AnnotationReader.hasClassAnnotation(Ljava/lang/Object;Ljava/lang/Class;)Z
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:252)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:104)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:85)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:227)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:99)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:85)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:375)
at com.sun.xml.bind.v2.model.impl.RegistryInfoImpl.<init>(RegistryInfoImpl.java:103)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.addRegistry(ModelBuilder.java:417)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:387)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:465)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:303)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:142)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1174)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:162)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:286)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:137)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:108)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:286)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:412)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:375)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:279)
at com.gee.gecs.cosmos.utilities.XmlService.fromXML(XmlService.java:106)
at com.gee.gecs.cosmos.utilities.ExpressionRunner.getJaxBObject(ExpressionRunner.java:430)
at com.gee.gecs.cosmos.registrant.ExcleXMLRegistrant.<clinit>(ExcleXMLRegistrant.java:115)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:88)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1223)
... 33 more
</code>```

The war file contains the relevant jars in WEB-INF/lib folder

答:
Hi you have two versions of jaxb-impl in your WEB-INF folder. One version is 2.0.5 and another version is 2.2.7. You need to remove the older version from your dependencies.

Also you have jaxb-api-2.1 in your dependencies.You need 2.2 version.

All in all looking through the contents of your WEB-INF lib you have a lot of libraries which are duplicated with different version. You need to do some clean up I believe.

Body:
I am getting the following error, when I am trying to deploy an ear into dev server where its published to JBoss7.1.EAP. The error is coming at the start of the server.
This error is not coming when I am trying to deploy in local JBOSS server.
This is coming when I am trying to deploy to remote server.

The application is in Spring5 Hibernate, the ear contains a war file and an ejb jar .

2019-05-30 18:31:24,597 INFO [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] (ServerService Thread Pool -- 185) Shutting down ExecutorService taskExecutor
2019-05-30 18:31:24,617 ERROR [org.springframework.web.context.ContextLoader] (ServerService Thread Pool -- 185) Context initialization failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name excleXMLRegistrant defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoSuchMethodError: com.sun.xml.bind.v2.model.annotation.AnnotationReader.hasClassAnnotation(Ljava/lang/Object;Ljava/lang/Class;)Z
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1231)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1130)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:756)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
at io.undertow.servlet.core.ApplicationListeners.contextInitialized(ApplicationListeners.java:187)
at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:205)
at io.undertow.servlet.core.DeploymentManagerImpl$1.call(DeploymentManagerImpl.java:174)
at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:42)
at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1508)
at io.undertow.servlet.core.DeploymentManagerImpl.deploy(DeploymentManagerImpl.java:239)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService.startContext(UndertowDeploymentService.java:99)
at org.wildfly.extension.undertow.deployment.UndertowDeploymentService$1.run(UndertowDeploymentService.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: java.lang.NoSuchMethodError: com.sun.xml.bind.v2.model.annotation.AnnotationReader.hasClassAnnotation(Ljava/lang/Object;Ljava/lang/Class;)Z
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:252)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:104)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:85)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getClassInfo(ModelBuilder.java:227)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:99)
at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.getClassInfo(RuntimeModelBuilder.java:85)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:375)
at com.sun.xml.bind.v2.model.impl.RegistryInfoImpl.<init>(RegistryInfoImpl.java:103)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.addRegistry(ModelBuilder.java:417)
at com.sun.xml.bind.v2.model.impl.ModelBuilder.getTypeInfo(ModelBuilder.java:387)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:465)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:303)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:142)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1174)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:162)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:286)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:137)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:108)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:286)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:412)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:375)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:279)
at com.gee.gecs.cosmos.utilities.XmlService.fromXML(XmlService.java:106)
at com.gee.gecs.cosmos.utilities.ExpressionRunner.getJaxBObject(ExpressionRunner.java:430)
at com.gee.gecs.cosmos.registrant.ExcleXMLRegistrant.<clinit>(ExcleXMLRegistrant.java:115)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:88)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1223)
... 33 more

The war file contains the relevant jars in WEB-INF/lib folder


问:
Pass a react value into a JS Alert
Im attempting to learn a little bit of react and struggling with this simple concept. I know its just a syntax thing that I'm unfamiliar with but I just can't get it down.

Im attempting to create a tic tac toe game, where each square has a value. When the square is clicked, it should pop up an alert box that shows "You've clicked box {Box Number}". I cannot figure out how to pass the value to the alert function.

```<code>class Square extends React.Component {

  render() {
    return (
      <button className="square" onClick={function() {alert("Youve clicked box " + this.props.value);}}>
        {this.props.value}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square value={i} />;
  }

  render() {
    const status = 'Next player: X';

    return (
      <div>
        <div className="status">{status}</div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  render() {
    return (
      <div className="game">
        <div className="game-board">
          <Board />
        </div>
        <div className="game-info">
          <div>{/* status */}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);
</code>```

答:
Looking at your code and based on your comment, the issue is that you're trying to access the props attribute of an object (this) that doesn't have the props attribute.

One way you can do this is to use an arrow function.

```<code><button onClick={() => { alert(`Something ${this.props.value}`); }>Click Me</button>
</code>```

Another way is to bind the function.

```<code>class Box extends React.Component {
  constructor(props) {
   super(props)
   this.onClick = this.onClick.bind(this)
  }

  onClick() {
    alert()
  }

  render() {
    return (
      <button onClick={this.onClick}>Click Me</button>
    )
  }
}
</code>```

Alternatively, you can directly use an arrow function inside your class so you don't have to bind if you don't want to define one in the render function.

```<code>class Box extends React.Component {
  onClick = () => {
    alert()
  }

  render() {
    return (
      <button onClick={this.onClick}>Click Me</button>
    )
  }
}
</code>```

Demo: https://jsfiddle.net/1wfyq68r/

Title: Pass a react value into a JS Alert

Body:
Im attempting to learn a little bit of react and struggling with this simple concept. I know its just a syntax thing that I'm unfamiliar with but I just can't get it down.

Im attempting to create a tic tac toe game, where each square has a value. When the square is clicked, it should pop up an alert box that shows "You've clicked box {Box Number}". I cannot figure out how to pass the value to the alert function.

class Square extends React.Component {

  render() {
    return (
      <button className="square" onClick={function() {alert("Youve clicked box " + this.props.value);}}>
        {this.props.value}
      </button>
    );
  }
}

class Board extends React.Component {
  renderSquare(i) {
    return <Square value={i} />;
  }

  render() {
    const status = 'Next player: X';

    return (

{status}

          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}

          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}

          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}

    );
  }
}

class Game extends React.Component {
  render() {
    return (

          <Board />

{/* status */}

{/* TODO */}

    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

Body:
Looking at your code and based on your comment, the issue is that you're trying to access the props attribute of an object (this) that doesn't have the props attribute.

One way you can do this is to use an arrow function.

<button onClick={() => { alert(`Something ${this.props.value}`); }>Click Me</button>

Another way is to bind the function.

class Box extends React.Component {
  constructor(props) {
   super(props)
   this.onClick = this.onClick.bind(this)
  }

  onClick() {
    alert()
  }

  render() {
    return (
      <button onClick={this.onClick}>Click Me</button>
    )
  }
}

Alternatively, you can directly use an arrow function inside your class so you don't have to bind if you don't want to define one in the render function.

class Box extends React.Component {
  onClick = () => {
    alert()
  }

  render() {
    return (
      <button onClick={this.onClick}>Click Me</button>
    )
  }
}

Demo: https://jsfiddle.net/1wfyq68r/


问:
Var is undefined in foundation.util.touch.js
I am getting an error on mobile when trying to use the sliders and the slider isn't draggable.  This is for the non-native version. The sliders work on desktops (chrome, firefox, ie) but not on an ipad (safari)

Foundation 6.5.3 via Foundation Rails 6.5.3

error in console is:

TypeError: touches is undefined on line 133 foundation.util.touch.js

https://github.com/zurb/foundation-sites/blob/develop/js/foundation.util.touch.js#L133

```<code> var touches = event.changedTouches,
          first = touches[0],
          eventTypes = {
            touchstart: 'mousedown',
            touchmove: 'mousemove',
            touchend: 'mouseup'
          },
          type = eventTypes[event.type],
          simulatedEvent
;
</code>```

133 is this line:

```<code>first = touches[0],
</code>```

Is it valid to use one var in a multi-var declaration var statement like that, declaring it and then using it in the same statement? Is that what the problem is?

答: I think this problem occurs when using older versions of jQuery. See https://github.com/zurb/foundation-sites/issues/11763</p>

Body:
I am getting an error on mobile when trying to use the sliders and the slider isn't draggable.  This is for the non-native version. The sliders work on desktops (chrome, firefox, ie) but not on an ipad (safari)

Foundation 6.5.3 via Foundation Rails 6.5.3

error in console is:

TypeError: touches is undefined on line 133 foundation.util.touch.js

https://github.com/zurb/foundation-sites/blob/develop/js/foundation.util.touch.js#L133

 var touches = event.changedTouches,
          first = touches[0],
          eventTypes = {
            touchstart: 'mousedown',
            touchmove: 'mousemove',
            touchend: 'mouseup'
          },
          type = eventTypes[event.type],
          simulatedEvent
;

133 is this line:

first = touches[0],

Is it valid to use one var in a multi-var declaration var statement like that, declaring it and then using it in the same statement? Is that what the problem is?


答:
You're re-binding the context of this by using a function declaration in your onClick. When you refer to this inside of that function, you're now referring to the context of that function, not the Square class (where this.props would reside).

Any easy fix is to use an arrow function instead–it does not rebind the context of this.

```<code> <button
    className="square"
    onClick={() => alert("Youve clicked box " + this.props.value)}
  >
  {this.props.value}
 </button>
</code>```

Title: Pass a react value into a JS Alert

Body:
You're re-binding the context of this by using a function declaration in your onClick. When you refer to this inside of that function, you're now referring to the context of that function, not the Square class (where this.props would reside).

Any easy fix is to use an arrow function instead–it does not rebind the context of this.

 <button
    className="square"
    onClick={() => alert("Youve clicked box " + this.props.value)}
  >
  {this.props.value}
 </button>


问:
Broken references in Virtualenvs
I recently installed a bunch of dotfiles on my Mac along with some other applications (I changed to iTerm instead of Terminal, and Sublime as my default text editor) but ever since, all my virtual environments have stopped working, although their folders inside .virtualenvs are still there and they give the following error whenever I try to run anything in them:

```<code>dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /Users/[user]/.virtualenvs/modclass/bin/python
  Reason: image not found
Trace/BPT trap: 5
</code>```

I have removed all the files related to dotfiles and have restored my .bash_profile to what it was before, but the problem persists. Is there any way to diagnose the problem or solve it in an easy way (e.g. not requiring to create all the virtualenvs all over again)?

答:
I had a broken virtual env due to a Homebrew reinstall of python (thereby broken symlinks) and also a few "sudo pip install"s I had done earlier. Weizhong's tips were very helpful in fixing the issues without having to reinstall packages. I also had to do the following for the mixed permissions problem.

sudo chown -R my_username lib/python2.7/site-packages

ContentLicense: CC BY-SA 3.0

Title: Broken references in Virtualenvs

Body:
I recently installed a bunch of dotfiles on my Mac along with some other applications (I changed to iTerm instead of Terminal, and Sublime as my default text editor) but ever since, all my virtual environments have stopped working, although their folders inside .virtualenvs are still there and they give the following error whenever I try to run anything in them:

dyld: Library not loaded: @executable_path/../.Python
  Referenced from: /Users/[user]/.virtualenvs/modclass/bin/python
  Reason: image not found
Trace/BPT trap: 5

I have removed all the files related to dotfiles and have restored my .bash_profile to what it was before, but the problem persists. Is there any way to diagnose the problem or solve it in an easy way (e.g. not requiring to create all the virtualenvs all over again)?


问:
How to put a new line into a wpf TextBlock control?
I'm fetching text from an XML file, and I'd like to insert some new lines that are interpreted by the textblock render as new lines.

I've tried:

```<code><data>Foo bar baz \n baz bar</data>
</code>```

But the data is still displayed without the new line. I set the contents of <data> via the .Text property via C#.

What do I need to put in the XML in order for it to render the new line in the GUI?

I've tried something like this manually setting the text in the XAML:

```<code><TextBlock Margin="0 15 0 0" Width="600">
There

is a new line.
</TextBlock>
</code>```

And while the encoded character doesn't appear in the GUI it also doesn't give me a new line.

答:
You have to ensure that the textblock has this option enabled:</p>

```<code>AcceptsReturn="True"
</code>```

Body:
I'm fetching text from an XML file, and I'd like to insert some new lines that are interpreted by the textblock render as new lines.

I've tried:

<data>Foo bar baz \n baz bar</data>

But the data is still displayed without the new line. I set the contents of <data> via the .Text property via C#.

What do I need to put in the XML in order for it to render the new line in the GUI?

I've tried something like this manually setting the text in the XAML:

<TextBlock Margin="0 15 0 0" Width="600">
There

is a new line.
</TextBlock>

And while the encoded character doesn't appear in the GUI it also doesn't give me a new line.

Body:
You have to ensure that the textblock has this option enabled:

AcceptsReturn="True"


问:
Calling merge layer on batch data in Keras (averaging output of a layer over batch)
I'm using the Keras functional API, and am interested in averaging the output of a previous layer over the training batch.

I've tried simply calling the Keras Average layer on the output of a Dense layer.

Here's a simple example.

from keras.models import  Model
from keras import layers
from keras import Input
from keras.utils import plot_model

input_tensor = layers.Input(shape=(784,))
output = layers.Dense(10,)(input_tensor)
average = layers.Average()(output)
avgout = Model(input_tensor, avgout)
avgout.summary()
```

<p>What I'd like is the "avgout" layer to give me the mean output of the output layer. The result:</p>

<p></p>

```ValueError                                Traceback (most recent call last)
<ipython-input-7-9d5576113651> in <module>
      6 input_tensor = layers.Input(shape=(784,))
      7 output = layers.Dense(10,)(input_tensor)
----> 8 average = layers.Average()(output)
      9 avgout = Model(input_tensor, avgout)
     10 avgout.summary()

~/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    429                                          'You can build it manually via: '
    430                                          '`layer.build(batch_input_shape)`')
--> 431                 self.build(unpack_singleton(input_shapes))
    432                 self.built = True
    433

~/anaconda3/lib/python3.7/site-packages/keras/layers/merge.py in build(self, input_shape)
     66         # Used purely for shape validation.
     67         if not isinstance(input_shape, list):
---> 68             raise ValueError('A merge layer should be called '
     69                              'on a list of inputs.')
     70         if len(input_shape) < 2:

ValueError: A merge layer should be called on a list of inputs.
```

答:
The Average layer in keras computer the average of multiple tensors, but not the mean of one tensor.

What you can do is using keras backend mean :

```<code>from keras import backend as K
from keras.models import  Model
from keras import layers
from keras import Input
from keras.utils import plot_model

def mean(input):
    return K.mean(input, axis=1)

input_tensor = layers.Input(shape=(784,))
output = layers.Dense(10,)(input_tensor)
average = layers.Lambda(mean, input_shape=(10,))(output)
avgout = Model(input_tensor, average)
avgout.summary()
</code>```

Body:
I'm using the Keras functional API, and am interested in averaging the output of a previous layer over the training batch.

I've tried simply calling the Keras Average layer on the output of a Dense layer.

Here's a simple example.

from keras.models import  Model
from keras import layers
from keras import Input
from keras.utils import plot_model

input_tensor = layers.Input(shape=(784,))
output = layers.Dense(10,)(input_tensor)
average = layers.Average()(output)
avgout = Model(input_tensor, avgout)
avgout.summary()

What I'd like is the "avgout" layer to give me the mean output of the output layer. The result:

ValueError                                Traceback (most recent call last)
<ipython-input-7-9d5576113651> in <module>
      6 input_tensor = layers.Input(shape=(784,))
      7 output = layers.Dense(10,)(input_tensor)
----> 8 average = layers.Average()(output)
      9 avgout = Model(input_tensor, avgout)
     10 avgout.summary()

~/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    429                                          'You can build it manually via: '
    430                                          '`layer.build(batch_input_shape)`')
--> 431                 self.build(unpack_singleton(input_shapes))
    432                 self.built = True
    433

~/anaconda3/lib/python3.7/site-packages/keras/layers/merge.py in build(self, input_shape)
     66         # Used purely for shape validation.
     67         if not isinstance(input_shape, list):
---> 68             raise ValueError('A merge layer should be called '
     69                              'on a list of inputs.')
     70         if len(input_shape) < 2:

ValueError: A merge layer should be called on a list of inputs.

Body:
The Average layer in keras computer the average of multiple tensors, but not the mean of one tensor.

What you can do is using keras backend mean :

from keras import backend as K
from keras.models import  Model
from keras import layers
from keras import Input
from keras.utils import plot_model

def mean(input):
    return K.mean(input, axis=1)

input_tensor = layers.Input(shape=(784,))
output = layers.Dense(10,)(input_tensor)
average = layers.Lambda(mean, input_shape=(10,))(output)
avgout = Model(input_tensor, average)
avgout.summary()


问:
Programmatically Install Add-In VBA
I'm looking to create a macro that'll install an add-in for the user to the excel ribbon. I'm upto:

```<code>Private Sub Workbook_Open()

On Error Resume Next
Application.AddIns("Name of Addin").Installed = False
On Error GoTo 0

With Application
    .AddIns.Add "Filepath to addin in shared location", False
    .AddIns("Name of Addin").Installed = True
End With

ThisWorkbook.Close False

End Sub
</code>```

Once running the macro, the addin installs to the ribbon no problems. The issue is, once excel is closed down, the addin no longer shows in the ribbon.

It would appear that excel is expecting the addin to be copied into the users C:\Documents and Settings\Username\Application Data\Microsoft\AddiIns folder as it throws the error that it can't find it when starting excel after closing down.

Now my understanding is that the second (false) variable for the line of code below basically says that the addin shouldn't be copied to the AddIns directory and rather should stay in the shared location.

```<code>.AddIns.Add "Filepath to addin in shared location", False
</code>```

Any ideas on why Excel is expecting the addin to be in the users default folder?

答:
I'll give it a try. Please see comments in code.

ThisWorkbook

```<code>Option Explicit
 '
 '---------------------------------------------------------------------
 ' Purpose : Call for installation as an addin if not installed
 '---------------------------------------------------------------------
 '
Private Sub Workbook_Open()

    Dim AddinTitle As String, AddinName As String
    Dim XlsName As String

    AddinTitle = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4)
    XlsName = AddinTitle & ".xlsm"
    AddinName = AddinTitle & ".xla"

     'check the addin's not already installed in UserLibraryPath
    If Dir(Application.UserLibraryPath & AddinName) = Empty Then
         'ask if user wants to install now
        If MsgBox("Install " & AddinTitle & _
        " as an add-in?", vbYesNo, _
        "Install?") = vbYes _
        Then
            Run "InstallAddIn"
        End If
    Else
        If ThisWorkbook.Name = XlsName Then
            Run "ReInstall"
        End If
    End If

End Sub

 '
 '---------------------------------------------------------------------
 ' Purpose : Actuate the addin, add custom controls
 '---------------------------------------------------------------------
 '
Private Sub Workbook_AddinInstall()
    Run "AddButtons"
End Sub
 '
 '---------------------------------------------------------------------
 ' Purpose : Deactivate the addin, remove custom controls
 '---------------------------------------------------------------------
 '
Private Sub Workbook_AddinUninstall()
    Run "RemoveButtons"
End Sub
</code>```

Module

```<code>Option Explicit
 '
 '---------------------------------------------------------------------
 ' Purpose : Convert .xls file to .xla, move it to
 ' addins folder, and install as addin
 '---------------------------------------------------------------------
 '
Private Sub InstallAddIn()

    Dim AddinTitle As String, AddinName As String
    Dim XlsVersion As String, MessageBody As String

    With ThisWorkbook
        AddinTitle = Left(.Name, Len(.Name) - 4)
        AddinName = AddinTitle & ".xlam"
        XlsVersion = .FullName '< could be anywhere

         'check the addin's not installed in
         'UserLibraryPath (error handling)
        If Dir(Application.UserLibraryPath & AddinName) = Empty Then

            .IsAddin = True '< hide workbook window

             'move & save as .xla file
            .SaveAs Application.UserLibraryPath & AddinName, 55

             'go thru the add-ins collection to see if it's listed
            If Listed Then
                 'check this addins checkbox in the addin dialog box
                AddIns(AddinTitle).Installed = True '<--Error happening if .xlam format
            Else
                 'it's not listed (not previously installed)
                 'add it to the addins collection
                 'and check this addins checkbox
                AddIns.Add(ThisWorkbook.FullName, True) _
                .Installed = True
            End If

             'inform user...
            MessageBody = AddinTitle & " has been installed - " & _
            "to access the tools available in" & _
            vbNewLine & _
            "this addin, you will find a button in the 'Tools' " & _
            "menu for your use"
            If BooksAreOpen Then '< quit if no other books are open
                .Save
                MsgBox MessageBody & "...", , AddinTitle & _
                " Installation Status..."
            Else
                If MsgBox(MessageBody & " the" & vbNewLine & _
                "next time you open Excel." & _
                "" & vbNewLine & vbNewLine & _
                "Quit Excel?...", vbYesNo, _
                AddinTitle & " Installation Status...") = vbYes Then
                    Application.Quit
                Else
                    .Save
                End If
            End If
        End If

    End With
End Sub

'---------------------------------------------------------------------
 ' Purpose : Checks if this addin is in the addin collection
 '---------------------------------------------------------------------
 '
Private Function Listed() As Boolean

    Dim Addin As Addin, AddinTitle As String

    Listed = False
    With ThisWorkbook
        AddinTitle = Left(.Name, Len(.Name) - 4)
        For Each Addin In AddIns
            If Addin.Title = AddinTitle Then
                Listed = True
                Exit For
            End If
        Next
    End With
End Function

'---------------------------------------------------------------------
 ' Purpose : Check if any workbooks are open
 ' (this workbook & startups excepted)
 '---------------------------------------------------------------------
 '
Private Function BooksAreOpen() As Boolean
     '
    Dim Wb As Workbook, OpenBooks As String

     'get a list of open books
    For Each Wb In Workbooks
        With Wb
            If Not (.Name = ThisWorkbook.Name _
            Or .Path = Application.StartupPath) Then
                OpenBooks = OpenBooks & .Name
            End If
        End With
    Next
    If OpenBooks = Empty Then
        BooksAreOpen = False
    Else
        BooksAreOpen = True
    End If
End Function

'---------------------------------------------------------------------
 ' Purpose : Replace addin with another version if installed
 '---------------------------------------------------------------------
 '
Private Sub ReInstall()

    Dim AddinName As String

    With ThisWorkbook
        AddinName = Left(.Name, Len(.Name) - 4) & ".xla"

         'check if 'addin' is already installed
         'in UserLibraryPath (error handling)
        If Dir(Application.UserLibraryPath & AddinName) = Empty Then

             'install if no previous version exists
            Call InstallAddIn

        Else
             'delete installed version & replace with this one if ok
            If MsgBox(" The target folder already contains " & _
            "a file with the same name... " & _
            vbNewLine & vbNewLine & _
            " (That file was last modified on: " & _
            Workbooks(AddinName) _
            .BuiltinDocumentProperties("Last Save Time") & ")" & _
            vbNewLine & vbNewLine & vbNewLine & _
            " Would you like to replace the existing file with " & _
            "this one? " & _
            vbNewLine & vbNewLine & _
            " (This file was last modified on: " & _
            .BuiltinDocumentProperties("Last Save Time") & ")", _
            vbYesNo, "Add-in Is In Place - " & _
            "Confirm File Replacemant...") = vbYes Then
                Workbooks(AddinName).Close False
                Kill Application.UserLibraryPath & AddinName
                Call InstallAddIn
            End If
        End If
    End With
End Sub

 '---------------------------------------------------------------------
 ' Purpose : Convert .xla file to .xls format
 ' and move it to default file path
 '---------------------------------------------------------------------
 '
Private Sub RemoveAddIn()

    Dim AddinTitle As String, AddinName As String
    Dim XlaVersion As String

    Application.ScreenUpdating = False

    With ThisWorkbook
        AddinTitle = Left(.Name, Len(.Name) - 4)
        AddinName = AddinTitle & ".xla"
        XlaVersion = .FullName

         'check the 'addin' is not already removed
         'from UserLibraryPath (error handling)
        If Not Dir(Application.UserLibraryPath & AddinName) = Empty _
        Then

            .Sheets(1).Cells.ClearContents '< cleanup
            Call RemoveButtons

             'move & save as .xls file
            .SaveAs Application.DefaultFilePath & _
            "\" & AddinTitle & ".xls"

            Kill XlaVersion '< delete .xla version

             'uncheck checkbox in the addin dialog box
            AddIns(AddinTitle).Installed = False
            .IsAddin = False '< show workbook window
            .Save

             'inform user and close
            MsgBox "The addin '" & AddinTitle & "' has been " & _
            "removed and converted to an .xls file." & _
            vbNewLine & vbNewLine & _
            "Should you later wish to re-install this as " & _
            "an addin, open the .xls file which" & _
            vbNewLine & "can now be found in " & _
            Application.DefaultFilePath & _
            " as: '" & .Name & "'"
            .Close
        End If

    End With

    Application.ScreenUpdating = True
End Sub

'---------------------------------------------------------------------
 ' Purpose : Add addin control buttons
 '---------------------------------------------------------------------
 '
Private Sub AddButtons()

     'change 'Startups...' to suit
    Const MyControl As String = "Startups..."
     'change 'Manage Startups' to suit
    Const MyControlCaption As String = "Manage Startups"

    Dim AddinTitle As String, Mybar As Object

    AddinTitle = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4)

    Call RemoveButtons

    On Error GoTo ErrHandler
    Set Mybar = Application.CommandBars("Worksheet Menu Bar") _
    .Controls("Tools").Controls _
    .Add(Type:=msoControlPopup, before:=13)
     '
    With Mybar
        .BeginGroup = True
        .Caption = MyControl
         '-------------------------------------------------------------
        .Controls.Add.Caption = MyControlCaption
        .Controls(MyControlCaption).OnAction = "ShowStartupForm"
         '-------------------------------------------------------------
        With .Controls.Add
            .BeginGroup = True
            .Caption = "Case " & AddinTitle
        End With
        .Controls("Case change " & AddinTitle).OnAction = "ULCase.UpperMacro"
         '-------------------------------------------------------------
        .Controls.Add.Caption = "Remove " & AddinTitle
        .Controls("Remove " & AddinTitle).OnAction = "Module1.RemoveAddIn"
         '-------------------------------------------------------------
    End With
    Exit Sub

ErrHandler:
    Set Mybar = Nothing
    Set Mybar = Application.CommandBars("Tools") _
    .Controls.Add(Type:=msoControlPopup, before:=13)
    Resume Next
End Sub
 '
 '---------------------------------------------------------------------
 ' Purpose : Remove addin control buttons
 '---------------------------------------------------------------------
 '
Private Sub RemoveButtons()
     '
     'change 'Startups...' to suit
    Const MyControl As String = "Startups..."
    On Error Resume Next
    With Application
        .CommandBars("Tools").Controls(MyControl).Delete
        .CommandBars("Worksheet Menu Bar") _
        .Controls("Tools").Controls(MyControl).Delete
    End With
End Sub
</code>```

Title: Programmatically Install Add-In VBA

Body:
I'm looking to create a macro that'll install an add-in for the user to the excel ribbon. I'm upto:

Private Sub Workbook_Open()

On Error Resume Next
Application.AddIns("Name of Addin").Installed = False
On Error GoTo 0

With Application
    .AddIns.Add "Filepath to addin in shared location", False
    .AddIns("Name of Addin").Installed = True
End With

ThisWorkbook.Close False

End Sub

Once running the macro, the addin installs to the ribbon no problems. The issue is, once excel is closed down, the addin no longer shows in the ribbon.

It would appear that excel is expecting the addin to be copied into the users C:\Documents and Settings\Username\Application Data\Microsoft\AddiIns folder as it throws the error that it can't find it when starting excel after closing down.

Now my understanding is that the second (false) variable for the line of code below basically says that the addin shouldn't be copied to the AddIns directory and rather should stay in the shared location.

.AddIns.Add "Filepath to addin in shared location", False

Any ideas on why Excel is expecting the addin to be in the users default folder?

Body:
I'll give it a try. Please see comments in code.

ThisWorkbook

Option Explicit
 '
 '---------------------------------------------------------------------
 ' Purpose : Call for installation as an addin if not installed
 '---------------------------------------------------------------------
 '
Private Sub Workbook_Open()

    Dim AddinTitle As String, AddinName As String
    Dim XlsName As String

    AddinTitle = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4)
    XlsName = AddinTitle & ".xlsm"
    AddinName = AddinTitle & ".xla"

     'check the addin's not already installed in UserLibraryPath
    If Dir(Application.UserLibraryPath & AddinName) = Empty Then
         'ask if user wants to install now
        If MsgBox("Install " & AddinTitle & _
        " as an add-in?", vbYesNo, _
        "Install?") = vbYes _
        Then
            Run "InstallAddIn"
        End If
    Else
        If ThisWorkbook.Name = XlsName Then
            Run "ReInstall"
        End If
    End If

End Sub

 '
 '---------------------------------------------------------------------
 ' Purpose : Actuate the addin, add custom controls
 '---------------------------------------------------------------------
 '
Private Sub Workbook_AddinInstall()
    Run "AddButtons"
End Sub
 '
 '---------------------------------------------------------------------
 ' Purpose : Deactivate the addin, remove custom controls
 '---------------------------------------------------------------------
 '
Private Sub Workbook_AddinUninstall()
    Run "RemoveButtons"
End Sub

Module

Option Explicit
 '
 '---------------------------------------------------------------------
 ' Purpose : Convert .xls file to .xla, move it to
 ' addins folder, and install as addin
 '---------------------------------------------------------------------
 '
Private Sub InstallAddIn()

    Dim AddinTitle As String, AddinName As String
    Dim XlsVersion As String, MessageBody As String

    With ThisWorkbook
        AddinTitle = Left(.Name, Len(.Name) - 4)
        AddinName = AddinTitle & ".xlam"
        XlsVersion = .FullName '< could be anywhere

         'check the addin's not installed in
         'UserLibraryPath (error handling)
        If Dir(Application.UserLibraryPath & AddinName) = Empty Then

            .IsAddin = True '< hide workbook window

             'move & save as .xla file
            .SaveAs Application.UserLibraryPath & AddinName, 55

             'go thru the add-ins collection to see if it's listed
            If Listed Then
                 'check this addins checkbox in the addin dialog box
                AddIns(AddinTitle).Installed = True '<--Error happening if .xlam format
            Else
                 'it's not listed (not previously installed)
                 'add it to the addins collection
                 'and check this addins checkbox
                AddIns.Add(ThisWorkbook.FullName, True) _
                .Installed = True
            End If

             'inform user...
            MessageBody = AddinTitle & " has been installed - " & _
            "to access the tools available in" & _
            vbNewLine & _
            "this addin, you will find a button in the 'Tools' " & _
            "menu for your use"
            If BooksAreOpen Then '< quit if no other books are open
                .Save
                MsgBox MessageBody & "...", , AddinTitle & _
                " Installation Status..."
            Else
                If MsgBox(MessageBody & " the" & vbNewLine & _
                "next time you open Excel." & _
                "" & vbNewLine & vbNewLine & _
                "Quit Excel?...", vbYesNo, _
                AddinTitle & " Installation Status...") = vbYes Then
                    Application.Quit
                Else
                    .Save
                End If
            End If
        End If

    End With
End Sub

'---------------------------------------------------------------------
 ' Purpose : Checks if this addin is in the addin collection
 '---------------------------------------------------------------------
 '
Private Function Listed() As Boolean

    Dim Addin As Addin, AddinTitle As String

    Listed = False
    With ThisWorkbook
        AddinTitle = Left(.Name, Len(.Name) - 4)
        For Each Addin In AddIns
            If Addin.Title = AddinTitle Then
                Listed = True
                Exit For
            End If
        Next
    End With
End Function

'---------------------------------------------------------------------
 ' Purpose : Check if any workbooks are open
 ' (this workbook & startups excepted)
 '---------------------------------------------------------------------
 '
Private Function BooksAreOpen() As Boolean
     '
    Dim Wb As Workbook, OpenBooks As String

     'get a list of open books
    For Each Wb In Workbooks
        With Wb
            If Not (.Name = ThisWorkbook.Name _
            Or .Path = Application.StartupPath) Then
                OpenBooks = OpenBooks & .Name
            End If
        End With
    Next
    If OpenBooks = Empty Then
        BooksAreOpen = False
    Else
        BooksAreOpen = True
    End If
End Function

'---------------------------------------------------------------------
 ' Purpose : Replace addin with another version if installed
 '---------------------------------------------------------------------
 '
Private Sub ReInstall()

    Dim AddinName As String

    With ThisWorkbook
        AddinName = Left(.Name, Len(.Name) - 4) & ".xla"

         'check if 'addin' is already installed
         'in UserLibraryPath (error handling)
        If Dir(Application.UserLibraryPath & AddinName) = Empty Then

             'install if no previous version exists
            Call InstallAddIn

        Else
             'delete installed version & replace with this one if ok
            If MsgBox(" The target folder already contains " & _
            "a file with the same name... " & _
            vbNewLine & vbNewLine & _
            " (That file was last modified on: " & _
            Workbooks(AddinName) _
            .BuiltinDocumentProperties("Last Save Time") & ")" & _
            vbNewLine & vbNewLine & vbNewLine & _
            " Would you like to replace the existing file with " & _
            "this one? " & _
            vbNewLine & vbNewLine & _
            " (This file was last modified on: " & _
            .BuiltinDocumentProperties("Last Save Time") & ")", _
            vbYesNo, "Add-in Is In Place - " & _
            "Confirm File Replacemant...") = vbYes Then
                Workbooks(AddinName).Close False
                Kill Application.UserLibraryPath & AddinName
                Call InstallAddIn
            End If
        End If
    End With
End Sub

 '---------------------------------------------------------------------
 ' Purpose : Convert .xla file to .xls format
 ' and move it to default file path
 '---------------------------------------------------------------------
 '
Private Sub RemoveAddIn()

    Dim AddinTitle As String, AddinName As String
    Dim XlaVersion As String

    Application.ScreenUpdating = False

    With ThisWorkbook
        AddinTitle = Left(.Name, Len(.Name) - 4)
        AddinName = AddinTitle & ".xla"
        XlaVersion = .FullName

         'check the 'addin' is not already removed
         'from UserLibraryPath (error handling)
        If Not Dir(Application.UserLibraryPath & AddinName) = Empty _
        Then

            .Sheets(1).Cells.ClearContents '< cleanup
            Call RemoveButtons

             'move & save as .xls file
            .SaveAs Application.DefaultFilePath & _
            "\" & AddinTitle & ".xls"

            Kill XlaVersion '< delete .xla version

             'uncheck checkbox in the addin dialog box
            AddIns(AddinTitle).Installed = False
            .IsAddin = False '< show workbook window
            .Save

             'inform user and close
            MsgBox "The addin '" & AddinTitle & "' has been " & _
            "removed and converted to an .xls file." & _
            vbNewLine & vbNewLine & _
            "Should you later wish to re-install this as " & _
            "an addin, open the .xls file which" & _
            vbNewLine & "can now be found in " & _
            Application.DefaultFilePath & _
            " as: '" & .Name & "'"
            .Close
        End If

    End With

    Application.ScreenUpdating = True
End Sub

'---------------------------------------------------------------------
 ' Purpose : Add addin control buttons
 '---------------------------------------------------------------------
 '
Private Sub AddButtons()

     'change 'Startups...' to suit
    Const MyControl As String = "Startups..."
     'change 'Manage Startups' to suit
    Const MyControlCaption As String = "Manage Startups"

    Dim AddinTitle As String, Mybar As Object

    AddinTitle = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 4)

    Call RemoveButtons

    On Error GoTo ErrHandler
    Set Mybar = Application.CommandBars("Worksheet Menu Bar") _
    .Controls("Tools").Controls _
    .Add(Type:=msoControlPopup, before:=13)
     '
    With Mybar
        .BeginGroup = True
        .Caption = MyControl
         '-------------------------------------------------------------
        .Controls.Add.Caption = MyControlCaption
        .Controls(MyControlCaption).OnAction = "ShowStartupForm"
         '-------------------------------------------------------------
        With .Controls.Add
            .BeginGroup = True
            .Caption = "Case " & AddinTitle
        End With
        .Controls("Case change " & AddinTitle).OnAction = "ULCase.UpperMacro"
         '-------------------------------------------------------------
        .Controls.Add.Caption = "Remove " & AddinTitle
        .Controls("Remove " & AddinTitle).OnAction = "Module1.RemoveAddIn"
         '-------------------------------------------------------------
    End With
    Exit Sub

ErrHandler:
    Set Mybar = Nothing
    Set Mybar = Application.CommandBars("Tools") _
    .Controls.Add(Type:=msoControlPopup, before:=13)
    Resume Next
End Sub
 '
 '---------------------------------------------------------------------
 ' Purpose : Remove addin control buttons
 '---------------------------------------------------------------------
 '
Private Sub RemoveButtons()
     '
     'change 'Startups...' to suit
    Const MyControl As String = "Startups..."
    On Error Resume Next
    With Application
        .CommandBars("Tools").Controls(MyControl).Delete
        .CommandBars("Worksheet Menu Bar") _
        .Controls("Tools").Controls(MyControl).Delete
    End With
End Sub


答:
You need to set the context of the click handler function so it references the correct this. This can be done by either

Using an arrow function

```<code>() => alert("Youve clicked box " + this.props.value)
</code>```

Explicitly binding

```<code>function() {
  alert("Youve clicked box " + this.props.value);
}.bind(this)
</code>```

A useful resource as to why this is required here

Title: Pass a react value into a JS Alert

Body:
You need to set the context of the click handler function so it references the correct this. This can be done by either

Using an arrow function

() => alert("Youve clicked box " + this.props.value)

Explicitly binding

function() {
  alert("Youve clicked box " + this.props.value);
}.bind(this)

A useful resource as to why this is required here


问:
Two values being compared before function returns the value
I have some code where a function (which contains a promise) runs and then returns a boolean value. I then check to see if that value is true, and if so run some other code. I had the values logging to the console to do some debugging, and I noticed that the if statement that checks to see if the function returned true was running before the function even returned anything.

I have attempted to use "await" and "async" but I haven't found any success in using them.

```<code>javascript
function myFunc()
   promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}
</code>```

Expected:

```<code>Returned true
Value was true
</code>```

Actual:

```<code>Value was false
Returned true
</code>```

答:
Try returning the promise from the function:

```<code>function myFunc()
   return promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}
</code>```

This is not the best practice, I would stick with a good old promise chain:

```<code>promise()
  .then(value => {
     if (value) {
       console.log('Value was true');
     } else {
       console.log('Value was false');
     }
   })
   .catch(err => {
         console.log('Error', err);
   });
</code>```

Body:
I have some code where a function (which contains a promise) runs and then returns a boolean value. I then check to see if that value is true, and if so run some other code. I had the values logging to the console to do some debugging, and I noticed that the if statement that checks to see if the function returned true was running before the function even returned anything.

I have attempted to use "await" and "async" but I haven't found any success in using them.

javascript
function myFunc()
   promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}

Expected:

Returned true
Value was true

Actual:

Value was false
Returned true

Body:
Try returning the promise from the function:

function myFunc()
   return promise()
      .then(value => {
         console.log('Returned true');
         return true;
      })
      .catch(err => {
         console.log('Error', err);
      });
end

if (myFunc()) {
   console.log('Value was true');
} else {
   console.log('Value was false');
}

This is not the best practice, I would stick with a good old promise chain:

promise()
  .then(value => {
     if (value) {
       console.log('Value was true');
     } else {
       console.log('Value was false');
     }
   })
   .catch(err => {
         console.log('Error', err);
   });


问:
How can I use "float: left" in a div without breaking the containing element's height?
It seems that floated HTML elements don't expand the heights of their containers. For example, consider the following code:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="portfoliosite">
    <div class="portfoliothumbnail"><!-- Img tag goes here --></div>
    <p class="portfoliotitle">AwesomeSite.Com</p>
    <p class="portfoliodescription">An awesome site I did. It launched on Jan 1, 2009</p>
</div></code>```

Notice how the containing div with the gray background is shorter than the red div, and the red div extends outside the container's boundaries. I'd like the containing element to expand to the size of its contents, including the floated element.

Is there an elegant solution for accomplishing this, preferably one that doesn't involve setting a fixed height or using JavaScript?

答: You need to clear the float, which returns document flow back to normal. Use clear:left (or right, or both if such floats need to be cleared) on the last element that should reset the flow. Also read up on ClearFix. It should be noted that ClearFix can get a little sticky with IE... if you have control over the markup, sometimes it is safer to use the traditional clear.

OwnerDisplayName: Joshua Carmody

Body:
It seems that floated HTML elements don't expand the heights of their containers. For example, consider the following code:

.portfoliosite {
    background: #777;
    padding: 10px;
    width: 550px;
}
.portfoliothumbnail {
    background: red;
    margin: 0 10px 10px 0;
    float: left;
    height: 150px;
    width: 150px;
}

AwesomeSite.Com

An awesome site I did. It launched on Jan 1, 2009

Notice how the containing div with the gray background is shorter than the red div, and the red div extends outside the container's boundaries. I'd like the containing element to expand to the size of its contents, including the floated element.

Is there an elegant solution for accomplishing this, preferably one that doesn't involve setting a fixed height or using JavaScript?

LastEditorDisplayName: Joshua Carmody

OwnerDisplayName: Rex M