问:
Application Insights - Exceptions Add information
Actually, I have application insights set in my asp.net web API 2 to log the error following the steps Diagnose exceptions in your web apps with Application Insights, everything is working fine but, I want to add information for each an exception, for example, CustomerId, JobId, and other.

So I would like to see that data in the exceptions (either call stack or other property) through Azure Application Insights (see this image). That information could help me to detect what are the records that I should use to try to replicate the error scenario.

Can you tell me any recommendation?

Thanks!

答:
As far as I know, the TelemetryClient.TrackException could add custom properties.

After adding these properties, you could find values in the azure insights portal.

More details about how to add the custom properties in web api, you could refer to below codes:

```<code>  public class AiExceptionLogger : ExceptionLogger
        {
            public override void Log(ExceptionLoggerContext context)
            {
                if (context != null && context.Exception != null)
                {//or reuse instance (recommended!). see note above
                    var ai = new TelemetryClient();
                    //Here you need get the CustomerId, JobId, and other. For example get the current user id
                    string re = HttpContext.Current.User.Identity.Name;

                    // Set up some properties:
                   //Here you need get what you need and add them to the properties
                    var properties = new Dictionary<string, string> {{ "Users", "vvvvv" } };
                        // Send the exception telemetry:
                    ai.TrackException(context.Exception, properties);
                }
                base.Log(context);
            }
        }
</code>```

You could find it in the See all properties as below:

But I have other question, How can I do to send data from my controller to "AiExceptionLogger". i.e: I have my controller a POST method Post(user, jobId), I want to add jobId to TrackException. Note: I don't want to use try{} catch(){} for every method in my controller, If I can add that information to context, it will be grat!. Thanks!

According to your description, I suggest you could try another way registered a filter and override the OnActionExecuted method.

In this method, you could firstly check the Exception is null. If the exception isn't null, you could get the ActionArguments from the HttpActionExecutedContext.

Then you could add this arguments in the properties and send them to the azure Application Insights.

More details, you could refer to below codes:

WebApiConfig:

```<code>public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());

            config.Filters.Add(new AAA());
        }

        public class AAA : ActionFilterAttribute
        {

            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                if (actionExecutedContext.Exception != null)
                {
                    var ai = new TelemetryClient();
                     //here get the arguments
                    string d1 = (string)actionExecutedContext.ActionContext.ActionArguments["id"];
                    var properties = new Dictionary<string, string> { { "Users", d1 } };
                    ai.TrackException(actionExecutedContext.Exception, properties);
                }
                base.OnActionExecuted(actionExecutedContext);
            }
        }
</code>```

Result:

Body:
As far as I know, the TelemetryClient.TrackException could add custom properties.

After adding these properties, you could find values in the azure insights portal.

More details about how to add the custom properties in web api, you could refer to below codes:

  public class AiExceptionLogger : ExceptionLogger
        {
            public override void Log(ExceptionLoggerContext context)
            {
                if (context != null && context.Exception != null)
                {//or reuse instance (recommended!). see note above
                    var ai = new TelemetryClient();
                    //Here you need get the CustomerId, JobId, and other. For example get the current user id
                    string re = HttpContext.Current.User.Identity.Name;

                    // Set up some properties:
                   //Here you need get what you need and add them to the properties
                    var properties = new Dictionary<string, string> {{ "Users", "vvvvv" } };
                        // Send the exception telemetry:
                    ai.TrackException(context.Exception, properties);
                }
                base.Log(context);
            }
        }

You could find it in the See all properties as below:

But I have other question, How can I do to send data from my controller to "AiExceptionLogger". i.e: I have my controller a POST method Post(user, jobId), I want to add jobId to TrackException. Note: I don't want to use try{} catch(){} for every method in my controller, If I can add that information to context, it will be grat!. Thanks!

According to your description, I suggest you could try another way registered a filter and override the OnActionExecuted method.

In this method, you could firstly check the Exception is null. If the exception isn't null, you could get the ActionArguments from the HttpActionExecutedContext.

Then you could add this arguments in the properties and send them to the azure Application Insights.

More details, you could refer to below codes:

WebApiConfig:

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //config.Services.Add(typeof(IExceptionLogger), new AiExceptionLogger());

            config.Filters.Add(new AAA());
        }

        public class AAA : ActionFilterAttribute
        {

            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                if (actionExecutedContext.Exception != null)
                {
                    var ai = new TelemetryClient();
                     //here get the arguments
                    string d1 = (string)actionExecutedContext.ActionContext.ActionArguments["id"];
                    var properties = new Dictionary<string, string> { { "Users", d1 } };
                    ai.TrackException(actionExecutedContext.Exception, properties);
                }
                base.OnActionExecuted(actionExecutedContext);
            }
        }

Result:


来源: stackexchange

问:
How to delete jsPlumb connection
I am playing with jsplumb, but I am not able to delete the connection between two divs having only the id of one div.</p>

答:
```<code>jsPlumb.deleteConnectionsForElement(elementId)
</code>```

works. Though it's old I'd like to add that finding out what methods a library has, provided it's self descriptive enough is quite easy.

dev tools

ContentLicense: CC BY-SA 3.0

Title: How to delete jsPlumb connection

Body:
jsPlumb.deleteConnectionsForElement(elementId)

works. Though it's old I'd like to add that finding out what methods a library has, provided it's self descriptive enough is quite easy.

dev tools


问:
Change Bootstrap 4 carousel direction
I want to change the direction of the carousel from left to right to top to bottom. All I've found are answers for Bootstrap 3 and they're not working. How can I do this in Bootstrap 4?

Here's the carousel code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    Previous

    Next

```

答:
You need to override the default directions, Just add below styles in your css file and make sure your css file load after your bootstrap :

```<code>.carousel-item-next.carousel-item-left,
.carousel-item-prev.carousel-item-right {
-webkit-transform: translate3d(0, 0, 0);
        transform: translate3d(0, 0, 0);
 }
 .carousel-item-next,
 .active.carousel-item-right {
   -webkit-transform: translate3d(0, -100%, 0);
        transform: translate3d(0, -100%, 0);
 }
 .carousel-item-prev,
 .active.carousel-item-left {
 -webkit-transform: translate3d(0, +100%, 0);
        transform: translate3d(0, +100, 0);
 }
