答:
Define TesT$Cell as a factor, and specify the order of the levels.

```<code>TesT$Cell <- factor(TesT$Cell, levels=myOrder)
</code>```

The plotting code doesn't need to change.

Title: Is there a way to use vectors to determine the order of x-axis labels and plot colours when using facet_wrap in ggplot2?

Body:
I would like to make 3 plots using facet_wrap, where I could set the order of the x-axis based on myOrder, and the colours based on myColours.
I have the following data.frame:

Cell <- c("AAA", "AAA", "AAA", "AAA", "AAA", "AAA", "AAA", "AAA", "AAA",
      "AAA", "ABB", "ABB", "ABB", "ABB", "ABB", "ABB", "ABB", "ABB",
      "ABB", "ABB", "ACB", "ACB", "ACB", "ACB", "ACB", "ACB", "ACB",
      "ACB", "ACB", "ACB", "BAA", "BAA", "BAA", "BAA", "BAA", "BAA",
      "BAA", "BAA", "BAA", "BAA", "BCA", "BCA", "BCA", "BCA", "BCA",
      "BCA", "BCA", "BCA", "BCA", "BCA", "BCC", "BCC", "BCC", "BCC",
      "BCC", "BCC", "BCC", "BCC", "BCC", "BCC", "CAA", "CAA", "CAA",
      "CAA", "CAA", "CAA", "CAA", "CAA", "CAA", "CAA", "CCC", "CCC",
      "CCC", "CCC", "CCC", "CCC", "CCC", "CCC", "CCC", "CCC", "CBA",
      "CBA", "CBA", "CBA", "CBA", "CBA", "CBA", "CBA", "CBA", "CBA")
Mean <- c(8, 11, 37, 3, 30, 8, 38, 50, 9, 31, 27, 41, 16,
      29, 4, 29, 28, 22, 48, 36, 13, 46, 21, 41, 38, 21,
      26, 27, 49, 4, 38, 44, 49, 48, 32, 3, 6, 25, 33,
      9, 9, 6, 8, 43, 21, 44, 41, 49, 32, 35, 40, 2, 41,
      34, 22, 12, 0, 21, 39, 30, 49, 26, 26, 39, 4, 13,
      18, 12, 9, 29, 24, 40, 38, 17, 40, 13, 30, 8, 9,
      11, 40, 19, 46, 6, 49, 38, 16, 1, 34, 22)
Type <- c("1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
      "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1",
      "1", "1", "1", "1", "1", "2", "2", "2", "2", "2", "2", "2", "2",
      "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2", "2",
      "2", "2", "2", "2", "2", "2", "2", "2", "2", "3", "3", "3", "3",
      "3", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3",
      "3", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3", "3")
TesT <- data.frame(Cell,Mean, Type)

I have been trying to plot these data using ggplot with the following code:

myOrder <- c("AAA", "ACB", "ABB", "BCA", "BAA", "BCC", "CBA", "CAA", "CCC")
myColours <- c("red", "blue", "green", "red", "blue", "green", rep("grey", 3))

ggplot(TesT, aes(x = Cell, y = Mean, fill = Cell)) +
  theme_bw() +
  stat_boxplot(geom = "errorbar") +
  geom_boxplot(colour = "black") +
  scale_x_discrete(breaks = myOrder, labels = myOrder) +
  scale_fill_manual(limits = myOrder, values = myColours) +
  facet_wrap(~Type, scales = "free_x") +
  scale_shape()

This is what I get:

My problem is that I do not manage to get the x-axis in the correct order (the order in myOrder).
The only way in which I managed to do this was by changing breaks to limits  (scale_x_discrete(limits = myOrder, labels = myOrder)). However, when I do this I get all the possible x categories in all the plots:

I have spent quite some time looking for an answer in here and in google but nothing seems to solve my problem. Does anyone have a suggestion?

Body:
Define TesT$Cell as a factor, and specify the order of the levels.

TesT$Cell <- factor(TesT$Cell, levels=myOrder)

The plotting code doesn't need to change.


来源: stackexchange

问:
How can I export the 'result' returned from a mysql query?
I am trying to use node js to place MySql data eventually in an HTML( really an ejs) page.

I have been using the code below from W3's node js examples. https://www.w3schools.com/nodejs/nodejs_mysql_select.asp

What I eventually would like to do is use module.exports on 'result', and be able to access the array in another file. I have been finding this difficult to accomplish.

```<code>var mysql = require('mysql');

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
});

// This is what is logged to the console.

// [ RowDataPacket { name: 'Company Inc', address: 'Highway 37' },
  RowDataPacket { name: 'Sanitation', address: 'Highway 27' },
  RowDataPacket { name: 'Ice Cream', address: 'Highway 11' } ]

// Above works but it doesn't do what I need it to.
// Below is explained what I need to happen.

var mysql = require('mysql');

var x; // x is undefined

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers",
    function (err, result, fields) {
    if (err) throw err;
    x = result; // If I do a 'console.log(x);' here I get the array above.
    // If try to 'module.exports = result;' here, it is
    // undefined in the receiving file. });
});

console.log(x); // x is undefined, even though result was stored in x.
</code>```

I would expect for the 'console.log(x);' at the bottom of the code to return the array, but it is undefined. This makes me think that anything in the 'con.query' is local. If that is the case, I considered using 'module. exports = result' in the function, but that also returns an undefined variable in the receiving file. If anyone knows why this happens, or if there is a solution, I would be very appreciative of your advice : )

答:
I got it to work! The problem was that my query was an async function, and I was expecting to get my data as if I were coding synchronously. Thank you for Cesar for your suggestion to use Promises, as that was what fixed my problem. Below is the now working code.

connection.js, also as suggested by Cesar.

```<code>    var mysql = require('mysql');

    var con = mysql.createConnection({
      host: "localhost",
      user: "username",
      password: "password",
      database: "testdb"
    });

    module.exports = con;
</code>```

The query.js page, now wrapped in a promise;

```<code>    var con = require('./connection.js');

    module.exports = new Promise(function(resolve, reject){
        con.connect(function(err) {
          if (err) throw err;
          con.query("SELECT * FROM customers", function (err, result, fields) {
            if (err) throw err;
              resolve(result);
          });
        });
    });
</code>```

app.js, which when accessed at port 3000, renders display.ejs with the db data

```<code>    var dataMod = require('./query.js');
    var express = require('express');

    var app = express();

    app.set('view engine', 'ejs');

    app.get('/', function(request, response){

      dataMod.then(function(data){
          response.render('display', {data: data});
      });

    });

    app.listen(3000);
</code>```

And the simple display.ejs page

```<code>    <!DOCTYPE html>
    <html>
      <body>
        <p> <%= data[0].name %> <%= data[0].address %></p>
        <p> <%= data[1].name %> <%= data[1].address %></p>
        <p> <%= data[2].name %> <%= data[2].address %></p>
      </body>
    </html>
</code>```

Which displays

Company Inc Highway 37

City Snitary Highway 27

Curbside treats middle of nowhere

on the browser!

This is just an example and is knowingly hard coded. What is the most important part, though, is the link from a database to browser using a promise. Thanks Cesar!

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use node js to place MySql data eventually in an HTML( really an ejs) page.

I have been using the code below from W3's node js examples. https://www.w3schools.com/nodejs/nodejs_mysql_select.asp

What I eventually would like to do is use module.exports on 'result', and be able to access the array in another file. I have been finding this difficult to accomplish.

var mysql = require('mysql');

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers", function (err, result, fields) {
    if (err) throw err;
    console.log(result);
});

// This is what is logged to the console.

// [ RowDataPacket { name: 'Company Inc', address: 'Highway 37' },
  RowDataPacket { name: 'Sanitation', address: 'Highway 27' },
  RowDataPacket { name: 'Ice Cream', address: 'Highway 11' } ]

// Above works but it doesn't do what I need it to.
// Below is explained what I need to happen.

var mysql = require('mysql');

var x; // x is undefined

var con = mysql.createConnection({
    host: "localhost",
    user: "username",
    password: "password",
    database: "testdb"
});