</code>```

I made an example for u :

https://jsfiddle.net/emilvr/L6cm19hL/2/

Title: Change Bootstrap 4 carousel direction

Body:
You need to override the default directions, Just add below styles in your css file and make sure your css file load after your bootstrap :

.carousel-item-next.carousel-item-left,
.carousel-item-prev.carousel-item-right {
-webkit-transform: translate3d(0, 0, 0);
        transform: translate3d(0, 0, 0);
 }
 .carousel-item-next,
 .active.carousel-item-right {
   -webkit-transform: translate3d(0, -100%, 0);
        transform: translate3d(0, -100%, 0);
 }
 .carousel-item-prev,
 .active.carousel-item-left {
 -webkit-transform: translate3d(0, +100%, 0);
        transform: translate3d(0, +100, 0);
 }

I made an example for u :

https://jsfiddle.net/emilvr/L6cm19hL/2/


问:
Android TimePicker hour field disappears after orientation change
I am using a TimePicker under API 1.5 and when the orientation is changed on my device (a stock G1 running 1.6 - though NOT on the 1.5/1.6 emulator), the hour field goes blank. It still remembers the hour, it just doesn't show it. Is there any workaround for this?

The same problem was described by someone else here:

http://groups.google.com/group/android-beginners/browse_thread/thread/b4288004021b876/de5899a2bb291ab5

Nothing helpful was forthcoming - can StackOverflow do better?

答:
As mentioned, overriding the onResume() method will sort this issue.</p>

```<code>   @Override
    public void onResume() {
        super.onResume();

        TimePicker tmp = (TimePicker) this.findViewById(R.id.yourTimePicker);
        tmp.setCurrentHour(7); // This will also set on rotate

    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
As mentioned, overriding the onResume() method will sort this issue.

   @Override
    public void onResume() {
        super.onResume();

        TimePicker tmp = (TimePicker) this.findViewById(R.id.yourTimePicker);
        tmp.setCurrentHour(7); // This will also set on rotate

    }


问:
Diversity indices by treatment groups and sites in R
I am trying to calculate the inverse Simpson's diversity index in R using vegan's diversity() function.  I would like to calculate this index for each experimental treatment.

My data looks a bit like this, where species is the species x site contingency table and env is the treatment factor x site table:

```<code>spe <- read.table(header=TRUE, text="
  S1   S2   S3   S4
  0    1    2    1
  0    1    1    0
  1    0    0    3
  0    1    0    1
  1    2    1    0
")

env <- read.table(header=TRUE, text="
  Stage
  a
  b
  c
  a
  c
")
</code>```

Ideally, I'd get a single diversity index value for each (a,b,c) treatment factor.

I know that the specnumber() function has a groups option, but I don't see anything similar for diversity and was hoping to find an easy way to do the same thing.  I've tried applying summaryBy(), aggregate(), and ddply() without any luck.

I've also tried brute force computing diversity(subset(spe, env$Stage=="a"),"simpson") for each individual env$Stagebut that still gives me a Simpson's diversity index for each site in that stage, not for the stage as a whole.

Thanks.

答:
There is no such groups argument in diversity because it is not well defined: Do you mean the average diversity of the sampling units in a group, or the diversity of the average of sampling units in a group? They are different things and it is best to explicitly do what you want this index to do.

The first thing is easier: just calculate diversities for SUs and take their average by groups:

```<code>tapply(diversity(spe, "simpson"), env$Stage, mean)
</code>```

For the diversity of the average community, you first need to aggregate your data by groups and then calculate the diversity for each group (and for most indices mean and sum give the same result in usual diversity() indices, but sum works in some cases where mean does not):

```<code>diversity(aggregate(. ~  env$Stage, spe, sum)[,-1], MARGIN=1, index="simpson")
</code>```

aggregate wants to add an extra column to name the rows and we must drop it with [,-1], and gives the result transposed and we need to set MARGIN = 1 (or use t() to back-transpose).

As you see, the results are different. Some people call this differences as beta diversity.

Body:
I am trying to calculate the inverse Simpson's diversity index in R using vegan's diversity() function.  I would like to calculate this index for each experimental treatment.

My data looks a bit like this, where species is the species x site contingency table and env is the treatment factor x site table:

spe <- read.table(header=TRUE, text="
  S1   S2   S3   S4
  0    1    2    1
  0    1    1    0
  1    0    0    3
  0    1    0    1
  1    2    1    0
")

env <- read.table(header=TRUE, text="
  Stage
  a
  b
  c
  a
  c
")

Ideally, I'd get a single diversity index value for each (a,b,c) treatment factor.

I know that the specnumber() function has a groups option, but I don't see anything similar for diversity and was hoping to find an easy way to do the same thing.  I've tried applying summaryBy(), aggregate(), and ddply() without any luck.

I've also tried brute force computing diversity(subset(spe, env$Stage=="a"),"simpson") for each individual env$Stagebut that still gives me a Simpson's diversity index for each site in that stage, not for the stage as a whole.

Thanks.

Body:
There is no such groups argument in diversity because it is not well defined: Do you mean the average diversity of the sampling units in a group, or the diversity of the average of sampling units in a group? They are different things and it is best to explicitly do what you want this index to do.

The first thing is easier: just calculate diversities for SUs and take their average by groups:

tapply(diversity(spe, "simpson"), env$Stage, mean)

For the diversity of the average community, you first need to aggregate your data by groups and then calculate the diversity for each group (and for most indices mean and sum give the same result in usual diversity() indices, but sum works in some cases where mean does not):

diversity(aggregate(. ~  env$Stage, spe, sum)[,-1], MARGIN=1, index="simpson")

aggregate wants to add an extra column to name the rows and we must drop it with [,-1], and gives the result transposed and we need to set MARGIN = 1 (or use t() to back-transpose).

As you see, the results are different. Some people call this differences as beta diversity.


问:
R Shiny Destroy ObserveEvent
I am new to R Shiny. I am trying to create an app with some dynamically generated buttons. Each button has a observeEvent associated with it. I want to add a reset button which deletes all the observeEvents. I went through some links and found that destroy() function can be used for the same, but I am unable to figure out how to use it. Any suggestions? Thanks.</p>

```<code>library(shiny)
ui<-fluidPage(
  actionButton(inputId = "add",label = "Add Stuff"),
  htmlOutput("obs"),
  actionButton("reset","Reset")
)
server<-function(input,output,session){

  output$obs<-renderUI(HTML({names(input)}))

  observeEvent(input$add,{
    addModal<-function(failed=FALSE){

      modalDialog(size = "l",easyClose = T,title = "Add",footer = "",
                  selectInput(inputId = "stuff",label = "Select",choices = c("A","B","C","D","E")),
                  numericInput(inputId = "numstuff",label = "Quantity",min = 1,max = 5,value = 1),
                  actionButton(inputId = "add2",label = "Add")
                  )

    }
    showModal(addModal())
  })

  num<<-0
  observeEvent(input$add2,{
    num<<-num+1
    insertUI(selector = "#add",where = "beforeBegin",
             ui = actionButton(inputId = paste0("comp",num),label = paste0(input$stuff,":",input$numstuff))
    )
    lapply(num:num,function(i){
    observeEvent(input[[paste0("comp",i)]],{
      modModal<-function(failed=FALSE){

        modalDialog(size = "l",easyClose = T,title = "Delete",footer = "",
                    # numericInput(inputId = "newquan",label = "New Quantity",min=1,max=5,value=1),
                    actionButton(inputId = paste0("gomod",i),label = "Delete")
        )
      }
      showModal(modModal())
    },ignoreInit = T)

    observeEvent(input[[paste0("gomod",i)]],{
      nm<-paste0("#comp",i)
      removeUI(selector=nm)
    })

  })
  })

  observeEvent(input$reset,{
    observers<-names(input)
    lapply(observers,function(x){
      if(substr(x,1,4)=="comp"){
        obs<-input[[x]]
        obs$destroy()
      }
    })
  })

}
shinyApp(ui=ui,server=server)
</code>```

答:
You have to assign the observe (or observeEvent) to a variable (e.g. o) and then call o$destroy inside the body of the observer. See this app for a good example of using this (though the use case, which is to create "concurrent, forked, cancellable tasks in Shiny," is probably a lot more complicated than yours). In any case, you can see the mechanism in action there.

You may also be interested in this app, which I think accomplishes what you want in an easier way (using the once = TRUE argument).

Title: R Shiny Destroy ObserveEvent

Body:
I am new to R Shiny. I am trying to create an app with some dynamically generated buttons. Each button has a observeEvent associated with it. I want to add a reset button which deletes all the observeEvents. I went through some links and found that destroy() function can be used for the same, but I am unable to figure out how to use it. Any suggestions? Thanks.

library(shiny)
ui<-fluidPage(
  actionButton(inputId = "add",label = "Add Stuff"),
  htmlOutput("obs"),
  actionButton("reset","Reset")
)
server<-function(input,output,session){

  output$obs<-renderUI(HTML({names(input)}))

  observeEvent(input$add,{
    addModal<-function(failed=FALSE){

      modalDialog(size = "l",easyClose = T,title = "Add",footer = "",
                  selectInput(inputId = "stuff",label = "Select",choices = c("A","B","C","D","E")),
                  numericInput(inputId = "numstuff",label = "Quantity",min = 1,max = 5,value = 1),
                  actionButton(inputId = "add2",label = "Add")
                  )

    }
    showModal(addModal())
  })

  num<<-0
  observeEvent(input$add2,{
    num<<-num+1
    insertUI(selector = "#add",where = "beforeBegin",
             ui = actionButton(inputId = paste0("comp",num),label = paste0(input$stuff,":",input$numstuff))
    )
    lapply(num:num,function(i){
    observeEvent(input[[paste0("comp",i)]],{
      modModal<-function(failed=FALSE){

        modalDialog(size = "l",easyClose = T,title = "Delete",footer = "",
                    # numericInput(inputId = "newquan",label = "New Quantity",min=1,max=5,value=1),
                    actionButton(inputId = paste0("gomod",i),label = "Delete")
        )
      }
      showModal(modModal())
    },ignoreInit = T)

    observeEvent(input[[paste0("gomod",i)]],{
      nm<-paste0("#comp",i)
      removeUI(selector=nm)
    })

  })
  })

  observeEvent(input$reset,{
    observers<-names(input)
    lapply(observers,function(x){
      if(substr(x,1,4)=="comp"){
        obs<-input[[x]]
        obs$destroy()
      }
    })
  })

}
shinyApp(ui=ui,server=server)


问:
Javascript error - cannot call method 'appendChild' of null
I am new to Javascript (and programming in general) and have been trying to get a basic grasp on working with the DOM.  Apologies if this is a very basic mistake, but I looked around and couldn't find an answer.

I am trying to use the appendChild method to add a heading and some paragraph text into the  in the very basic HTML file below.

```<code>    <html>
<head>
    <title>JS Practice</title>
</head>
<body>
    <script src="script.js"></script>
    <div id = "main">
        <h1>Simple HTML Page</h1>
        <p>This is a very simple HTML page.</p>
        <p>It's about as basic as they come. It has: </p>
        <ul>
            <li>An H1 Tag</li>
            <li>Two paragraphs</li>
            <li>An unordered list</li>
        </ul>
    </div>
    <div id="javascript">
    </div>
</body>
</html>
</code>```

Here is the js code:

```<code>var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");

newHeading.innerHTML = "New Heading!";
newParagraph.innerHTML = "Some text for a paragraph.";

document.getElementById("javascript").appendChild(newHeading);
document.getElementById("javascript").appendChild(newParagraph);
</code>```

Running it causes an error: "Cannot call method 'appendChild' of null"

Help? I can't figure out why this isn't working...

答:
Because your JavaScript file is loaded first, and that time when you write window.document.body.appendChild(btn), body element is not loaded in html, that's why you are getting error here, you can load the js file once body element is loaded in DOM.

index.html

```<code><html>
     <head>
         <script src="JavaScript.js"></script>
     </head>
     <body onload="init()">
          <h3> button will come here</h3>
     </body>
</html>
</code>```

JavaScript.js

```<code>function init(){

   var button = window.document.createElement("button");

   var textNode = window.document.createTextNode("click me");

   button.appendChild(textNode);

   window.document.body.appendChild(button);

  }
</code>```

Body:
I am new to Javascript (and programming in general) and have been trying to get a basic grasp on working with the DOM.  Apologies if this is a very basic mistake, but I looked around and couldn't find an answer.

I am trying to use the appendChild method to add a heading and some paragraph text into the  in the very basic HTML file below.

    <title>JS Practice</title>

Simple HTML Page

This is a very simple HTML page.

It's about as basic as they come. It has:

An H1 Tag

Two paragraphs

An unordered list

Here is the js code:

var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");

newHeading.innerHTML = "New Heading!";
newParagraph.innerHTML = "Some text for a paragraph.";

document.getElementById("javascript").appendChild(newHeading);
document.getElementById("javascript").appendChild(newParagraph);

Running it causes an error: "Cannot call method 'appendChild' of null"

Help? I can't figure out why this isn't working...

Body:
Because your JavaScript file is loaded first, and that time when you write window.document.body.appendChild(btn), body element is not loaded in html, that's why you are getting error here, you can load the js file once body element is loaded in DOM.

index.html

<html>
     <head>
         <script src="JavaScript.js"></script>
     </head>
     <body onload="init()">
          <h3> button will come here</h3>
     </body>
</html>

JavaScript.js

function init(){

   var button = window.document.createElement("button");

   var textNode = window.document.createTextNode("click me");

   button.appendChild(textNode);

   window.document.body.appendChild(button);

  }


问:
Force compilation error with sealed classes
With sealed classes you can use exhaustive when expressions and omit the else clause when the expression returns a result:

```<code>sealed class SealedClass {
  class First : SealedClass()
  class Second : SealedClass()
}

fun test(sealedClass: SealedClass) : String =
    when (sealedClass) {
      is SealedClass.First -> "First"
      is SealedClass.Second -> "Second"
    }
</code>```

Now if I were to add a Third to SealedClass, the compiler will complain that the when expression in test() is not exhaustive, and I need to add a clause for Third or else.

I am wondering however if this check can also be enforced when test() does not return anything:

```<code>fun test(sealedClass: SealedClass) {
    when (sealedClass) {
      is SealedClass.First -> doSomething()
      is SealedClass.Second -> doSomethingElse()
    }
}
</code>```

This snippet does not break if Third is added.
I can add a return statement before when, but this could easily be forgotten and may break if the return type of one of the clauses is not Unit.

How can I make sure I don't forget to add a branch to my when clauses?

答:
In inspiration by Voddan's answer, you can build a property called safe you can use:

```<code>val Any?.safe get() = Unit
</code>```

To use:

```<code>when (sealedClass) {
    is SealedClass.First -> doSomething()
    is SealedClass.Second -> doSomethingElse()
}.safe
</code>```

I think it provides a clearer message than just appending .let{} or assigning the result to a value.

There is an open issue on the Kotlin tracker which considers to support 'sealed whens'.

Body:
With sealed classes you can use exhaustive when expressions and omit the else clause when the expression returns a result:

sealed class SealedClass {
  class First : SealedClass()
  class Second : SealedClass()
}

fun test(sealedClass: SealedClass) : String =
    when (sealedClass) {
      is SealedClass.First -> "First"
      is SealedClass.Second -> "Second"
    }

Now if I were to add a Third to SealedClass, the compiler will complain that the when expression in test() is not exhaustive, and I need to add a clause for Third or else.

I am wondering however if this check can also be enforced when test() does not return anything:

fun test(sealedClass: SealedClass) {
    when (sealedClass) {
      is SealedClass.First -> doSomething()
      is SealedClass.Second -> doSomethingElse()
    }
}

This snippet does not break if Third is added.
I can add a return statement before when, but this could easily be forgotten and may break if the return type of one of the clauses is not Unit.

How can I make sure I don't forget to add a branch to my when clauses?

Body:
In inspiration by Voddan's answer, you can build a property called safe you can use:

val Any?.safe get() = Unit

To use:

when (sealedClass) {
    is SealedClass.First -> doSomething()
    is SealedClass.Second -> doSomethingElse()
}.safe

I think it provides a clearer message than just appending .let{} or assigning the result to a value.

There is an open issue on the Kotlin tracker which considers to support 'sealed whens'.

ContentLicense: CC BY-SA 4.0


问:
Finding the longest border of a string
First, let me tell you what the border of a string is,

```<code>let x = "abacab"
let y = "ababab"
</code>```

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

答:
Finding the "border of a string" is what the prefix function (also known as failure function) of Knuth-Morris-Pratt algorithm do. Implementation in c++ (a bit changed version of this code):

```<code>int longestBorder(const string& s) {
    int len = s.length();
    vector<int> prefixFunc(len);
    prefixFunc[0] = 0;

    int curBorderLen = 0;
    for (int i = 1; i < len; ++i) {
        while (curBorderLen > 0 && s[curBorderLen] != s[i])
            curBorderLen = prefixFunc[curBorderLen - 1];

        if (s[curBorderLen] == s[i])
            ++curBorderLen;

        prefixFunc[i] = curBorderLen;
    }

    return prefixFunc[len-1];
}
</code>```

Runnable version: http://ideone.com/hTW8FL

The complexity of this algorithm is O(n).

Title: Finding the longest border of a string

Body:
First, let me tell you what the border of a string is,

let x = "abacab"
let y = "ababab"

The border of a string is a substring which is both a proper prefix and proper suffix of the string — "proper" meaning that the whole string does not count as a substring. The longest border of x is "ab". The longest border of y is "abab" (the prefix and suffix can overlap).

Another example:

In string "abcde hgrab abcde", then "abcde" is a prefix as well as suffix. Thus it is also the longest border of the string above.

How can I find the longest border of a string?

Body:
Finding the "border of a string" is what the prefix function (also known as failure function) of Knuth-Morris-Pratt algorithm do. Implementation in c++ (a bit changed version of this code):

int longestBorder(const string& s) {
    int len = s.length();
    vector<int> prefixFunc(len);
    prefixFunc[0] = 0;

    int curBorderLen = 0;
    for (int i = 1; i < len; ++i) {
        while (curBorderLen > 0 && s[curBorderLen] != s[i])
            curBorderLen = prefixFunc[curBorderLen - 1];

        if (s[curBorderLen] == s[i])
            ++curBorderLen;

        prefixFunc[i] = curBorderLen;
    }

    return prefixFunc[len-1];
}

Runnable version: http://ideone.com/hTW8FL

The complexity of this algorithm is O(n).


问:
PHP sum two different minutes
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

```<code>$default_time = "00:30";
 $extra_time   = "00:25";
</code>```

my expected output : 00:55

but now display 01:00

this is my code

```<code>$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
</code>```

答:
```<code><?php
    $time = "00:30";
    $time2 = "00:25";

    $secs = strtotime($time2)-strtotime("00:00:00");
    $result = date("H:i:s",strtotime($time)+$secs);
    print_r($result);
?>
</code>```

Title: PHP sum two different minutes

Body:
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

$default_time = "00:30";
 $extra_time   = "00:25";

my expected output : 00:55

but now display 01:00

this is my code

$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));


问:
What is the result of the expression?
Does this code would work as expected in all browsers? Is there any notes in specification about it?

```<code>var attributes = this._attributes ? this._attributes : (this._attributes = []);
</code>```

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.

答:
There's nothing special about that expression, and you'll have no problems in any major browser. You could shorten it by using the || operator:

```<code>var attributes = this._attributes || (this._attributes = []);
</code>```

Title: What is the result of the expression?

Body:
Does this code would work as expected in all browsers? Is there any notes in specification about it?

var attributes = this._attributes ? this._attributes : (this._attributes = []);

I.e. if *this._attributes* not initialized, then new array will be created and that array will be assigned to *this._attributes* and to attributes.

Body:
There's nothing special about that expression, and you'll have no problems in any major browser. You could shorten it by using the || operator:

var attributes = this._attributes || (this._attributes = []);


答:
Here is the function you can calculate total time by passing the arguments to functions.

$hours, $min are supposed variable which is zero

```<code>$default_time = "00:30";
$break_time   = "00:25";
function calculate_total_time() {
    $i = 0;
    foreach(func_get_args() as $time) {
        sscanf($time, '%d:%d', $hour, $min);
        $i += $hour * 60 + $min;
    }

    if( $h = floor($i / 60) ) {
        $i %= 60;
    }

    return sprintf('%02d:%02d', $h, $i);
}

// use example
echo calculate_total_time($default_time, $break_time); # 00:55
</code>```

Title: PHP sum two different minutes

Body:
Here is the function you can calculate total time by passing the arguments to functions.

$hours, $min are supposed variable which is zero

$default_time = "00:30";
$break_time   = "00:25";
function calculate_total_time() {
    $i = 0;
    foreach(func_get_args() as $time) {
        sscanf($time, '%d:%d', $hour, $min);
        $i += $hour * 60 + $min;
    }

    if( $h = floor($i / 60) ) {
        $i %= 60;
    }

    return sprintf('%02d:%02d', $h, $i);
}

// use example
echo calculate_total_time($default_time, $break_time); # 00:55


问:
Contentful: Prevent webhook from triggering, when using Content Management API
So I've created a webhook within the Contentful dashboard, that triggers when an entry is either published or deleted, and it works as it should. However, I want to be able to publish entries via the Content Management JavaScript API, without triggering the webhook. Are there any measures I can take to make this possible?</p>

答:
Unfortunately there's no difference if an entry is published through the API or the web app directly. The web app simply calls the API under the hood.

What might be possible is to inspect the published entry within the web hook and evaluate whether code should execute or not. Perhaps by setting a hidden field when publishing through the API directly.

For example say you have a field publishedThroughAPI, you make sure this field is omitted from the delivery API and not editable:

Then set this field to true just before publishing through the JavaScript API and inspect this field in your webhook and simply return out of the hook if the field is set to true.

The webhook will recieve a payload that contains your published entry. Basically the same payload as for a normal request with the difference that it will contain every locale. Below is a small example:

```<code>{
   "sys": {
         //System meta data, created at, published at etc.
    },
   "fields": {
       //All fields of the entry.
       "title": {
            "en-US": "English title",
            "sv-SE": "Swedish title"
       },
       "publishedThroughAPI": {
            "en-US": true,
            "sv-SE": true
       }
   }
}
</code>```

Body:
Unfortunately there's no difference if an entry is published through the API or the web app directly. The web app simply calls the API under the hood.

What might be possible is to inspect the published entry within the web hook and evaluate whether code should execute or not. Perhaps by setting a hidden field when publishing through the API directly.

For example say you have a field publishedThroughAPI, you make sure this field is omitted from the delivery API and not editable:

Then set this field to true just before publishing through the JavaScript API and inspect this field in your webhook and simply return out of the hook if the field is set to true.

The webhook will recieve a payload that contains your published entry. Basically the same payload as for a normal request with the difference that it will contain every locale. Below is a small example:

{
   "sys": {
         //System meta data, created at, published at etc.
    },
   "fields": {
       //All fields of the entry.
       "title": {
            "en-US": "English title",
            "sv-SE": "Swedish title"
       },
       "publishedThroughAPI": {
            "en-US": true,
            "sv-SE": true
       }
   }
}


问:
Play Framework bindFromRequest() method returns objects with null parameters
I am new to Play! so I am trying to create a very basic post request that pulls data a user enters into a form. However, when I pull the object from the form, all of its fields are null. For example. Here is a basic class I wrote called user.

```<code>public class User{

public String email;
public String password;

}
</code>```

Simple. Here is my new user class inside the Controller.

```<code>    public Result new_user() {
    User user = Form.form(User.class).bindFromRequest().get();

    System.out.println("Username: " + user.email);
    System.out.println("Password: " + user.password);

    return ok("This worked.");
    }
</code>```

My routes file:

```<code>GET     /                    controllers.HomeController.start
POST    /accounts/login      controllers.HomeController.new_user()
</code>```

And finally, the HTML form:

```<code>        <form action = "@routes.HomeController.new_user()" method = "post">
         <input type="text" name="firstname">
         <input type="text" name="lastname">
         <button>Add Person</button>
        </form>
</code>```

I know this does not save to a database, but I really don't see the point in trying if I cant even print out to the console. Essentially what happens is the console will print "null" and "null", regardless of what I enter. I know that it does in fact create the object, as printing user will display something like:

```<code>models.User@1204f842
</code>```

But the fields are not set! What can I do to get this working?

Edit: I should mention that I checked if the form had any errors, it came back false.

答:
Fix the code in the html:</p>

```<code>     <input type="text" name="email">
     <input type="text" name="password">
</code>```

Body:
I am new to Play! so I am trying to create a very basic post request that pulls data a user enters into a form. However, when I pull the object from the form, all of its fields are null. For example. Here is a basic class I wrote called user.

public class User{

public String email;
public String password;

}

Simple. Here is my new user class inside the Controller.

    public Result new_user() {
    User user = Form.form(User.class).bindFromRequest().get();

    System.out.println("Username: " + user.email);
    System.out.println("Password: " + user.password);

    return ok("This worked.");
    }

My routes file:

GET     /                    controllers.HomeController.start
POST    /accounts/login      controllers.HomeController.new_user()

And finally, the HTML form:

        <form action = "@routes.HomeController.new_user()" method = "post">
         <input type="text" name="firstname">
         <input type="text" name="lastname">
         <button>Add Person</button>
        </form>

I know this does not save to a database, but I really don't see the point in trying if I cant even print out to the console. Essentially what happens is the console will print "null" and "null", regardless of what I enter. I know that it does in fact create the object, as printing user will display something like:

models.User@1204f842

But the fields are not set! What can I do to get this working?

Edit: I should mention that I checked if the form had any errors, it came back false.

Body:
Fix the code in the html:

     <input type="text" name="email">
     <input type="text" name="password">


问:
How to enable CORS in ASP.net Core WebAPI
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

```<code>    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });
</code>```

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

```<code>    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }
</code>```

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

```<code>[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller
</code>```

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

```<code>.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")
</code>```

These are other headers I tried which failed

```<code>.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")
</code>```

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

```<code>app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));
</code>```

答:
try adding jQuery.support.cors = true; before the Ajax call

It could also be that the data your sending to the API is wonky,

try adding the following JSON function

```<code>        var JSON = JSON || {};

    // implement JSON.stringify serialization
    JSON.stringify = JSON.stringify || function (obj) {

        var t = typeof (obj);
        if (t != "object" || obj === null) {

            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);

        }
        else {

            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);

            for (n in obj) {
                v = obj[n]; t = typeof (v);

                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);

                json.push((arr ? "" : '"' + n + '":') + String(v));
            }

            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

    // implement JSON.parse de-serialization
    JSON.parse = JSON.parse || function (str) {
        if (str === "") str = '""';
        eval("var p=" + str + ";");
        return p;
    };
</code>```

then in your data: object change it to

```<code>    data: JSON.stringify({
        username: username,
        password: password
    }),
</code>```

Body:
What I am trying to do

I have a backend ASP.Net Core Web API hosted on an Azure Free Plan (Add default security headers in .Net Core).

I also have a Client Website which I want to make consume that API. The Client Application will not be hosted on Azure, but rather will be hosted on Github Pages or on another Web Hosting Service that I have access to. Because of this the domain names won't line up.

Looking into this, I need to enable CORS on the Web API side, however I have tried just about everything for several hours now and it is refusing to work.

How I have the Client Setup
Its just a simple client written in React.js. I'm calling the APIs through AJAX in Jquery. The React site works so I know its not that. The Jquery API call works as I confirmed in Attempt 1. Here is how I make the calls

    var apiUrl = "http://andrewgodfroyportfolioapi.azurewebsites.net/api/Authentication";
    //alert(username + "|" + password + "|" + apiUrl);
    $.ajax({
        url: apiUrl,
        type: "POST",
        data: {
            username: username,
            password: password
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var authenticatedUser = JSON.parse(response);
            //alert("Data Loaded: " + authenticatedUser);
            if (onComplete != null) {
                onComplete(authenticatedUser);
            }
        },
        error: function (xhr, status, error) {
            //alert(xhr.responseText);
            if (onComplete != null) {
                onComplete(xhr.responseText);
            }
        }
    });

What I have tried

Attempt 1 - The 'proper' way

https://learn.microsoft.com/en-us/aspnet/core/security/cors

I have followed this tutorial on the Microsoft Website to a T, trying all 3 options of enabling it Globally in the Startup.cs, Setting it up on every controller and Trying it on every Action.

Following this method, the Cross Domain works, but only on a single Action on a single controller (POST to the AccountController). For everything else, the Microsoft.AspNetCore.Cors middleware refuses to set the headers.

I installed Microsoft.AspNetCore.Cors through NUGET and the version is 1.1.2

Here is how I have it setup in Startup.cs

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Cors
        services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

        // Add framework services.
        services.AddMvc();
        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new CorsAuthorizationFilterFactory("MyPolicy"));
        });

        ...
        ...
        ...
    }

    // This method gets called by the runtime. Use this method to configure
    //the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env,
    ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        // Enable Cors
        app.UseCors("MyPolicy");

        //app.UseMvcWithDefaultRoute();
        app.UseMvc();

        ...
        ...
        ...
    }

As you can see, I am doing everything as told. I add Cors before MVC both times, and when that didn't work I attempted putting [EnableCors("MyPolicy")] on every controller as so

[Route("api/[controller]")]
[EnableCors("MyPolicy")]
public class AdminController : Controller

Attempt 2 - Brute Forcing it

https://andrewlock.net/adding-default-security-headers-in-asp-net-core/

After several hours of trying on the previous attempt, I figured I would try to bruteforce it by trying to set the headers manually, forcing them to run on every response. I did this following this tutorial on how to manually add headers to every response.

These are the headers I added

.AddCustomHeader("Access-Control-Allow-Origin", "*")
.AddCustomHeader("Access-Control-Allow-Methods", "*")
.AddCustomHeader("Access-Control-Allow-Headers", "*")
.AddCustomHeader("Access-Control-Max-Age", "86400")

These are other headers I tried which failed

.AddCustomHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE")
.AddCustomHeader("Access-Control-Allow-Headers", "content-type, accept, X-PINGOTHER")
.AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Host, User-Agent, Accept, Accept: application/json, application/json, Accept-Language, Accept-Encoding, Access-Control-Request-Method, Access-Control-Request-Headers, Origin, Connection, Content-Type, Content-Type: application/json, Authorization, Connection, Origin, Referer")