con.connect(function(err) {
    if (err) throw err;
    con.query("SELECT * FROM customers",
    function (err, result, fields) {
    if (err) throw err;
    x = result; // If I do a 'console.log(x);' here I get the array above.
    // If try to 'module.exports = result;' here, it is
    // undefined in the receiving file. });
});

console.log(x); // x is undefined, even though result was stored in x.

I would expect for the 'console.log(x);' at the bottom of the code to return the array, but it is undefined. This makes me think that anything in the 'con.query' is local. If that is the case, I considered using 'module. exports = result' in the function, but that also returns an undefined variable in the receiving file. If anyone knows why this happens, or if there is a solution, I would be very appreciative of your advice : )

Body:
I got it to work! The problem was that my query was an async function, and I was expecting to get my data as if I were coding synchronously. Thank you for Cesar for your suggestion to use Promises, as that was what fixed my problem. Below is the now working code.

connection.js, also as suggested by Cesar.

    var mysql = require('mysql');

    var con = mysql.createConnection({
      host: "localhost",
      user: "username",
      password: "password",
      database: "testdb"
    });

    module.exports = con;

The query.js page, now wrapped in a promise;

    var con = require('./connection.js');

    module.exports = new Promise(function(resolve, reject){
        con.connect(function(err) {
          if (err) throw err;
          con.query("SELECT * FROM customers", function (err, result, fields) {
            if (err) throw err;
              resolve(result);
          });
        });
    });

app.js, which when accessed at port 3000, renders display.ejs with the db data

    var dataMod = require('./query.js');
    var express = require('express');

    var app = express();

    app.set('view engine', 'ejs');

    app.get('/', function(request, response){

      dataMod.then(function(data){
          response.render('display', {data: data});
      });

    });

    app.listen(3000);

And the simple display.ejs page

    <!DOCTYPE html>
    <html>
      <body>
        <p> <%= data[0].name %> <%= data[0].address %></p>
        <p> <%= data[1].name %> <%= data[1].address %></p>
        <p> <%= data[2].name %> <%= data[2].address %></p>
      </body>
    </html>

Which displays

Company Inc Highway 37

City Snitary Highway 27

Curbside treats middle of nowhere

on the browser!

This is just an example and is knowingly hard coded. What is the most important part, though, is the link from a database to browser using a promise. Thanks Cesar!


问:
concurrency problems in interceptor tracking MDC
I have the following interceptor that tracks request/response based on saving and restoring some vars stored in MDC context for every request.

```<code>public class LoggingInterceptor implements DeferredResultProcessingInterceptor {
    private final HelloSeeYouLogger helloSeeYouLogger;
    private static final String X_UOW = "X-UOW";
    private static final String X_REQUEST_ID = "X-RequestId";
    private Map<String, String> context;

    public LoggingInterceptor(HelloSeeYouLogger helloSeeYouLogger) {
        this.helloSeeYouLogger = helloSeeYouLogger;
    }

    @Override
    public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) {
        addUowAndRequestIdToMDC(request.getHeader(X_UOW), request.getHeader(X_REQUEST_ID));
        final String uri = getUri((HttpServletRequest) request.getNativeRequest());
        helloSeeYouLogger.logHelloThere(uri);
        context = MDC.getCopyOfContextMap();
    }

    @Override
    public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) {
        if (context != null) {
            MDC.setContextMap(context);
        }
        final String uri = getUri((HttpServletRequest) request.getNativeRequest());
        String body = getBody((HttpServletRequest) request.getNativeRequest());
        if (!StringUtils.isEmpty(body)) {
            body = replaceMoreThanOneSpacesWithOneSpace(hideCreditCardNumber(body));
        }
        helloSeeYouLogger.logSeeYou(uri, body);
        clearUowAndRequestIdFromMDC();
    }

public static void addUowAndRequestIdToMDC(final String uow, final String requestId) {
        //This NewRelic stuff shouldn't be here as it is used for distributed tracing and not logging.
        // However it helps to levarage requests tracking from a metric service such as new relic to a log aggregation service
        //such as ELK.
        NewRelic.addCustomParameter(UOW, uow);
        NewRelic.addCustomParameter(REQUEST_ID, requestId);
        MDC.put(UOW, uow);
        MDC.put(REQUEST_ID, requestId);
    }

    public static void clearUowAndRequestIdFromMDC() {
        if (MDC.get(UOW) != null) {
            MDC.remove(UOW);
        }

        if (MDC.get(REQUEST_ID) != null) {
            MDC.remove(REQUEST_ID);
        }
    }
</code>```

I think i mn going to have concurrency problems as context is an instance variable and when running multiple concurrent thread saving and restoring MDC context will result in wrong results. Also using synchronize keyword will add performance problems.
I was wondering if there is a better approach to track MDC context when a spring controller returns a DeferredResult.

Thanks

答:
You can use try using HandlerInterceptorAdapter instead

Check: https://www.logicbig.com/how-to/code-snippets/jcode-spring-mvc-deferredresultprocessinginterceptor.html

Body:
I have the following interceptor that tracks request/response based on saving and restoring some vars stored in MDC context for every request.

public class LoggingInterceptor implements DeferredResultProcessingInterceptor {
    private final HelloSeeYouLogger helloSeeYouLogger;
    private static final String X_UOW = "X-UOW";
    private static final String X_REQUEST_ID = "X-RequestId";
    private Map<String, String> context;

    public LoggingInterceptor(HelloSeeYouLogger helloSeeYouLogger) {
        this.helloSeeYouLogger = helloSeeYouLogger;
    }

    @Override
    public <T> void beforeConcurrentHandling(NativeWebRequest request, DeferredResult<T> deferredResult) {
        addUowAndRequestIdToMDC(request.getHeader(X_UOW), request.getHeader(X_REQUEST_ID));
        final String uri = getUri((HttpServletRequest) request.getNativeRequest());
        helloSeeYouLogger.logHelloThere(uri);
        context = MDC.getCopyOfContextMap();
    }

    @Override
    public <T> void afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult) {
        if (context != null) {
            MDC.setContextMap(context);
        }
        final String uri = getUri((HttpServletRequest) request.getNativeRequest());
        String body = getBody((HttpServletRequest) request.getNativeRequest());
        if (!StringUtils.isEmpty(body)) {
            body = replaceMoreThanOneSpacesWithOneSpace(hideCreditCardNumber(body));
        }
        helloSeeYouLogger.logSeeYou(uri, body);
        clearUowAndRequestIdFromMDC();
    }

public static void addUowAndRequestIdToMDC(final String uow, final String requestId) {
        //This NewRelic stuff shouldn't be here as it is used for distributed tracing and not logging.
        // However it helps to levarage requests tracking from a metric service such as new relic to a log aggregation service
        //such as ELK.
        NewRelic.addCustomParameter(UOW, uow);
        NewRelic.addCustomParameter(REQUEST_ID, requestId);
        MDC.put(UOW, uow);
        MDC.put(REQUEST_ID, requestId);
    }

    public static void clearUowAndRequestIdFromMDC() {
        if (MDC.get(UOW) != null) {
            MDC.remove(UOW);
        }

        if (MDC.get(REQUEST_ID) != null) {
            MDC.remove(REQUEST_ID);
        }
    }

I think i mn going to have concurrency problems as context is an instance variable and when running multiple concurrent thread saving and restoring MDC context will result in wrong results. Also using synchronize keyword will add performance problems.
I was wondering if there is a better approach to track MDC context when a spring controller returns a DeferredResult.

Thanks


问:
How to conditionally append a data frame row to one above
I have a data frame that looks like this

```<code>   ID       Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456             NA    3116362
2 NA       NA    NA     C100ST                       NA    NA
3 66112599 37135 /26    S / ADR                      NA    1246880.3900000001
4 NA       NA    NA     65101599 / S0                NA    NA
5 45461599 37155 /O6    B / INR / REVERSE            NA    623440.19000000006
6 NA       NA    NA     UNDO / S0                    NA    NA
7 69876599 37134 /O3    N / ABC                   401.63   NA
8 19991099 37122 /O5    P / PDA / ASK 4265        401.65   NA
9 NA       NA    NA     AT045BT                      NA    NA
</code>```

I've been struggling to get this done but nothing I tried has worked. Basically what I want to do is if the ID value of a row is NA, I want to append the text in the Account column to the row above and then remove it.

I'm expecting the end result to look something like this:

```<code>   ID      Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456 / C100ST     NA    3116362
2 66112599 37135 /26    S / ADR / 65101599 / S0       NA    1246880.3900000001
3 45461599 37155 /O6    B / INR / REVERSE / UNDO / S0 NA    623440.19000000006
4 69876599 37134 /O3    N / ABC                       401.63   NA
5 19991099 37122 /O5    P / PDA / ASK 4265 / AT045BT  401.65   NA
</code>```

As you can see, the Row with ID value 69876599 remains the same as there was no other row immediately below it with a NA value for ID.

Does anyone know a way to deal with this?

答:
An option would be to fill the selected column to change the NA with the previous non-NA element, grouped by those columns, collapse the 'Account' by concatenating the elements to a single string, then summarise the rest of the 'Amount' columns to get the first non-NA element

```<code>library(tidyverse)
df1 %>%
   fill(ID, Date, Period) %>%
   group_by(ID, Date, Period) %>%
   group_by(Account = str_c(Account, collapse = ' / '), add = TRUE) %>%
   summarise_all(list(~ .[which(!is.na(.))[1]]))
# A tibble: 5 x 6
# Groups:   ID, Date, Period [5]
#        ID  Date Period Account                       Amount1  Amount2
#     <int> <int> <chr>  <chr>                           <dbl>    <dbl>
#1 19991099 37122 /O5    P / PDA / ASK 4265 / AT045BT     402.      NA
#2 45461599 37155 /O6    B / INR / REVERSE / UNDO / S0     NA   623440.
#3 66112599 37135 /26    S / ADR / 65101599 / S0           NA  1246880.
#4 69876599 37134 /O3    N / ABC                          402.      NA
#5 76311099 43494 /1     P / ABC / 123456 / C100ST         NA  3116362
</code>```

data

```<code>df1 <- structure(list(ID = c(76311099L, NA, 66112599L, NA, 45461599L,
NA, 69876599L, 19991099L, NA), Date = c(43494L, NA, 37135L, NA,
37155L, NA, 37134L, 37122L, NA), Period = c("/1", NA, "/26",
NA, "/O6", NA, "/O3", "/O5", NA), Account = c("P / ABC / 123456",
"C100ST", "S / ADR", "65101599 / S0", "B / INR / REVERSE", "UNDO / S0",
"N / ABC", "P / PDA / ASK 4265", "AT045BT"), Amount1 = c(NA,
NA, NA, NA, NA, NA, 401.63, 401.65, NA), Amount2 = c(3116362,
NA, 1246880.39, NA, 623440.19, NA, NA, NA, NA)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9"))
</code>```

Body:
I have a data frame that looks like this

   ID       Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456             NA    3116362
2 NA       NA    NA     C100ST                       NA    NA
3 66112599 37135 /26    S / ADR                      NA    1246880.3900000001
4 NA       NA    NA     65101599 / S0                NA    NA
5 45461599 37155 /O6    B / INR / REVERSE            NA    623440.19000000006
6 NA       NA    NA     UNDO / S0                    NA    NA
7 69876599 37134 /O3    N / ABC                   401.63   NA
8 19991099 37122 /O5    P / PDA / ASK 4265        401.65   NA
9 NA       NA    NA     AT045BT                      NA    NA

I've been struggling to get this done but nothing I tried has worked. Basically what I want to do is if the ID value of a row is NA, I want to append the text in the Account column to the row above and then remove it.

I'm expecting the end result to look something like this:

   ID      Date  Period Account                      Amount1 Amount2
  <chr>    <chr> <chr>  <chr>                        <chr> <chr>
1 76311099 43494 /1     P / ABC / 123456 / C100ST     NA    3116362
2 66112599 37135 /26    S / ADR / 65101599 / S0       NA    1246880.3900000001
3 45461599 37155 /O6    B / INR / REVERSE / UNDO / S0 NA    623440.19000000006
4 69876599 37134 /O3    N / ABC                       401.63   NA
5 19991099 37122 /O5    P / PDA / ASK 4265 / AT045BT  401.65   NA

As you can see, the Row with ID value 69876599 remains the same as there was no other row immediately below it with a NA value for ID.

Does anyone know a way to deal with this?

Body:
An option would be to fill the selected column to change the NA with the previous non-NA element, grouped by those columns, collapse the 'Account' by concatenating the elements to a single string, then summarise the rest of the 'Amount' columns to get the first non-NA element

library(tidyverse)
df1 %>%
   fill(ID, Date, Period) %>%
   group_by(ID, Date, Period) %>%
   group_by(Account = str_c(Account, collapse = ' / '), add = TRUE) %>%
   summarise_all(list(~ .[which(!is.na(.))[1]]))
# A tibble: 5 x 6
# Groups:   ID, Date, Period [5]
#        ID  Date Period Account                       Amount1  Amount2
#     <int> <int> <chr>  <chr>                           <dbl>    <dbl>
#1 19991099 37122 /O5    P / PDA / ASK 4265 / AT045BT     402.      NA
#2 45461599 37155 /O6    B / INR / REVERSE / UNDO / S0     NA   623440.
#3 66112599 37135 /26    S / ADR / 65101599 / S0           NA  1246880.
#4 69876599 37134 /O3    N / ABC                          402.      NA
#5 76311099 43494 /1     P / ABC / 123456 / C100ST         NA  3116362

data

df1 <- structure(list(ID = c(76311099L, NA, 66112599L, NA, 45461599L,
NA, 69876599L, 19991099L, NA), Date = c(43494L, NA, 37135L, NA,
37155L, NA, 37134L, 37122L, NA), Period = c("/1", NA, "/26",
NA, "/O6", NA, "/O3", "/O5", NA), Account = c("P / ABC / 123456",
"C100ST", "S / ADR", "65101599 / S0", "B / INR / REVERSE", "UNDO / S0",
"N / ABC", "P / PDA / ASK 4265", "AT045BT"), Amount1 = c(NA,
NA, NA, NA, NA, NA, 401.63, 401.65, NA), Amount2 = c(3116362,
NA, 1246880.39, NA, 623440.19, NA, NA, NA, NA)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9"))


问:
C# autostart automatically add application to startup folder
Is it possible that C# autostart automatically add application to startup folder. Now i can download and install C# application with autostart but application is not srated automatically when i restart windows. How to do that?</p>

答:
You can use it :</p>

```<code>RegistryKey rkey =
    Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rkey.SetValue("YourApplicationName", Application.ExecutablePath);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You can use it :

RegistryKey rkey =
    Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
rkey.SetValue("YourApplicationName", Application.ExecutablePath);

ContentLicense: CC BY-SA 3.0


问:
Why can't docker build COPY files to the /dev folder?
I want to create a docker image where I add a file to the /dev folder. I'm using this Dockerfile:

```<code>FROM ubuntu:bionic
COPY test.txt /dev/
</code>```

After building this with:

```<code>docker build -t test .
</code>```

I get a docker image where nothing has been added to the /dev folder. No error has been thrown by docker build.

I find this very strange because copying to different folders works fine. For example

COPY test.txt /

COPY test.txt /root/

COPY test.txt /home/

all work fine.

Does the /dev folder have some special permissions? How do I copy a file to the /dev folder?

I'm using Docker Toolbox on windows.

答:
/dev is a special folder on linux systems reserved to maintain the devices related ressources (filesystem, disks, etc...) and mounted on a special filesystem. In a docker container, it will be remounted with a tmpfs dedicated filesystem and is not on the main container filesystem (/). See the following example:

$ docker run -it --rm ubuntu:18.04
root@17b9ad96ccbc:/# df -h /dev/
Filesystem      Size  Used Avail Use% Mounted on
tmpfs            64M     0   64M   0% /dev
```

In your case, your file was actually copied during the build but in a temporary filesystem that died as soon as the build was finished.

Conclusion: don't use /dev as a destination, choose an other folder.

Body:
I want to create a docker image where I add a file to the /dev folder. I'm using this Dockerfile:

FROM ubuntu:bionic
COPY test.txt /dev/

After building this with:

docker build -t test .

I get a docker image where nothing has been added to the /dev folder. No error has been thrown by docker build.

I find this very strange because copying to different folders works fine. For example

COPY test.txt /

COPY test.txt /root/

COPY test.txt /home/

all work fine.

Does the /dev folder have some special permissions? How do I copy a file to the /dev folder?

I'm using Docker Toolbox on windows.

Body:
/dev is a special folder on linux systems reserved to maintain the devices related ressources (filesystem, disks, etc...) and mounted on a special filesystem. In a docker container, it will be remounted with a tmpfs dedicated filesystem and is not on the main container filesystem (/). See the following example:

$ docker run -it --rm ubuntu:18.04
root@17b9ad96ccbc:/# df -h /dev/
Filesystem      Size  Used Avail Use% Mounted on
tmpfs            64M     0   64M   0% /dev

In your case, your file was actually copied during the build but in a temporary filesystem that died as soon as the build was finished.

Conclusion: don't use /dev as a destination, choose an other folder.


问:
Can I import Python's 3.6's formatted string literals (f-strings) into older 3.x, 2.x Python?
The new Python 3.6 f-strings seem like a huge jump in string usability to me, and I would love to jump in and adopt them whole heartedly on new projects which might be running on older interpreters. 2.7, 3.3-3.5 support would be great but at the very least I would like to use these in Python 3.5 code bases. How can I import 3.6's formatted string literals for use by older interpreters?

I understand that formatted string literals like f"Foo is {age} {units} old" are not breaking changes, so would not be included in a from __future__ import ... call. But the change is not back-ported (AFAIK) I would need to be sure that whatever new code I write with f-strings is only ran on Python 3.6+ which is a deal breaker for a lot of projects.

答:
A dirty solution using simpleeval

```<code>import re
import simpleeval
test='_someString'
lst = ['_456']

s = '123123{lst[0]}{test}'

def template__format(template, context=None):
    if context is None:
        frame = inspect.currentframe()
        context = frame.f_back.f_locals
        del frame
    ptn =  '([^{]?){([^}]+)}'
    class counter():
        i = -1

    def count(m):
        counter.i += 1
        return m.expand('\\1{%d}'%counter.i)

    template = re.sub(ptn,string=s, repl= count)
    exprs = [x[1] for x in re.findall(ptn,s)]
    vals = map(simpleeval.SimpleEval(names=context).eval,exprs)
    res = template.format(*vals)
    return res

print (template__format(s))

</code>```

Body:
A dirty solution using simpleeval

import re
import simpleeval
test='_someString'
lst = ['_456']

s = '123123{lst[0]}{test}'

def template__format(template, context=None):
    if context is None:
        frame = inspect.currentframe()
        context = frame.f_back.f_locals
        del frame
    ptn =  '([^{]?){([^}]+)}'
    class counter():
        i = -1

    def count(m):
        counter.i += 1
        return m.expand('\\1{%d}'%counter.i)

    template = re.sub(ptn,string=s, repl= count)
    exprs = [x[1] for x in re.findall(ptn,s)]
    vals = map(simpleeval.SimpleEval(names=context).eval,exprs)
    res = template.format(*vals)
    return res

print (template__format(s))


问:
Multi line card carousel card for Vuetify
How can I achieve the multi card inside carousel similar to this Demo in Vuetify

```<code><v-carousel>
  <v-carousel-item
  v-for="(item,i) in items"
  :key="i"
  :src="item.src">
    <card></card> // card will be here
  </v-carousel-item>
</v-carousel>
</code>```

I would like to show 6 cards per slide, 3 columns and 2 rows. Or if there are any plugins available

答:
You need two "v-for", the first with limit 2, second with limit 6. And if you want 2 rows look the vuetify official documentation grid system documentation

Try this, it is without style of your example

```<code><v-flex>
  <v-carousel hide-delimiters style="box-shadow: 0px 0px">
    <v-carousel-item v-for="i in 2" :key="i">
      <v-layout row>
        <v-flex sm4 v-for="j in 6" :key="j" pl-2 pr-2>
          <v-card>
            <v-img
              src="https://cdn.vuetifyjs.com/images/cards/desert.jpg"
              aspect-ratio="0.8"
            ></v-img>
            <v-card-title primary-title>
              <div>
                <h3 class="headline mb-0">Card {{i}}-{{j}}</h3>
                <div> Card text </div>
              </div>
            </v-card-title>
          </v-card>
        </v-flex>
      </v-layout>
    </v-carousel-item>
  </v-carousel>
</v-flex>
</code>```

Body:
How can I achieve the multi card inside carousel similar to this Demo in Vuetify

<v-carousel>
  <v-carousel-item
  v-for="(item,i) in items"
  :key="i"
  :src="item.src">
    <card></card> // card will be here
  </v-carousel-item>
</v-carousel>

I would like to show 6 cards per slide, 3 columns and 2 rows. Or if there are any plugins available

Body:
You need two "v-for", the first with limit 2, second with limit 6. And if you want 2 rows look the vuetify official documentation grid system documentation

Try this, it is without style of your example

<v-flex>
  <v-carousel hide-delimiters style="box-shadow: 0px 0px">
    <v-carousel-item v-for="i in 2" :key="i">
      <v-layout row>
        <v-flex sm4 v-for="j in 6" :key="j" pl-2 pr-2>
          <v-card>
            <v-img
              src="https://cdn.vuetifyjs.com/images/cards/desert.jpg"
              aspect-ratio="0.8"
            ></v-img>
            <v-card-title primary-title>
              <div>
                <h3 class="headline mb-0">Card {{i}}-{{j}}</h3>
                <div> Card text </div>
              </div>
            </v-card-title>
          </v-card>
        </v-flex>
      </v-layout>
    </v-carousel-item>
  </v-carousel>
</v-flex>


问:
How do I delete Azure Databricks workspace via script
Is posible to delete An Azure Databricks workspace via Script. I´m trying to build my resources via script with ARM, and also i´m doing the same with resource deletion with powershell scripting.

I could´n find the powershell command to delete a databricks workspace, like others :

Remove-AzureRmNetworkSecurityGroup

Remove-AzureRmVirtualNetwork

Remove-AzureRmDataFactoryV2

Are there any alternatives to delete resources via scripting.

Thanks in advance.

答:
I have found the solution to delete a resource in powershell, use this command

```<code>Remove-AzureRmResource -ResourceGroupName $ResourceGroup -ResourceName $DatabricksWorkspaceName -ResourceType Microsoft.Databricks/workspaces -Force
</code>```

where:

$ResourceGroup is the resource group where your databricks resource is.

$DatabricksWorkspaceName is the name of your databricks resource.

Also You can use to delete other types of resources adapting the syntax.

Body:
I have found the solution to delete a resource in powershell, use this command

Remove-AzureRmResource -ResourceGroupName $ResourceGroup -ResourceName $DatabricksWorkspaceName -ResourceType Microsoft.Databricks/workspaces -Force

where:

$ResourceGroup is the resource group where your databricks resource is.

$DatabricksWorkspaceName is the name of your databricks resource.

Also You can use to delete other types of resources adapting the syntax.


问:
Alter partition table with 60 million rows of data performance issue
I am trying to partition a table with 60 million rows of data based on year.

Specifications:
 MySQL 5.7.1
OS : windows

```<code>ALTER TABLE full_data PARTITION BY RANGE (YEAR(ProcessDate))(
    PARTITION years VALUES LESS THAN (2019)
 ) ;
</code>```

For the past one day, the process is running. Could you please help me to improve the performance.

```<code>CREATE TABLE full_data` (
    Mobile bigint(11) DEFAULT NULL,
    Name varchar(200) DEFAULT NULL,
    Barcode varchar(200) DEFAULT NULL,
    Batch varchar(200) DEFAULT NULL,
    Carton varchar(500) DEFAULT NULL,
    Doctype varchar(500) DEFAULT NULL,
    Rack varchar(500) DEFAULT NULL,
    ProcessDate datetime DEFAULT NULL,
    KEY Mobile (Mobile,Barcode),
    KEY MobileBarcode (Mobile,Barcode)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; '
</code>```

答:
Such an ALTER will take hours to copy all the data from the existing table into a temp table, then swap it into place.  Disk I/O is taking the time.

But why do that partitioning?  Only in rare cases will it provide any performance benefit.  How many years do you have?  What queries do you run against the table?  Please provide SHOW CREATE TABLE.

If you are having performance problems, let's start with EXPLAIN SELECT ...

Body:
I am trying to partition a table with 60 million rows of data based on year.

Specifications:
 MySQL 5.7.1
OS : windows

ALTER TABLE full_data PARTITION BY RANGE (YEAR(ProcessDate))(
    PARTITION years VALUES LESS THAN (2019)
 ) ;

For the past one day, the process is running. Could you please help me to improve the performance.

CREATE TABLE full_data` (
    Mobile bigint(11) DEFAULT NULL,
    Name varchar(200) DEFAULT NULL,
    Barcode varchar(200) DEFAULT NULL,
    Batch varchar(200) DEFAULT NULL,
    Carton varchar(500) DEFAULT NULL,
    Doctype varchar(500) DEFAULT NULL,
    Rack varchar(500) DEFAULT NULL,
    ProcessDate datetime DEFAULT NULL,
    KEY Mobile (Mobile,Barcode),
    KEY MobileBarcode (Mobile,Barcode)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; '


问:
Store file data in variable Javascript
I am trying to save the content of a file to a variable using a stream. However, the scope of the variable is not accesible from outside the function.

```<code>var data = '';
var fileContent = '';
var reader = fs.createReadStream(filePath);
reader.setEncoding('UTF8');

reader.on('data', function(chunk) {
   data += chunk;
});

reader.on('end', function() {
   fileContent = data;
});

return fileContent;
</code>```

I tried to return the value inside the function but it is not returning the expected thing.

答:
What do want to do ist reading the file synchronously. fs has special mothods for this. For example readFileSync(). What you try to do is reading it as a stream, but the object which you are returning immeadialty is still empty when you do this. It will eentually populated later, when the stream is processed.

So go for sync methods or write your code for streams or asnyc processing.

Title: Store file data in variable Javascript

Body:
I am trying to save the content of a file to a variable using a stream. However, the scope of the variable is not accesible from outside the function.

var data = '';
var fileContent = '';
var reader = fs.createReadStream(filePath);
reader.setEncoding('UTF8');

reader.on('data', function(chunk) {
   data += chunk;
});

reader.on('end', function() {
   fileContent = data;
});

return fileContent;

I tried to return the value inside the function but it is not returning the expected thing.


问:
How to get abstract user first_name and last_name and how to update it
```<code># models.py

class User(AbstractUser):
   `` id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Employee(models.Model):
    employee = models.OneToOneField(User, on_delete=models.CASCADE)
     reporting_manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='reporting_managers',
                                          null=True, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_join = models.DateField(null=True, blank=True)
    date_of_exit = models.DateField(null=True, blank=True)
</code>```

I want here first_name and last_name from Abstract user and that should be also updatable. Help me out this issue.

```<code># views.py

class EmployeeUpdateView(UpdateView):

"""
For updating profile of each employee :update view
"""

model = Employee

fields = ('reporting_manager','date_of_birth','date_of_join','gender','address','photo',\
          'department','employee_code','blood_group','designation','phone_no','personal_email_id','official_email_id',\
          'email_domain','city','allowed_apps')

template_name = "registration/update_employee.html"
</code>```

答:
In html i created explicitly first name and last name inputs for
  this i added

```<code><input type="text" name="first_name" value="{{ employee.employee.first_name }}" ><br>
</code>```

Body:
# models.py

class User(AbstractUser):
   `` id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

class Employee(models.Model):
    employee = models.OneToOneField(User, on_delete=models.CASCADE)
     reporting_manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='reporting_managers',
                                          null=True, blank=True)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_join = models.DateField(null=True, blank=True)
    date_of_exit = models.DateField(null=True, blank=True)

I want here first_name and last_name from Abstract user and that should be also updatable. Help me out this issue.

# views.py

class EmployeeUpdateView(UpdateView):

"""
For updating profile of each employee :update view
"""

model = Employee

fields = ('reporting_manager','date_of_birth','date_of_join','gender','address','photo',\
          'department','employee_code','blood_group','designation','phone_no','personal_email_id','official_email_id',\
          'email_domain','city','allowed_apps')

template_name = "registration/update_employee.html"

Body:
In html i created explicitly first name and last name inputs for
  this i added

<input type="text" name="first_name" value="{{ employee.employee.first_name }}" ><br>


问:
How to get text input like function on kivy?
I'm not sure how to approach the below in terms of kivy. Rather than using the command prompt to get the input values, I want to use kivy to get the input values. I would be grateful if you could help me with it. For example, the first line asks a question to the user. The user answers it and that information is tide upto a variable which I'm able to use for manipulation. </p>

```<code>    def coord(d):
        while True:
            deforchan = input('Use default(d) coordinates or change(c) in page %s: ' %d)
            if deforchan == 'd':
                x1, y1, x2, y2 = '700','800','1140','200'
                i = table_foo(x1, y1, x2, y2,d)
                break
            elif deforchan == 'c':
                print('Enter (0,0) coordinate: ')
                x1, y1 = input('x_coordinate: '), input('y_coordinate: ')
                print('Enter (0,0) coordinate:')
                x2, y2 = input('x_coordinate: '), input('y_coordinate: ')
                x1 = str(x1)
                y1 = str(850-int(y1))
                x2 = str(x2)
                y2 = str(850-int(y2))
                print(x1, y1, x2, y2,d)
                i = table_foo(x1, y1, x2, y2,d)
                break
            else:
                print('Oops! Try Again')

        return x1, y1, x2, y2, d

    def final():
    #     pdfname = 'example2.pdf'
    #     nofpages = len(PdfReader(pdfname).pages)
        for d in range(1, int(nofpages)+1):
            x1, y1, x2, y2, d = coord(d)

            while True:
                add_tables = input('Any additional tables in page %s? (y or n) ' %d)
                if add_tables == 'y':
                    x1, y1, x2, y2, d = coord(d)
                elif add_tables == 'n':
                    break
                else:
                    print('Oops! Try Again')
</code>```

答:
Use Kivy widgets such as BoxLayout, GridLayout, Label, TextInput and Button to display the default values and wait for use to either override the default values or enter new values.

main.py

```<code>from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<Demo>:
    orientation: 'vertical'

    GridLayout:
        cols: 3
        Label:
            text: 'Enter (0,0) coordinate:'
        TextInput:
            id: x1
            hint_text: 'x1 coordinate'
            text: '700'
        TextInput:
            id: y1
            hint_text: 'y1 coordinate'
            text: '800'
        Label:
            text: 'Enter (0,0) coordinate:'
        TextInput:
            id: x2
            hint_text: 'x2 coordinate'
            text: '1140'
        TextInput:
            id: y2
            hint_text: 'y2 coordinate'
            text: '200'

    Button:
        text: 'Submit'
        on_release: app.root.coordinates(x1.text, y1.text, x2.text, y2.text)

""")

class Demo(BoxLayout):

    def coordinates(self, x1, y1, x2, y2):
        print(f"x1={x1}, y1={y1}, x2={x2}, y2={y2}")

class TestApp(App):

    def build(self):
        return Demo()

if __name__ == "__main__":
    TestApp().run()
</code>```

Output

Body:
I'm not sure how to approach the below in terms of kivy. Rather than using the command prompt to get the input values, I want to use kivy to get the input values. I would be grateful if you could help me with it. For example, the first line asks a question to the user. The user answers it and that information is tide upto a variable which I'm able to use for manipulation.

    def coord(d):
        while True:
            deforchan = input('Use default(d) coordinates or change(c) in page %s: ' %d)
            if deforchan == 'd':
                x1, y1, x2, y2 = '700','800','1140','200'
                i = table_foo(x1, y1, x2, y2,d)
                break
            elif deforchan == 'c':
                print('Enter (0,0) coordinate: ')
                x1, y1 = input('x_coordinate: '), input('y_coordinate: ')
                print('Enter (0,0) coordinate:')
                x2, y2 = input('x_coordinate: '), input('y_coordinate: ')
                x1 = str(x1)
                y1 = str(850-int(y1))
                x2 = str(x2)
                y2 = str(850-int(y2))
                print(x1, y1, x2, y2,d)
                i = table_foo(x1, y1, x2, y2,d)
                break
            else:
                print('Oops! Try Again')

        return x1, y1, x2, y2, d

    def final():
    #     pdfname = 'example2.pdf'
    #     nofpages = len(PdfReader(pdfname).pages)
        for d in range(1, int(nofpages)+1):
            x1, y1, x2, y2, d = coord(d)

            while True:
                add_tables = input('Any additional tables in page %s? (y or n) ' %d)
                if add_tables == 'y':
                    x1, y1, x2, y2, d = coord(d)
                elif add_tables == 'n':
                    break
                else:
                    print('Oops! Try Again')

Body:
Use Kivy widgets such as BoxLayout, GridLayout, Label, TextInput and Button to display the default values and wait for use to either override the default values or enter new values.

main.py

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string("""
<Demo>:
    orientation: 'vertical'

    GridLayout:
        cols: 3
        Label:
            text: 'Enter (0,0) coordinate:'
        TextInput:
            id: x1
            hint_text: 'x1 coordinate'
            text: '700'
        TextInput:
            id: y1
            hint_text: 'y1 coordinate'
            text: '800'
        Label:
            text: 'Enter (0,0) coordinate:'
        TextInput:
            id: x2
            hint_text: 'x2 coordinate'
            text: '1140'
        TextInput:
            id: y2
            hint_text: 'y2 coordinate'
            text: '200'

    Button:
        text: 'Submit'
        on_release: app.root.coordinates(x1.text, y1.text, x2.text, y2.text)

""")

class Demo(BoxLayout):

    def coordinates(self, x1, y1, x2, y2):
        print(f"x1={x1}, y1={y1}, x2={x2}, y2={y2}")

class TestApp(App):

    def build(self):
        return Demo()

if __name__ == "__main__":
    TestApp().run()

Output


问:
Mulesoft Amazon connector security
I am using Anypoint Studio 7.3, Mule 4.1.5 and Amazon S3 connector 5.2

When I configure the Amazon S3 connector I have to set the access key and secret key.  My query is what other security is there around this connection e.g. how is the connection encrypted?  Is it safe for sensitive data?

Thanks

答:
As the documentation states, it uses the AWS APIs and the AWS SDK for Java. So it uses the security mechanisms provided by Amazon themselves.

https://docs.mulesoft.com/connectors/amazon/amazon-s3-connector

Title: Mulesoft Amazon connector security


问:
Why is `'\t\n ' == false` in JavaScript?
In JavaScript...

```<code>'\t\n ' == false // true
</code>```

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

答:
I think the process can be described in a recursive function. (Imagining we live in a world where JavaScript only has the strict equality operator.)

```<code>function equals(x, y) {
    if (typeof y === "boolean") {
        return equals(x, +y);
    }
    else if (typeof x === "string") {
        return +x === y;
    }
}
</code>```

A StringNumericLiteral that is empty or contains only white space is converted to +0.

Body:
In JavaScript...

'\t\n ' == false // true

I can assume that any string that consists solely of whitespace characters is considered equal to false in JavaScript.

According to this article, I figured that false would be converted to 0, but was unable to find mention of whitespace considered equal to false using Google.

Why is this? Is there some good reading on the subject besides digging into the ECMAScript spec?

Body:
I think the process can be described in a recursive function. (Imagining we live in a world where JavaScript only has the strict equality operator.)

function equals(x, y) {
    if (typeof y === "boolean") {
        return equals(x, +y);
    }
    else if (typeof x === "string") {
        return +x === y;
    }
}

A StringNumericLiteral that is empty or contains only white space is converted to +0.


问:
Update an object Property based on other properties
I am trying to update a property based on value from 2 other properties.

I am using INotifyPropertyChanged here.

So basically I have 3 properties A, B and C. The property I am updating is C here based on A and B. I am able to update property value of C from A and B. So property C will be an addition of property A and B (C = A + B). It works fine when one value is passed from either A or B but when values from both properties are passed it only takes in value from the last property value passed. I know I need to increment the value of C when value from each property is passed. But what is the best way to achieve this?

Here is my code:

```<code>private int? _a;
public int? A
{
   get => _a;
   set
   {
       _a = value;
       OnPropertyChanged($"A");
       C = _a;
   }
 }

private int? _b;
public int? B
{
    get => _b;
    set
    {
       _b = value;
       OnPropertyChanged($"B");
       C = _b;
    }
 }

 private int? _c;
 public int? C
 {
    get => _c;
    set
    {
       _c = value;
    }
 }

 public event PropertyChangedEventHandler PropertyChanged;

 [NotifyPropertyChangedInvocator]
 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }
</code>```

Update

Sorry for the confusion above, basically I am trying to update the value of property C when property A and B are passed through. So property C will be an addition of property A and B (C = A + B). Hope this clears the confusion?

答:
Given the above clarification, what you'd do is something like:</p>

```<code>private int? _a;
public int? A
{
   get => _a;
   set
   {
       if (value.HasValue != _a.HasValue || value.GetValueOrDefault(0) != _a.GetValueOrDefault(0))
       {
          _a = value;
          OnPropertyChanged();
          OnPropertyChanged(nameof(C));
       }
   }
 }

private int? _b;
public int? B
{
    get => _b;
    set
    {
       if (value.HasValue != _b.HasValue || value.GetValueOrDefault(0) != _b.GetValueOrDefault(0))
       {
          _a = value;
          OnPropertyChanged();
          OnPropertyChanged(nameof(C));
       }
    }
 }

 public int? C
 {
    get => A + B;
 }

 public event PropertyChangedEventHandler PropertyChanged;

 [NotifyPropertyChangedInvocator]
 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }
</code>```

Body:
I am trying to update a property based on value from 2 other properties.

I am using INotifyPropertyChanged here.

So basically I have 3 properties A, B and C. The property I am updating is C here based on A and B. I am able to update property value of C from A and B. So property C will be an addition of property A and B (C = A + B). It works fine when one value is passed from either A or B but when values from both properties are passed it only takes in value from the last property value passed. I know I need to increment the value of C when value from each property is passed. But what is the best way to achieve this?

Here is my code:

private int? _a;
public int? A
{
   get => _a;
   set
   {
       _a = value;
       OnPropertyChanged($"A");
       C = _a;
   }
 }

private int? _b;
public int? B
{
    get => _b;
    set
    {
       _b = value;
       OnPropertyChanged($"B");
       C = _b;
    }
 }

 private int? _c;
 public int? C
 {
    get => _c;
    set
    {
       _c = value;
    }
 }

 public event PropertyChangedEventHandler PropertyChanged;

 [NotifyPropertyChangedInvocator]
 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }

Update

Sorry for the confusion above, basically I am trying to update the value of property C when property A and B are passed through. So property C will be an addition of property A and B (C = A + B). Hope this clears the confusion?

Body:
Given the above clarification, what you'd do is something like:

private int? _a;
public int? A
{
   get => _a;
   set
   {
       if (value.HasValue != _a.HasValue || value.GetValueOrDefault(0) != _a.GetValueOrDefault(0))
       {
          _a = value;
          OnPropertyChanged();
          OnPropertyChanged(nameof(C));
       }
   }
 }

private int? _b;
public int? B
{
    get => _b;
    set
    {
       if (value.HasValue != _b.HasValue || value.GetValueOrDefault(0) != _b.GetValueOrDefault(0))
       {
          _a = value;
          OnPropertyChanged();
          OnPropertyChanged(nameof(C));
       }
    }
 }

 public int? C
 {
    get => A + B;
 }

 public event PropertyChangedEventHandler PropertyChanged;

 [NotifyPropertyChangedInvocator]
 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }


问:
Using the ASP.NET OAuth providers without ASP.NET Identity
My project is using asp.net membership (not Identity), I am trying to implement the OAuth based on the steps listed at this link

While testing the code, it created the identity tables at my database (AspNetUsers, AspNetUserRoles, AspNetRoles...)

I don't want to use these tables, I want to use it with the membership tables (aspnet_Users, aspnet_Membership...)

```<code>public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var applicationUserManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    //while executing this line, the identity tables are created
    var applicationUser = await applicationUserManager.FindAsync(context.UserName, context.Password);
    if (applicationUser == null)
    {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return;
    }

    var claimsIdentityOAuth =
            await applicationUser.GenerateUserIdentityAsync(applicationUserManager,
                OAuthDefaults.AuthenticationType);
    var claimsIdentityCookie = await applicationUser.GenerateUserIdentityAsync(applicationUserManager,
    CookieAuthenticationDefaults.AuthenticationType);
    var properties = CreateProperties(applicationUser.UserName);
    var authenticationTicket = new AuthenticationTicket(claimsIdentityOAuth, properties);
    context.Validated(authenticationTicket);
    context.Request.Context.Authentication.SignIn(claimsIdentityCookie);
}
</code>```

How to use OAuth with asp.net membership?

答:
You could do that but, you need a custom implementation of Identity tables and then do a map for your desired tables using Entity Framework Code First

Custom Storage Providers for ASP.NET Identity

```<code> protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>().ToTable("YouUserTableMembership");
        modelBuilder.Entity<ApplicationUser>().ToTable("YouUserTableMembership");

        modelBuilder.Entity<IdentityRole>().ToTable("role");
        modelBuilder.Entity<IdentityUserRole>().ToTable("YouUserRoleTableMembership");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("YouUserClaimTableMembership");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("YouUserLoginTableMembership");
    }
</code>```

Body:
My project is using asp.net membership (not Identity), I am trying to implement the OAuth based on the steps listed at this link

While testing the code, it created the identity tables at my database (AspNetUsers, AspNetUserRoles, AspNetRoles...)

I don't want to use these tables, I want to use it with the membership tables (aspnet_Users, aspnet_Membership...)

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    var applicationUserManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    //while executing this line, the identity tables are created
    var applicationUser = await applicationUserManager.FindAsync(context.UserName, context.Password);
    if (applicationUser == null)
    {
        context.SetError("invalid_grant", "The user name or password is incorrect.");
        return;
    }

    var claimsIdentityOAuth =
            await applicationUser.GenerateUserIdentityAsync(applicationUserManager,
                OAuthDefaults.AuthenticationType);
    var claimsIdentityCookie = await applicationUser.GenerateUserIdentityAsync(applicationUserManager,
    CookieAuthenticationDefaults.AuthenticationType);
    var properties = CreateProperties(applicationUser.UserName);
    var authenticationTicket = new AuthenticationTicket(claimsIdentityOAuth, properties);
    context.Validated(authenticationTicket);
    context.Request.Context.Authentication.SignIn(claimsIdentityCookie);
}

How to use OAuth with asp.net membership?

Body:
You could do that but, you need a custom implementation of Identity tables and then do a map for your desired tables using Entity Framework Code First

Custom Storage Providers for ASP.NET Identity

 protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>().ToTable("YouUserTableMembership");
        modelBuilder.Entity<ApplicationUser>().ToTable("YouUserTableMembership");

        modelBuilder.Entity<IdentityRole>().ToTable("role");
        modelBuilder.Entity<IdentityUserRole>().ToTable("YouUserRoleTableMembership");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("YouUserClaimTableMembership");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("YouUserLoginTableMembership");
    }


问:
WSO2 enterprise integrator - datasource
do you know where is save settings about datasource from wso2 EI?
i create datasource on GUI in wso2 but I can't find record on server.
Thanks</p>

答:
The data sources added from the Management console UI is saved to the registry under /_system/config/repository/components/org.wso2.carbon.ndatasource registry path. You can navigate to the registry path from management console UI and you can download the data source definition created from there.
registry path

If you need to add data source definitions from the file system you can create a file with format {any_name}-datasources.xml and put the data source configurations and save it under {SERVER_HOME}/conf/datasources

Title: WSO2 enterprise integrator - datasource


问:
what class is returned after a delete action in rails
I am using rails-ujs to delete an object,
my goal is to hide that div wit that obj after i delete it, i've done it before, but i cant get it this time, i think i need to know whats going on.
on view:

```<code><div class="employee_<%= employee.id %>"
<%= link_to 'Destroy', employee, method: :delete, remote: true } %>
</div
</code>```

on destroy.js.erb:

```<code>$('div.each-employee-data').find('div.employee_<%= @employee.id %>').hide(); # if i change the id to employee.id i get another error
</code>```

controller:

```<code>format js
</code>```

console error:

```<code>NoMethodError in Employees#destroy

Showing
/Desktop/bad/current/app/views/employees/destroy.js.erb where line #1
raised:
undefined method `id' for nil:NilClass