With this method, the Cross Site headers are being properly applied and they show up in my developer console and in Postman. The problem however is that while it passes the Access-Control-Allow-Origin check, the webbrowser throws a hissy fit on (I believe) Access-Control-Allow-Headers stating 415 (Unsupported Media Type)

So the brute force method doesn't work either

Finally

Has anyone gotten this to work and could lend a hand, or just be able to point me in the right direction?

EDIT

So to get the API calls to go through, I had to stop using JQuery and switch to a Pure Javascript XMLHttpRequest format.

Attempt 1

I managed to get the Microsoft.AspNetCore.Cors to work by following MindingData's answer, except within the Configure Method putting the app.UseCors before app.UseMvc.

In addition, when mixed with the Javascript API Solution options.AllowAnyOrigin() for wildcard support began to work as well.

Attempt 2

So I have managed to get Attempt 2 (brute forcing it) to work... with the only exception that the Wildcard for Access-Control-Allow-Origin doesn't work and as such I have to manually set the domains that have access to it.

Its obviously not ideal since I just want this WebAPI to be wide opened to everyone, but it atleast works for me on a separate site, which means it's a start

app.UseSecurityHeadersMiddleware(new SecurityHeadersBuilder()
    .AddDefaultSecurePolicy()
    .AddCustomHeader("Access-Control-Allow-Origin", "http://localhost:3000")
    .AddCustomHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, PATCH, DELETE")
    .AddCustomHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Content-Type, Authorization"));

Body:
try adding jQuery.support.cors = true; before the Ajax call

It could also be that the data your sending to the API is wonky,

try adding the following JSON function

        var JSON = JSON || {};

    // implement JSON.stringify serialization
    JSON.stringify = JSON.stringify || function (obj) {

        var t = typeof (obj);
        if (t != "object" || obj === null) {

            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);

        }
        else {

            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);

            for (n in obj) {
                v = obj[n]; t = typeof (v);

                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);

                json.push((arr ? "" : '"' + n + '":') + String(v));
            }

            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

    // implement JSON.parse de-serialization
    JSON.parse = JSON.parse || function (str) {
        if (str === "") str = '""';
        eval("var p=" + str + ";");
        return p;
    };