Rails.root: /Desktop/bad/current

Application Trace
app/views/employees/destroy.js.erb:1:in
`_app_views_employees_destroy_js_erb__4462192751889852231_70177039108760'
</code>```

答:
Once you've destroyed a record - you should no longer use it, and it no longer have an id. For your case you can save the id prior to deleting in controller:

@deleted_employee_id = @employee.id
@employee.destroy
...
```

and in js view ...find('div.employee_<%= @deleted_employee_id %>').hide()...

PS. Also it's common practice to use "soft deletes" - have a flag in model that indicates if the record was "deleted" and set it in destroy action, without actual delete, this is useful, if a user would want to "undo".

Body:
I am using rails-ujs to delete an object,
my goal is to hide that div wit that obj after i delete it, i've done it before, but i cant get it this time, i think i need to know whats going on.
on view:

<div class="employee_<%= employee.id %>"
<%= link_to 'Destroy', employee, method: :delete, remote: true } %>
</div

on destroy.js.erb:

$('div.each-employee-data').find('div.employee_<%= @employee.id %>').hide(); # if i change the id to employee.id i get another error

controller:

format js

console error:

NoMethodError in Employees#destroy

Showing
/Desktop/bad/current/app/views/employees/destroy.js.erb where line #1
raised:
undefined method `id' for nil:NilClass

Rails.root: /Desktop/bad/current

Application Trace
app/views/employees/destroy.js.erb:1:in
`_app_views_employees_destroy_js_erb__4462192751889852231_70177039108760'

Body:
Once you've destroyed a record - you should no longer use it, and it no longer have an id. For your case you can save the id prior to deleting in controller:

@deleted_employee_id = @employee.id
@employee.destroy
...

and in js view ...find('div.employee_<%= @deleted_employee_id %>').hide()...

PS. Also it's common practice to use "soft deletes" - have a flag in model that indicates if the record was "deleted" and set it in destroy action, without actual delete, this is useful, if a user would want to "undo".


问:
can i create java servlet as rest web service
Can I use Java Servlet as a Rest web service?
And how to request using curl to servlet?

thank

答:
Sure you can use a (raw) servlet to create a REST service. But that is too much work knowing that there exists a standard API for this (JAX-RS JSR-311) and many frameworks implementing it :

http://www.jboss.org/resteasy

http://cxf.apache.org/docs/jax-rs.html

http://jersey.java.net/


问:
How to join source specific multicast group in C# (IGMPv3)
We have a C# application that can join and receives data from a multicast group. This works well. We now want to support IGMPv3 and be able to specify the IP of the source when joining a multicast group. From the MSDN documentation, I don't see how to do this. I have found the following link that seems to answer my question.

http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/e8063f6d-22f5-445e-a00c-bf46b46c1561

And here is how I implemented this:

```<code>byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
Buffer.BlockCopy(multicastIp.GetAddressBytes(), 0, membershipAddresses, 0, 4);
Buffer.BlockCopy(sourceIp.GetAddressBytes(), 0, membershipAddresses, 4, 4);
Buffer.BlockCopy(localIp.GetAddressBytes(), 0, membershipAddresses, 8, 4);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, membershipAddresses);
</code>```

But I get a SocketException when calling SetSocketOption() with this error: The requested address is not valid in its context.

Can someone points me what I am doing wrong here? Thanks!

答:
For anyone struggling with source multicast</p>

```<code>static void StartListner(IPAddress sourceIp, IPAddress multicastGroupIp, IPAddress localIp, int port)
{
    Task.Run(() =>
    {
        try
        {
            Console.WriteLine("Starting: "  + sourceIp + " - " + multicastGroupIp + " - " + localIp + " / " + port);

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            IPEndPoint localEndpoint = new IPEndPoint(localIp, port);
            socket.Bind(localEndpoint);

            byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
            Buffer.BlockCopy(multicastGroupIp.GetAddressBytes(), 0, membershipAddresses, 0, 4);
            Buffer.BlockCopy(sourceIp.GetAddressBytes(), 0, membershipAddresses, 4, 4);
            Buffer.BlockCopy(localIp.GetAddressBytes(), 0, membershipAddresses, 8, 4);
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddSourceMembership, membershipAddresses);

            while (true)
            {
                byte[] b = new byte[1024];
                int length = socket.Receive(b);

                Console.WriteLine("PORT: " + port + " : " + Encoding.ASCII.GetString(b, 0, length));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    });
}
</code>```

Body:
We have a C# application that can join and receives data from a multicast group. This works well. We now want to support IGMPv3 and be able to specify the IP of the source when joining a multicast group. From the MSDN documentation, I don't see how to do this. I have found the following link that seems to answer my question.

http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/e8063f6d-22f5-445e-a00c-bf46b46c1561

And here is how I implemented this:

byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
Buffer.BlockCopy(multicastIp.GetAddressBytes(), 0, membershipAddresses, 0, 4);
Buffer.BlockCopy(sourceIp.GetAddressBytes(), 0, membershipAddresses, 4, 4);
Buffer.BlockCopy(localIp.GetAddressBytes(), 0, membershipAddresses, 8, 4);
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, membershipAddresses);

But I get a SocketException when calling SetSocketOption() with this error: The requested address is not valid in its context.

Can someone points me what I am doing wrong here? Thanks!

Body:
For anyone struggling with source multicast

static void StartListner(IPAddress sourceIp, IPAddress multicastGroupIp, IPAddress localIp, int port)
{
    Task.Run(() =>
    {
        try
        {
            Console.WriteLine("Starting: "  + sourceIp + " - " + multicastGroupIp + " - " + localIp + " / " + port);

            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            IPEndPoint localEndpoint = new IPEndPoint(localIp, port);
            socket.Bind(localEndpoint);

            byte[] membershipAddresses = new byte[12]; // 3 IPs * 4 bytes (IPv4)
            Buffer.BlockCopy(multicastGroupIp.GetAddressBytes(), 0, membershipAddresses, 0, 4);
            Buffer.BlockCopy(sourceIp.GetAddressBytes(), 0, membershipAddresses, 4, 4);
            Buffer.BlockCopy(localIp.GetAddressBytes(), 0, membershipAddresses, 8, 4);
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddSourceMembership, membershipAddresses);

            while (true)
            {
                byte[] b = new byte[1024];
                int length = socket.Receive(b);

                Console.WriteLine("PORT: " + port + " : " + Encoding.ASCII.GetString(b, 0, length));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    });
}


问:
laravel reset password custom validator?
by looking at ResetsPasswords code I can see that rules method is protected:

```<code> protected function rules()
    {
        return [
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|confirmed|min:6',
        ];
    }
</code>```

what is the appropriate way in laravel of adding another custom validation into the reset password form if I cant override the rules method?

I can override the reset method but its too big and if in the future versions they will change some logic I will be in trouble as I don't want to mess too much with security features

答:
You can overwrite the reset method in the ResetsPasswords trait. So that it adds a custom validator to the Broker instance and bypasses Laravel's nonsense default validation rules.

```<code>/**
 * Reset the given user's password.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function reset(Request $request)
{
    $this->validate($request, $this->rules(), $this->validationErrorMessages());

    // These two lines below allow you to bypass the default validation.
    $broker = $this->broker();
    $broker->validate(function () { return true; });

    $response->reset(
        $this->credentials($request), function ($user, $password) {
            $this->resetPassword($user, $password);
        }
    );

    return $response == Password::PASSWORD_RESET
                ? $this->sendResetResponse($response)
                : $this->sendResetFailedResponse($request, $response);
}
</code>```

Body:
by looking at ResetsPasswords code I can see that rules method is protected:

 protected function rules()
    {
        return [
            'token' => 'required',
            'email' => 'required|email',
            'password' => 'required|confirmed|min:6',
        ];
    }

what is the appropriate way in laravel of adding another custom validation into the reset password form if I cant override the rules method?

I can override the reset method but its too big and if in the future versions they will change some logic I will be in trouble as I don't want to mess too much with security features

Body:
You can overwrite the reset method in the ResetsPasswords trait. So that it adds a custom validator to the Broker instance and bypasses Laravel's nonsense default validation rules.

/**
 * Reset the given user's password.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse
 */
public function reset(Request $request)
{
    $this->validate($request, $this->rules(), $this->validationErrorMessages());

    // These two lines below allow you to bypass the default validation.
    $broker = $this->broker();
    $broker->validate(function () { return true; });

    $response->reset(
        $this->credentials($request), function ($user, $password) {
            $this->resetPassword($user, $password);
        }
    );

    return $response == Password::PASSWORD_RESET
                ? $this->sendResetResponse($response)
                : $this->sendResetFailedResponse($request, $response);
}


问:
Interface A incorrectly extends interface B
Given this interface:

```<code>interface Props extends React.HTMLAttributes<HTMLDivElement> {
  compLevel: string;
  property: Property;
  comps: Property[];
}
</code>```

I'm having difficulties with the property attribute given that it already exists on HTMLAttributes as property?: string;:

Interface 'Props' incorrectly extends interface
  'HTMLAttributes'.   Types of property 'property' are
  incompatible.
      Type 'SerializedObject' is not assignable to type 'string'.

Renaming the attribute works though I'd rather not do that.What is a recommended interface to extend/approach to use so that I don't need to redefine className on my Props?

答:
What are you going to do with Props?  You probably shouldn't use it in places that expect a React.HTMLAttributes<HTMLDivElement>.  As stated, and treating the code as a complete example, I'd probably define Props like this:

```<code>// SimpleSpread<L, R> is a simplified version of what happens when you
// do an object spread like {...left, ...right} where left is of type L and
// right is of type R.  It is the type R, with any properties on L that
// don't exist in R.  (It doesn't work if a key in L is an optional property in
// R, which is why this is simplified)
type SimpleSpread<L, R> = R & Pick<L, Exclude<keyof L, keyof R>>;

// Define the props you want to spread into React.HTMLAttributes<HTMLDivElement>
interface PropsExtra {
  compLevel: string;
  property: Property;
  comps: Property[];
}

// Define Props
interface Props
  extends SimpleSpread<React.HTMLAttributes<HTMLDivElement>, PropsExtra> {}
</code>```

This works by treating Props like PropsExtra with only those properties from React.HTMLAttributes<HTMLDivElement> that do not appear in PropsExtra.  So this will end up overwriting the property property instead of extending it.

That will now have no error.

Do note that the following will be an error:

```<code>declare function acceptAttributes(attrs: React.HTMLAttributes<HTMLDivElement>);
declare const p: Props;
acceptAttributes(p); // error! p is not a React.HTMLAttributes<HTMLDivElement>
</code>```

Because they differ in the types of the property property (heh), a value of type Props is no longer a valid React.HTMLAttributes<HTMLDivElement> value.  Anything which expects the latter will not accept the former.  You could then change the expected argument type of such functions, which will likely cascade outwards until this change touches more of your code base than you intended.

So it really depends on your use case if this will work for you.  Good luck!

Body:
Given this interface:

interface Props extends React.HTMLAttributes<HTMLDivElement> {
  compLevel: string;
  property: Property;
  comps: Property[];
}

I'm having difficulties with the property attribute given that it already exists on HTMLAttributes as property?: string;:

Interface 'Props' incorrectly extends interface
  'HTMLAttributes'.   Types of property 'property' are
  incompatible.
      Type 'SerializedObject' is not assignable to type 'string'.

Renaming the attribute works though I'd rather not do that.What is a recommended interface to extend/approach to use so that I don't need to redefine className on my Props?

Body:
What are you going to do with Props?  You probably shouldn't use it in places that expect a React.HTMLAttributes<HTMLDivElement>.  As stated, and treating the code as a complete example, I'd probably define Props like this:

// SimpleSpread<L, R> is a simplified version of what happens when you
// do an object spread like {...left, ...right} where left is of type L and
// right is of type R.  It is the type R, with any properties on L that
// don't exist in R.  (It doesn't work if a key in L is an optional property in
// R, which is why this is simplified)
type SimpleSpread<L, R> = R & Pick<L, Exclude<keyof L, keyof R>>;

// Define the props you want to spread into React.HTMLAttributes<HTMLDivElement>
interface PropsExtra {
  compLevel: string;
  property: Property;
  comps: Property[];
}

// Define Props
interface Props
  extends SimpleSpread<React.HTMLAttributes<HTMLDivElement>, PropsExtra> {}

This works by treating Props like PropsExtra with only those properties from React.HTMLAttributes<HTMLDivElement> that do not appear in PropsExtra.  So this will end up overwriting the property property instead of extending it.

That will now have no error.

Do note that the following will be an error:

declare function acceptAttributes(attrs: React.HTMLAttributes<HTMLDivElement>);
declare const p: Props;
acceptAttributes(p); // error! p is not a React.HTMLAttributes<HTMLDivElement>

Because they differ in the types of the property property (heh), a value of type Props is no longer a valid React.HTMLAttributes<HTMLDivElement> value.  Anything which expects the latter will not accept the former.  You could then change the expected argument type of such functions, which will likely cascade outwards until this change touches more of your code base than you intended.

So it really depends on your use case if this will work for you.  Good luck!


问:
extern declaration and definition in C
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

```<code>extern int foo; //default
static int bar;
</code>```

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

```<code>static int bar = 5;
</code>```

but casts a complain at

```<code>extern int foo = 4;
</code>```

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?

答:
IIRC, extern is more of a hint to the compiler that it does not have to allocate storage for the value.  The linker is expected to find the value in another compilation unit.  Usually extern is used in header files to indicate that the someone has defined storage associated with the name.  The definition of the value does not include the extern keyword since the compiler has to allocate storage for the value in the compilation unit that includes the definition.

See extern storage class specifier for more details.

Title: extern declaration and definition in C

Body:
a global variable may one to two different storage classes in C, to my best knowledge, and the declaration may be given with two different keywords, correspodingly

extern int foo; //default
static int bar;

Static variables are only visible within the module of declaration, and cannot be exported. In case of extern declaration, the variable is in the common namespace of all modules linked, unless shadowed by static variable.

Whereas static variables have to be defined in their module, an extern variable may be defined somewhere else. It has to be defined if ever used.

My compiler (GCC) accepts

static int bar = 5;

but casts a complain at

extern int foo = 4;

It seems to be expected that extern variables are never defined with the keyword 'extern'. This leads to the following question:

What kind of storage class does the Object 'foo' in the example above have in the module where it is defined?


问:
Scala ClassCastException on Option.orNull
When I try to run following code:

```<code>  def config[T](key: String): Option[T] = {
    //in reality this is a map of various instance types as values
    Some("string".asInstanceOf[T])
  }
  config("path").orNull
</code>```

I'm getting error:

java.lang.String cannot be cast to scala.runtime.Null$
  java.lang.ClassCastException

Following attempts are working fine:

```<code>config[String]("path").orNull
config("path").getOrElse("")
</code>```

Since getOrElse works its confusing why null is so special and throws an error. Is there a way for orNull to work without specifying generic type ?

scalaVersion := "2.12.8"

答:
Just to show how you may avoid the use asInstanceOf to get the values from a typed config.

```<code>sealed trait Value extends Product with Serializable
final case class IntValue(value: Int) extends Value
final case class StringValue(value: String) extends Value
final case class BooleanValue(value: Boolean) extends Value

type Config = Map[String, Value]

sealed trait ValueExtractor[T] {
  def extract(config: Config)(fieldName: String): Option[T]
}

object ValueExtractor {
  implicit final val IntExtractor: ValueExtractor[Int] =
    new ValueExtractor[Int] {
      override def extract(config: Config)(fieldName: String): Option[Int] =
        config.get(fieldName).collect {
          case IntValue(value) => value
        }
    }

  implicit final val StringExtractor: ValueExtractor[String] =
    new ValueExtractor[String] {
      override def extract(config: Config)(fieldName: String): Option[String] =
        config.get(fieldName).collect {
          case StringValue(value) => value
        }
    }

  implicit final val BooleanExtractor: ValueExtractor[Boolean] =
    new ValueExtractor[Boolean] {
      override def extract(config: Config)(fieldName: String): Option[Boolean] =
        config.get(fieldName).collect {
          case BooleanValue(value) => value
        }
    }
}

implicit class ConfigOps(val config: Config) extends AnyVal {
  def getAs[T](fieldName: String)(default: => T)
              (implicit extractor: ValueExtractor[T]): T =
    extractor.extract(config)(fieldName).getOrElse(default)
}
</code>```

Then, you can use it like this.

```<code>val config = Map("a" -> IntValue(10), "b" -> StringValue("Hey"), "d" -> BooleanValue(true))

config.getAs[Int](fieldName = "a")(default = 0) // res: Int = 10
config.getAs[Int](fieldName = "b")(default = 0) // res: Int = 0
config.getAs[Boolean](fieldName = "c")(default = false) // res: Boolean = false
</code>```

Now, the problem becomes how to create the typed config from a raw source.

And even better, how to directly map the config to a case class.

But, those are more complex, and probably is better to just use something already done, like pureconfig.

Just as an academic exercise, lets see if we can support Lists & Maps.

Lets start with lists, a naive approach would be to have another case class for values which are lists, and create a factory of extractors for every kind of list (this process is formally know as implicit derivation).

```<code>import scala.reflect.ClassTag

final case class ListValue[T](value: List[T]) extends Value

...

// Note that, it has to be a def, since it is not only one implicit.
// But, rather a factory of implicits.
// Also note that, it needs another implicit parameter to construct the specific implicit.
// In this case, it needs a ClasTag for the inner type of the list to extract.
implicit final def listExtractor[T: ClassTag]: ValueExtractor[List[T]] =
  new ValueExtractor[List[T]] {
    override def extract(config: Config)(fieldName: String): Option[List[T]] =
      config.get(fieldName).collect {
        case ListValue(value) => value.collect {
          // This works as a safe caster, which will remove all value that couldn't been casted.
          case t: T => t
        }
      }
  }
</code>```

Now, you can use it like this.

```<code>val config = Map("l" ->ListValue(List(1, 2, 3)))

config.getAs[List[Int]](fieldName = "l")(default = List.empty)
// res: List[Int] = List(1, 2, 3)
config.getAs[List[String]](fieldName = "l")(default = List("Hey"))
// res: String = List() - The default is not used, since the field is a List...
// whose no element could be casted to String.
</code>```

However, this approach is limited to plain types, if you need a List of other generic type, like a List of Lists. Then, this won't work.

```<code>val config = Map("l" ->ListValue(List(List(1, 2), List(3))))

val l = config.getAs[List[List[String]]](fieldName = "l")(default = List.empty)
// l: List[List[String]] = List(List(1, 2), List(3)) ???!!!
l.head
// res: List[String] = List(1, 2)
l.head.head
// java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
</code>```

The problem here is type erasure, which ClassTags can not solve, you may try to use TypeTags which can preserve the complete type, but the solution becomes more cumbersome.

For Maps the solution is quite similar, especially if you fix the key type to String (assuming what you really want is a nested config). But, this post is too long now, so I would leave it as an exercise for the reader.

Nevertheless, as already said, this can be broken easily, and is not completely robust.

There are better approaches, but I myself am not very skilled on those (yet), and even if I would be, the answer would be more long and really not necessary at all.

Lucky for you, even if pureconfig does not support YAML directly, there is a module which does, pureconfig-yaml.

I would suggest you to take a look to the module, and if you have further problems ask a new question tagging pureconfig and yaml directly. Also, if it is just a small doubt, you may try asking in thegitter channel.

Body:
When I try to run following code:

  def config[T](key: String): Option[T] = {
    //in reality this is a map of various instance types as values
    Some("string".asInstanceOf[T])
  }
  config("path").orNull

I'm getting error:

java.lang.String cannot be cast to scala.runtime.Null$
  java.lang.ClassCastException

Following attempts are working fine:

config[String]("path").orNull
config("path").getOrElse("")

Since getOrElse works its confusing why null is so special and throws an error. Is there a way for orNull to work without specifying generic type ?

scalaVersion := "2.12.8"

Body:
Just to show how you may avoid the use asInstanceOf to get the values from a typed config.

sealed trait Value extends Product with Serializable
final case class IntValue(value: Int) extends Value
final case class StringValue(value: String) extends Value
final case class BooleanValue(value: Boolean) extends Value

type Config = Map[String, Value]

sealed trait ValueExtractor[T] {
  def extract(config: Config)(fieldName: String): Option[T]
}

object ValueExtractor {
  implicit final val IntExtractor: ValueExtractor[Int] =
    new ValueExtractor[Int] {
      override def extract(config: Config)(fieldName: String): Option[Int] =
        config.get(fieldName).collect {
          case IntValue(value) => value
        }
    }

  implicit final val StringExtractor: ValueExtractor[String] =
    new ValueExtractor[String] {
      override def extract(config: Config)(fieldName: String): Option[String] =
        config.get(fieldName).collect {
          case StringValue(value) => value
        }
    }

  implicit final val BooleanExtractor: ValueExtractor[Boolean] =
    new ValueExtractor[Boolean] {
      override def extract(config: Config)(fieldName: String): Option[Boolean] =
        config.get(fieldName).collect {
          case BooleanValue(value) => value
        }
    }
}

implicit class ConfigOps(val config: Config) extends AnyVal {
  def getAs[T](fieldName: String)(default: => T)
              (implicit extractor: ValueExtractor[T]): T =
    extractor.extract(config)(fieldName).getOrElse(default)
}

Then, you can use it like this.

val config = Map("a" -> IntValue(10), "b" -> StringValue("Hey"), "d" -> BooleanValue(true))

config.getAs[Int](fieldName = "a")(default = 0) // res: Int = 10
config.getAs[Int](fieldName = "b")(default = 0) // res: Int = 0
config.getAs[Boolean](fieldName = "c")(default = false) // res: Boolean = false

Now, the problem becomes how to create the typed config from a raw source.

And even better, how to directly map the config to a case class.

But, those are more complex, and probably is better to just use something already done, like pureconfig.

Just as an academic exercise, lets see if we can support Lists & Maps.

Lets start with lists, a naive approach would be to have another case class for values which are lists, and create a factory of extractors for every kind of list (this process is formally know as implicit derivation).

import scala.reflect.ClassTag

final case class ListValue[T](value: List[T]) extends Value

...

// Note that, it has to be a def, since it is not only one implicit.
// But, rather a factory of implicits.
// Also note that, it needs another implicit parameter to construct the specific implicit.
// In this case, it needs a ClasTag for the inner type of the list to extract.
implicit final def listExtractor[T: ClassTag]: ValueExtractor[List[T]] =
  new ValueExtractor[List[T]] {
    override def extract(config: Config)(fieldName: String): Option[List[T]] =
      config.get(fieldName).collect {
        case ListValue(value) => value.collect {
          // This works as a safe caster, which will remove all value that couldn't been casted.
          case t: T => t
        }
      }
  }

Now, you can use it like this.

val config = Map("l" ->ListValue(List(1, 2, 3)))

config.getAs[List[Int]](fieldName = "l")(default = List.empty)
// res: List[Int] = List(1, 2, 3)
config.getAs[List[String]](fieldName = "l")(default = List("Hey"))
// res: String = List() - The default is not used, since the field is a List...
// whose no element could be casted to String.

However, this approach is limited to plain types, if you need a List of other generic type, like a List of Lists. Then, this won't work.

val config = Map("l" ->ListValue(List(List(1, 2), List(3))))

val l = config.getAs[List[List[String]]](fieldName = "l")(default = List.empty)
// l: List[List[String]] = List(List(1, 2), List(3)) ???!!!
l.head
// res: List[String] = List(1, 2)
l.head.head
// java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

The problem here is type erasure, which ClassTags can not solve, you may try to use TypeTags which can preserve the complete type, but the solution becomes more cumbersome.

For Maps the solution is quite similar, especially if you fix the key type to String (assuming what you really want is a nested config). But, this post is too long now, so I would leave it as an exercise for the reader.

Nevertheless, as already said, this can be broken easily, and is not completely robust.

There are better approaches, but I myself am not very skilled on those (yet), and even if I would be, the answer would be more long and really not necessary at all.

Lucky for you, even if pureconfig does not support YAML directly, there is a module which does, pureconfig-yaml.

I would suggest you to take a look to the module, and if you have further problems ask a new question tagging pureconfig and yaml directly. Also, if it is just a small doubt, you may try asking in thegitter channel.


问:
Complete the middleware file such that, all the query parameters are validated and null and undefined values throw an error message
output when both name and age parameters are passed.

problem statment for creating api:
Complete the middleware file and index.js file in the given application such that, all the query parameters required by the route are validated and null and undefined values throw an error message -
The query parameters that are compulsory are - name :String, age:Number

create a route named '/query' and send response as explained above when this route is requested.
according to me the the api should include these condition to get the desired output, they are:

1.when both the query parameters are present respond with success(status:200)

2.when age query parameter is entered and name parameter is empty then respond with failure(status:403)

3.when name query parameter is entered and age parameter is empty then respond with failure(status:403)

when one of the query parameters is null for "eg: http://localhost:3000/query/?age=2&name"

```<code>    the output i get is this:
    {
     "error": false,
     "status": 200,
     "userMessage": "all parameters entered",
     "data": {
     "name": "",
     "age": "2"
    }
    }
</code>```

but the expected output should have
          error:true,
          status:403
this is error iam facing.

there are two files. one is  index.js file and the other checkQueryParameters.js file.(this is a middleware)

code of index.js

```<code>const express = require('express');
const app = express();
const middleware = require('./middleware/checkQueryParameter');

app.get('/query',middleware.checkQueryParameters,(req,res)=>{
res.end();
});
app.listen(3000,()=>console.log('Example app listening on point
3000'));
module.exports = app;
</code>```

code of checkQueryParameters.js

```<code>let checkQueryParameters = (req,res,next)=>{
  let name = req.query.name;
  let age = req.query.age;
  console.log(typeof(age));
  console.log(typeof(name))
  console.log(age);
  console.log(name);

  if(typeof name == undefined || name == null){
  let result ={
      error : true,
      status : 403,
      userMessage : 'some parameters missing',
      data : 'name'
      }
      res.send(result);
     }
     else if(typeof age == undefined || age == null){
     let result ={
         error : true,
         status : 403,
         userMessage : 'all parameters missing',
         data : 'age'
        }
        res.send(result);

     }
     else{
         let result ={
         error : false,
         status : 200,
         userMessage : 'all parameters entered',
         data :{
                 'name' : name,
                  'age' : age
               }
        }
      res.send(result);

     }
    }

   module.exports = {
      checkQueryParameters:checkQueryParameters
   }
</code>```

答:
I think that your problem is an empty string case.

In case of ?age=2&name, if you console.log(req.query.name); you will probably see that name is not null, is not undefined. It is an empty string ' '. If you want to check that case as an error,  you should check for an empty string too.

```<code>if(typeof name == undefined || name == null || name === ''){
...
</code>```

or

```<code>if(typeof age == undefined || age == null || age === ''){
....
</code>```

And one point about the rest of your middleware logic. Inside the if else block, where you check about age parameter, you send a message "all parameters missing". That is wrong. name is not missing, the fact that age validation is executed means that your first if block was not executed, so name parameter is pretty valid. You should handle it like this:

```<code>if(typeof name == undefined || name == null || name === ''){
    let result = {
        error : true,
        status : 403,
        userMessage : 'name parameter is missing',
        data : 'name'
    }
    ...
} else if(typeof age == undefined || age == null || age === ''){
    let result = {
        error : true,
        status : 403,
        userMessage : 'age parameter is missing',
        data : 'age'
    }
    ...
}
else {
...
}
</code>```

Body:
output when both name and age parameters are passed.

problem statment for creating api:
Complete the middleware file and index.js file in the given application such that, all the query parameters required by the route are validated and null and undefined values throw an error message -
The query parameters that are compulsory are - name :String, age:Number

create a route named '/query' and send response as explained above when this route is requested.
according to me the the api should include these condition to get the desired output, they are:

1.when both the query parameters are present respond with success(status:200)

2.when age query parameter is entered and name parameter is empty then respond with failure(status:403)

3.when name query parameter is entered and age parameter is empty then respond with failure(status:403)

when one of the query parameters is null for "eg: http://localhost:3000/query/?age=2&name"

    the output i get is this:
    {
     "error": false,
     "status": 200,
     "userMessage": "all parameters entered",
     "data": {
     "name": "",
     "age": "2"
    }
    }

but the expected output should have
          error:true,
          status:403
this is error iam facing.

there are two files. one is  index.js file and the other checkQueryParameters.js file.(this is a middleware)

code of index.js

const express = require('express');
const app = express();
const middleware = require('./middleware/checkQueryParameter');

app.get('/query',middleware.checkQueryParameters,(req,res)=>{
res.end();
});
app.listen(3000,()=>console.log('Example app listening on point
3000'));
module.exports = app;

code of checkQueryParameters.js

let checkQueryParameters = (req,res,next)=>{
  let name = req.query.name;
  let age = req.query.age;
  console.log(typeof(age));
  console.log(typeof(name))
  console.log(age);
  console.log(name);

  if(typeof name == undefined || name == null){
  let result ={
      error : true,
      status : 403,
      userMessage : 'some parameters missing',
      data : 'name'
      }
      res.send(result);
     }
     else if(typeof age == undefined || age == null){
     let result ={
         error : true,
         status : 403,
         userMessage : 'all parameters missing',
         data : 'age'
        }
        res.send(result);

     }
     else{
         let result ={
         error : false,
         status : 200,
         userMessage : 'all parameters entered',
         data :{
                 'name' : name,
                  'age' : age
               }
        }
      res.send(result);

     }
    }

   module.exports = {
      checkQueryParameters:checkQueryParameters
   }

Body:
I think that your problem is an empty string case.

In case of ?age=2&name, if you console.log(req.query.name); you will probably see that name is not null, is not undefined. It is an empty string ' '. If you want to check that case as an error,  you should check for an empty string too.

if(typeof name == undefined || name == null || name === ''){
...

or

if(typeof age == undefined || age == null || age === ''){
....

And one point about the rest of your middleware logic. Inside the if else block, where you check about age parameter, you send a message "all parameters missing". That is wrong. name is not missing, the fact that age validation is executed means that your first if block was not executed, so name parameter is pretty valid. You should handle it like this:

if(typeof name == undefined || name == null || name === ''){
    let result = {
        error : true,
        status : 403,
        userMessage : 'name parameter is missing',
        data : 'name'
    }
    ...
} else if(typeof age == undefined || age == null || age === ''){
    let result = {
        error : true,
        status : 403,
        userMessage : 'age parameter is missing',
        data : 'age'
    }
    ...
}
else {
...
}