then in your data: object change it to

    data: JSON.stringify({
        username: username,
        password: password
    }),


答:
That will work in all browsers.

It could be actually made terser with...

```<code>var attributes = this._attributes || (this._attributes = []);
</code>```

Title: What is the result of the expression?

Body:
That will work in all browsers.

It could be actually made terser with...

var attributes = this._attributes || (this._attributes = []);


问:
Why aren't my classes logging, but Spring is logging (Spring boot with Maven and log4j)?
I've been beating my head against the wall for almost 2 solid days, trying all the suggestions I've found in the answers to several questions here, with no joy.  Spring appears to be logging just fine, but nothing is being logged from my application classes.  I'm using Spring boot 1.5.3 and building an app that uses log4j and runs in a tomcat container (so it doesn't need Spring's embedded tomcat container).  Here are the dependencies that were in my original pom.xml:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.jboss.logging</groupId>
                <artifactId>jboss-logging</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>log4j-over-slf4j</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jcl</artifactId>
        <version>2.7</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>2.7</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
</code>```

I tried the solution suggested by @M.Deinum with no change in outcome:  Spring logged successfully, my classes did not.  The pom.xml in that case looked like this:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
</code>```

I have the following config file at the root of my app's class path:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="org.springframework.beans.factory" level="DEBUG"/>
        <Root level="DEBUG">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

The dependencies currently in my pom.xml are only the latest in a loooooong line of permutations I've tried, using code taken from the Spring Framework Reference 4.3.8.RELEASE and multiple questions answered here on stackoverflow.

答:
Cleanup your dependencies, you are excluding too much and including too much. Spring Boot has separate starters for all logging packages supported, simply use those.

```<code><dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

</dependencies>
</code>```

This is also explained in the reference guide.

Now when you want to use logging make sure to go through the SLF4J API and not Log4j2 directly (as this might trigger very early initialization and interfere with the setup from Spring Boot).

To create a deployable war you need to modify some of the dependencies with scope provided not exclude them. That is also described in the reference guide.

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>
</code>```

Body:
I've been beating my head against the wall for almost 2 solid days, trying all the suggestions I've found in the answers to several questions here, with no joy.  Spring appears to be logging just fine, but nothing is being logged from my application classes.  I'm using Spring boot 1.5.3 and building an app that uses log4j and runs in a tomcat container (so it doesn't need Spring's embedded tomcat container).  Here are the dependencies that were in my original pom.xml:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.jboss.logging</groupId>
                <artifactId>jboss-logging</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
            <exclusion>
                <artifactId>log4j-over-slf4j</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-jcl</artifactId>
        <version>2.7</version>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
        <version>2.7</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>2.7</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

I tried the solution suggested by @M.Deinum with no change in outcome:  Spring logged successfully, my classes did not.  The pom.xml in that case looked like this:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

I have the following config file at the root of my app's class path:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="org.springframework.beans.factory" level="DEBUG"/>
        <Root level="DEBUG">
            <AppenderRef ref="Console"/>
        </Root>
    </Loggers>
</Configuration>

The dependencies currently in my pom.xml are only the latest in a loooooong line of permutations I've tried, using code taken from the Spring Framework Reference 4.3.8.RELEASE and multiple questions answered here on stackoverflow.

Body:
Cleanup your dependencies, you are excluding too much and including too much. Spring Boot has separate starters for all logging packages supported, simply use those.

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

</dependencies>

This is also explained in the reference guide.

Now when you want to use logging make sure to go through the SLF4J API and not Log4j2 directly (as this might trigger very early initialization and interfere with the setup from Spring Boot).

To create a deployable war you need to modify some of the dependencies with scope provided not exclude them. That is also described in the reference guide.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>


问:
why if($row['field'] == value) work like SELECT WHERE field = value?
Today I'm drunked. I write wrong code like this.

```<code>$sql = "SELECT id, firstname, lastname, status FROM MyGuests";
$result = $conn->query($sql);

     while($row = $result->fetch_assoc()) {
      if($row['status'] == 'Active') {
         echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "<br>";
     }
}
</code>```

and it work like SELECT WHERE status = 'Active'  .
It not make sense for me why is it work?

I think if statement just check the one column, and not relative to that all row column. It should not work.

答:
They both are used in php.

==    Equality    $x == $y  Returns true if $x and $y have the same key/value pairs.

===   Identity    $x === $y Returns true if $x and $y have the same key/value pairs in the same order and of the same types.

I hope your doubt is cleared now. :-)

Body:
Today I'm drunked. I write wrong code like this.

$sql = "SELECT id, firstname, lastname, status FROM MyGuests";
$result = $conn->query($sql);

     while($row = $result->fetch_assoc()) {
      if($row['status'] == 'Active') {
         echo "
 id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"] . "
";
     }
}

and it work like SELECT WHERE status = 'Active'  .
It not make sense for me why is it work?

I think if statement just check the one column, and not relative to that all row column. It should not work.


问:
Build Errors with Cordova and Visual Studio 2015 Community
I am having some difficulty trying to understand why Visual Studio uses a different version of Node and NPM than what is installed...

My Development Environment Details:
-Windows 8.1
-Node Version: 6.10.3 (node -v)
-NPM Version: 5.0.1 (npm -v)

When I open up a solution file I get the following messages in my NPM Output window

```<code>PATH=.\node_modules\.bin;%VSINSTALLDIR%\Web\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\bin
"C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\COMMUNITY\Web\External\npm.CMD" install
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\Web\\External\\Node.exe" "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\Web\\External\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v5.4.1
npm ERR! npm  v3.3.4
npm ERR! No compatible version found: ionic-native@3.5.0
npm ERR! Valid install targets:
npm ERR! ["2.9.0","2.8.1","2.8.0","2.7.0","2.6.0","2.5.1","2.5.0","2.4.1","2.4.0","2.3.2","2.3.1","2.3.0","2.2.17","2.2.16","2.2.15","2.2.14","2.2.13","2.2.12","2.2.11","2.2.10","2.2.9","2.2.8","2.2.7","2.2.6","2.2.5","2.2.4","2.2.3","2.2.2","2.2.1","2.2.0","2.1.9","2.1.8","2.1.7","2.1.6","2.1.5","2.1.4","2.1.3","2.1.2","2.0.3","2.0.2","2.0.1","2.0.0","1.3.27","1.3.26","1.3.25","1.3.24","1.3.23","1.3.22","1.3.21","1.3.20","1.3.19","1.3.18","1.3.17","1.3.16","1.3.15","1.3.14","1.3.13","1.3.12","1.3.11","1.3.10","1.3.9","1.3.8","1.3.7","1.3.6","1.3.5","1.3.4","1.3.3","1.3.2","1.3.1","1.3.0","1.2.4","1.2.3","1.2.2","1.2.1","1.2.0","1.1.1","1.1.0","1.0.12","1.0.11","1.0.10","1.0.9","1.0.8","1.0.7"]
npm ERR!
</code>```

The error messages say Visual studio is trying to use node v5.4.1 and npm  v3.3.4.... Where are these versions installed?  And why isn't it using Node 6.10.3 and NPM 5.0.2?

Any help with this would be great!

答:
It seems you are using an old ionic-native package in your application. You should uninstall it by issuing the below command,

```<code>npm uninstall --save ionic-native
</code>```

And then try installing the latest one by issuing the below npm install command,

```<code>npm install @ionic-native/core --save
</code>```

Hope this helps!.

Body:
I am having some difficulty trying to understand why Visual Studio uses a different version of Node and NPM than what is installed...

My Development Environment Details:
-Windows 8.1
-Node Version: 6.10.3 (node -v)
-NPM Version: 5.0.1 (npm -v)

When I open up a solution file I get the following messages in my NPM Output window

PATH=.\node_modules\.bin;%VSINSTALLDIR%\Web\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\cmd;C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\bin
"C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\COMMUNITY\Web\External\npm.CMD" install
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\Web\\External\\Node.exe" "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\Web\\External\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v5.4.1
npm ERR! npm  v3.3.4
npm ERR! No compatible version found: ionic-native@3.5.0
npm ERR! Valid install targets:
npm ERR! ["2.9.0","2.8.1","2.8.0","2.7.0","2.6.0","2.5.1","2.5.0","2.4.1","2.4.0","2.3.2","2.3.1","2.3.0","2.2.17","2.2.16","2.2.15","2.2.14","2.2.13","2.2.12","2.2.11","2.2.10","2.2.9","2.2.8","2.2.7","2.2.6","2.2.5","2.2.4","2.2.3","2.2.2","2.2.1","2.2.0","2.1.9","2.1.8","2.1.7","2.1.6","2.1.5","2.1.4","2.1.3","2.1.2","2.0.3","2.0.2","2.0.1","2.0.0","1.3.27","1.3.26","1.3.25","1.3.24","1.3.23","1.3.22","1.3.21","1.3.20","1.3.19","1.3.18","1.3.17","1.3.16","1.3.15","1.3.14","1.3.13","1.3.12","1.3.11","1.3.10","1.3.9","1.3.8","1.3.7","1.3.6","1.3.5","1.3.4","1.3.3","1.3.2","1.3.1","1.3.0","1.2.4","1.2.3","1.2.2","1.2.1","1.2.0","1.1.1","1.1.0","1.0.12","1.0.11","1.0.10","1.0.9","1.0.8","1.0.7"]
npm ERR!

The error messages say Visual studio is trying to use node v5.4.1 and npm  v3.3.4.... Where are these versions installed?  And why isn't it using Node 6.10.3 and NPM 5.0.2?

Any help with this would be great!

Body:
It seems you are using an old ionic-native package in your application. You should uninstall it by issuing the below command,

npm uninstall --save ionic-native

And then try installing the latest one by issuing the below npm install command,

npm install @ionic-native/core --save

Hope this helps!.


问:
Discard the decorator
Could you help me understand whether it is possible to use a function both with a decorator and without it.

Example:

```<code>def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

@makeitalic
def hello():
    return "hello, sir or madam!"
</code>```

The only way that comes to my mind:

```<code>def hello():
    return "hello, sir or madam!"

@makeitalic
def italic_hello():
    return(hello())
</code>```

Well, is it possible to use hello() without the decorator?

答: Not in general.  The decorated function replaces the original, so there is no way to get the original unless the decorator itself makes it available explicitly (e.g., by storing it in some global registry or as an attribute on some object).  (You can access it as a cell variable in the decorated function's closure object, but that's not very robust and shouldn't be relied on except for testing and experimenting.)

Title: Discard the decorator

Body:
Could you help me understand whether it is possible to use a function both with a decorator and without it.

Example:

def makeitalic(fn):
    def wrapped():
        return "" + fn() + ""
    return wrapped

@makeitalic
def hello():
    return "hello, sir or madam!"

The only way that comes to my mind:

def hello():
    return "hello, sir or madam!"

@makeitalic
def italic_hello():
    return(hello())

Well, is it possible to use hello() without the decorator?


问:
Java RegEx meta character (.) and ordinary dot?
In Java RegEx, how to find out the difference between .(dot) the meta character and the normal dot as we using in any sentence. How to handle this kind of situation for other meta characters too like (*,+,\d,...)

答:
Here is code you can directly copy paste :

```<code>String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
   system.out.println(imageNameArray[i]);
}
</code>```

And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.

```<code>String imageName = "picture1  . jpg";
String [] imageNameArray = imageName.split("\\s*.\\s*");
    for(int i =0; i< imageNameArray.length ; i++)
    {
       system.out.println(imageNameArray[i]);
    }
</code>```

Here, \\s* is there to consider the spaces and give you only required splitted strings.

Body:
Here is code you can directly copy paste :

String imageName = "picture1.jpg";
String [] imageNameArray = imageName.split("\\.");
for(int i =0; i< imageNameArray.length ; i++)
{
   system.out.println(imageNameArray[i]);
}

And what if mistakenly there are spaces left before or after "." in such cases? It's always best practice to consider those spaces also.

String imageName = "picture1  . jpg";
String [] imageNameArray = imageName.split("\\s*.\\s*");
    for(int i =0; i< imageNameArray.length ; i++)
    {
       system.out.println(imageNameArray[i]);
    }

Here, \\s* is there to consider the spaces and give you only required splitted strings.


问:
Git: How to "undo" a merge
The situation:
Starting with the Master at A I branched and made some changes at B then merged that branch back in (C). After making some more changes I was at D but found I needed to deploy the code without the changes that happened in the branch. If I hand't merged it that would have been fine.

```<code>A_______C___D
 \     /
  \_B_/
</code>```

Firstly I'd like to know what I should have done from here to deploy the code as if the merge never happened. Note: none of the same files that were edited in the branch have been edited in the master.

Secondly...

I didn't have time to work out the best method to deal with this, so I deleted the files which the branch added, and manually reverted a few edits made in the branch then commited the result for deployment (F)

```<code>A_______C___D___F
 \     /
  \_B_/
</code>```

I want to be able to keep developing the branch and merge any changes from the master into it to keep it up to date, but if I do that the stuff I did to create F will be merged in and cause the files to be deleted and the edits to be reverted. What is the best way to deal with this?

答:
You can use rebase to do that in one step:

```<code>git rebase --onto A C D
</code>```

I just tested this, with appropriate results:

```<code>$ edit test.txt
$ git add .
$ git commit -mA
$ git checkout -b the_branch
$ edit test.txt
$ git commit -a -mB
$ git checkout master
$ git merge master the_branch --no-ff
$ edit test.txt
$ git commit -a -mD
</code>```

From here you have the situation you described.
Then:

```<code>$ git rebase --onto <SHA1-for-A> <SHA1-for-C> master
</code>```

rebases commits from C (excluded) to master, onto A.
I needed to fix some conflicts since I modified at the same places in B and D, but I think you won't.

```<code>   _D'
  /
 /
A_______C___D
 \     /
  \_B_/
</code>```

Doc about git rebase --onto, which is more or less your situation:
http://git-scm.com/docs/git-rebase

If you had:

```<code>A_______C___D___F
 \     /
  \_B_/
</code>```

, then you have now:

```<code>   _D'___F'_(master)
  /
 /
A_______C___D___F
 \     /
  \_B_/(the_branch)
</code>```

From here, merging the changes in master into the branch is easy. Discard the commit F' altogether.

```<code>$ git checkout master # if you were not here already
$ git branch old_fix  # if you want to be able to return to F' later
$ git reset --hard <SHA1-to-D'>
</code>```

After the commands above you have:

```<code>     (master)
    /
   _D'___F'_(old_fix)
  /
 /
A_______C___D___F
 \     /
  \_B_/(the_branch)
</code>```

To merge updates of master into the_branch:

```<code>$ git checkout the_branch
$ git merge master
</code>```

... and fix the conflicts.

Title: Git: How to "undo" a merge

Body:
The situation:
Starting with the Master at A I branched and made some changes at B then merged that branch back in (C). After making some more changes I was at D but found I needed to deploy the code without the changes that happened in the branch. If I hand't merged it that would have been fine.

A_______C___D
 \     /
  \_B_/

Firstly I'd like to know what I should have done from here to deploy the code as if the merge never happened. Note: none of the same files that were edited in the branch have been edited in the master.

Secondly...

I didn't have time to work out the best method to deal with this, so I deleted the files which the branch added, and manually reverted a few edits made in the branch then commited the result for deployment (F)

A_______C___D___F
 \     /
  \_B_/

I want to be able to keep developing the branch and merge any changes from the master into it to keep it up to date, but if I do that the stuff I did to create F will be merged in and cause the files to be deleted and the edits to be reverted. What is the best way to deal with this?

Body:
You can use rebase to do that in one step:

git rebase --onto A C D

I just tested this, with appropriate results:

$ edit test.txt
$ git add .
$ git commit -mA
$ git checkout -b the_branch
$ edit test.txt
$ git commit -a -mB
$ git checkout master
$ git merge master the_branch --no-ff
$ edit test.txt
$ git commit -a -mD

From here you have the situation you described.
Then:

$ git rebase --onto <SHA1-for-A> <SHA1-for-C> master

rebases commits from C (excluded) to master, onto A.
I needed to fix some conflicts since I modified at the same places in B and D, but I think you won't.

   _D'
  /
 /
A_______C___D
 \     /
  \_B_/

Doc about git rebase --onto, which is more or less your situation:
http://git-scm.com/docs/git-rebase

If you had:

A_______C___D___F
 \     /
  \_B_/

, then you have now:

   _D'___F'_(master)
  /
 /
A_______C___D___F
 \     /
  \_B_/(the_branch)

From here, merging the changes in master into the branch is easy. Discard the commit F' altogether.

$ git checkout master # if you were not here already
$ git branch old_fix  # if you want to be able to return to F' later
$ git reset --hard <SHA1-to-D'>

After the commands above you have:

     (master)
    /
   _D'___F'_(old_fix)
  /
 /
A_______C___D___F
 \     /
  \_B_/(the_branch)

To merge updates of master into the_branch:

$ git checkout the_branch
$ git merge master

... and fix the conflicts.


问:
How to get current AppInfo in UWP environment
How can I get the current AppInfo of the running UWP application? I could not find any accessible constructor or static function to get this information.</p>

答:
Make sure that your device is updated to Windows10 Creators Update version.

Firstly, you should add Capability appDiagnostics to Package.appxmanifest. Directly to modify the code of the file.

```<code><Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"     xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap mp rescap">
  <Capabilities>
    <Capability Name="internetClient" />
    <rescap:Capability Name="appDiagnostics"/>
  </Capabilities>
</Package>
</code>```

Then in the main code, get current package by matching the PackageFamilyName.

```<code>var list = await AppDiagnosticInfo.RequestInfoAsync();
var currentPackage = list.Where(o => o.AppInfo.PackageFamilyName == Package.Current.Id.FamilyName).FirstOrDefault();
if (currentPackage != null)
{
    AppInfo currentAppInfo = currentPackage.AppInfo;
}
</code>```

Body:
Make sure that your device is updated to Windows10 Creators Update version.

Firstly, you should add Capability appDiagnostics to Package.appxmanifest. Directly to modify the code of the file.

<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"     xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="uap mp rescap">
  <Capabilities>
    <Capability Name="internetClient" />
    <rescap:Capability Name="appDiagnostics"/>
  </Capabilities>
</Package>

Then in the main code, get current package by matching the PackageFamilyName.

var list = await AppDiagnosticInfo.RequestInfoAsync();
var currentPackage = list.Where(o => o.AppInfo.PackageFamilyName == Package.Current.Id.FamilyName).FirstOrDefault();
if (currentPackage != null)
{
    AppInfo currentAppInfo = currentPackage.AppInfo;
}


问:
R function for a function to be repeated based on column values
I have a large data set for which I need to do string matching. I have got some very useful posts from this site and referring them I have created a function to do the string matching for my dataset. I am pasting my sample data and code.

SAMPLE DATA

```<code>Address1 <- c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR")
AREACODE <- c('10','10','14','20','30')
Year1 <- c(2001:2005)

Address2 <- c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR")
Year2 <- c(2001:2010)
AREA_CODE <- c('10','10','10','20','30','40','50','61','64', '99')

data1 <- data.table(Address1, Year1, AREACODE)
data2 <- data.table(Address2, Year2, AREA_CODE)
data2[, unique_id := sprintf("%06d", 1:nrow(data2))]
</code>```

CODE

```<code>fn.fuzzymatch<-function(dat1,dat2,string1,string2,meth){

  dist.name<-stringdistmatrix(dat1[[string1]],dat2[[string2]],method = meth)

  min.name<-apply(dist.name, 1, min)

  match.s1.s2<-NULL
  for(i in 1:nrow(dist.name))
  {
    s2.i<-match(min.name[i],dist.name[i,])
    s1.i<-i
    match.s1.s2<-rbind(data.frame(s1_row=s1.i,s2_row=s2.i,s1name=dat1[s1.i,][[string1]],s2name=dat2[s2.i,][[string2]], dist=min.name[i]),match.s1.s2)
  }
  output <- (match.s1.s2)[order(match.s1.s2$s1_row),]
  return(output)
}

match_50 <- fn.fuzzymatch(data1,data2,"Address1","Address2","dl")
</code>```

This is working fine for the data at country level, but then I have multiple data files at region level and each region is having multiple areas. Areacode for each region is available by the AREACODE variable in data1 and AREA_CODE variable in data2. I want to update my function so that

string matching is done for each area and the output has that area code

output is returned for each region consolidated for all area codes in that region.

I was trying to use split and to convert the data files into list and use and then use rbindlist to combine them but not able to succeed and have been getting different kinds of errors. I am sure there is a way to do this but not able to get it. Hope I can have some suggestions.

答:
While you can probably use an apply function to repeat over separate data files of different regions, here is a fuzzyjoin solution based on my answer to your previous question.

It looks for the best stringdist match for Address and the AreaCode must match exactly (==). I also specified year2 had to be >= year1, just for demonstration.

Finally, I used dplyr::group_by and dplyr::top_n to get the minimum distance matches and I had to assume what to do in matching ties (picked matches with largest year2). You can also use slice_min which replaces the older top_n and if the original order is important and not alphabetical, use mutate(rank = row_number(dist)) %>% filter(rank == 1)

Data:

```<code>Address1 <- c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR")
AREACODE <- c('10','10','14','20','30')
Year1 <- c(2001:2005)

Address2 <- c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR")
Year2 <- c(2001:2010)
AREA_CODE <- c('10','10','10','20','30','40','50','61','64', '99')

data1 <- data.table(Address1, Year1, AREACODE)
data2 <- data.table(Address2, Year2, AREA_CODE)
data2[, unique_id := sprintf("%06d", 1:nrow(data2))]
</code>```

Solution:

```<code>library(fuzzyjoin, quietly = TRUE); library(dplyr, quietly = TRUE)

# First, need to define match_fun_stringdist
# Code from stringdist_join from https://github.com/dgrtwo/fuzzyjoin
match_fun_stringdist <- function(v1, v2) {

  # Can't pass these parameters in from fuzzy_join because of multiple incompatible match_funs, so I set them here.
  ignore_case = FALSE
  method = "dl"
  max_dist = 99
  distance_col = "dist"

  if (ignore_case) {
    v1 <- stringr::str_to_lower(v1)
    v2 <- stringr::str_to_lower(v2)
  }

  # shortcut for Levenshtein-like methods: if the difference in
  # string length is greater than the maximum string distance, the
  # edit distance must be at least that large

  # length is much faster to compute than string distance
  if (method %in% c("osa", "lv", "dl")) {
    length_diff <- abs(stringr::str_length(v1) - stringr::str_length(v2))
    include <- length_diff <= max_dist

    dists <- rep(NA, length(v1))

    dists[include] <- stringdist::stringdist(v1[include], v2[include], method = method)
  } else {
    # have to compute them all
    dists <- stringdist::stringdist(v1, v2, method = method)
  }
  ret <- dplyr::data_frame(include = (dists <= max_dist))
  if (!is.null(distance_col)) {
    ret[[distance_col]] <- dists
  }
  ret
}

# Finally, call fuzzy_join
fuzzy_join(data1, data2,
           by = list(x = c("Address1", "AREACODE", "Year1"), y = c("Address2", "AREA_CODE", "Year2")),
           match_fun = list(match_fun_stringdist, `==`, `<=`),
           mode = "left"
           ) %>%
  group_by(Address1, Year1, AREACODE) %>%
  top_n(1, -Address1.dist) %>%
  top_n(1, Year2) %>%
  select(unique_id, Address1.dist, everything())
</code>```

Body:
I have a large data set for which I need to do string matching. I have got some very useful posts from this site and referring them I have created a function to do the string matching for my dataset. I am pasting my sample data and code.

SAMPLE DATA

Address1 <- c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR")
AREACODE <- c('10','10','14','20','30')
Year1 <- c(2001:2005)

Address2 <- c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR")
Year2 <- c(2001:2010)
AREA_CODE <- c('10','10','10','20','30','40','50','61','64', '99')

data1 <- data.table(Address1, Year1, AREACODE)
data2 <- data.table(Address2, Year2, AREA_CODE)
data2[, unique_id := sprintf("%06d", 1:nrow(data2))]

CODE

fn.fuzzymatch<-function(dat1,dat2,string1,string2,meth){

  dist.name<-stringdistmatrix(dat1[[string1]],dat2[[string2]],method = meth)

  min.name<-apply(dist.name, 1, min)

  match.s1.s2<-NULL
  for(i in 1:nrow(dist.name))
  {
    s2.i<-match(min.name[i],dist.name[i,])
    s1.i<-i
    match.s1.s2<-rbind(data.frame(s1_row=s1.i,s2_row=s2.i,s1name=dat1[s1.i,][[string1]],s2name=dat2[s2.i,][[string2]], dist=min.name[i]),match.s1.s2)
  }
  output <- (match.s1.s2)[order(match.s1.s2$s1_row),]
  return(output)
}

match_50 <- fn.fuzzymatch(data1,data2,"Address1","Address2","dl")

This is working fine for the data at country level, but then I have multiple data files at region level and each region is having multiple areas. Areacode for each region is available by the AREACODE variable in data1 and AREA_CODE variable in data2. I want to update my function so that

string matching is done for each area and the output has that area code

output is returned for each region consolidated for all area codes in that region.

I was trying to use split and to convert the data files into list and use and then use rbindlist to combine them but not able to succeed and have been getting different kinds of errors. I am sure there is a way to do this but not able to get it. Hope I can have some suggestions.

Body:
While you can probably use an apply function to repeat over separate data files of different regions, here is a fuzzyjoin solution based on my answer to your previous question.

It looks for the best stringdist match for Address and the AreaCode must match exactly (==). I also specified year2 had to be >= year1, just for demonstration.

Finally, I used dplyr::group_by and dplyr::top_n to get the minimum distance matches and I had to assume what to do in matching ties (picked matches with largest year2). You can also use slice_min which replaces the older top_n and if the original order is important and not alphabetical, use mutate(rank = row_number(dist)) %>% filter(rank == 1)

Data:

Address1 <- c("786, GALI NO 5, XYZ","rambo, 45, strret 4, atlast, pqr","23/4, 23RD FLOOR, STREET 2, ABC-E, PQR","45-B, GALI NO5, XYZ","HECTIC, 99 STREET, PQR")
AREACODE <- c('10','10','14','20','30')
Year1 <- c(2001:2005)

Address2 <- c("abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR","abc, pqr, xyz","786, GALI NO 4 XYZ","45B, GALI NO 5, XYZ","del, 546, strret2, towards east, pqr","23/4, STREET 2, PQR")
Year2 <- c(2001:2010)
AREA_CODE <- c('10','10','10','20','30','40','50','61','64', '99')

data1 <- data.table(Address1, Year1, AREACODE)
data2 <- data.table(Address2, Year2, AREA_CODE)
data2[, unique_id := sprintf("%06d", 1:nrow(data2))]

Solution:

library(fuzzyjoin, quietly = TRUE); library(dplyr, quietly = TRUE)

# First, need to define match_fun_stringdist
# Code from stringdist_join from https://github.com/dgrtwo/fuzzyjoin
match_fun_stringdist <- function(v1, v2) {

  # Can't pass these parameters in from fuzzy_join because of multiple incompatible match_funs, so I set them here.
  ignore_case = FALSE
  method = "dl"
  max_dist = 99
  distance_col = "dist"

  if (ignore_case) {
    v1 <- stringr::str_to_lower(v1)
    v2 <- stringr::str_to_lower(v2)
  }

  # shortcut for Levenshtein-like methods: if the difference in
  # string length is greater than the maximum string distance, the
  # edit distance must be at least that large

  # length is much faster to compute than string distance
  if (method %in% c("osa", "lv", "dl")) {
    length_diff <- abs(stringr::str_length(v1) - stringr::str_length(v2))
    include <- length_diff <= max_dist

    dists <- rep(NA, length(v1))

    dists[include] <- stringdist::stringdist(v1[include], v2[include], method = method)
  } else {
    # have to compute them all
    dists <- stringdist::stringdist(v1, v2, method = method)
  }
  ret <- dplyr::data_frame(include = (dists <= max_dist))
  if (!is.null(distance_col)) {
    ret[[distance_col]] <- dists
  }
  ret
}

# Finally, call fuzzy_join
fuzzy_join(data1, data2,
           by = list(x = c("Address1", "AREACODE", "Year1"), y = c("Address2", "AREA_CODE", "Year2")),
           match_fun = list(match_fun_stringdist, `==`, `<=`),
           mode = "left"
           ) %>%
  group_by(Address1, Year1, AREACODE) %>%
  top_n(1, -Address1.dist) %>%
  top_n(1, Year2) %>%
  select(unique_id, Address1.dist, everything())