问:
How can I get an object inside a javascript event handler?
I am trying to get an object inside the onclick event handler function.

But it is not working the way I expect it to.

For example, if I run this code:

```<code>var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = function () {
        console.log("this.id: " + this.id);
        console.log("entry.id: " + entry.id);
    };

}
</code>```

What I expect is:

```<code>this.id: 1
entry.id: 1

this.id: 2
entry.id: 2

this.id: 3
entry.id: 3
</code>```

But what I get is:

```<code>this.id: 1
entry.id: 3

this.id: 2
entry.id: 3

this.id: 3
entry.id: 3
</code>```

Why is the entry object always the entry with the id 3?

How can I get the correct entry object inside the click event handler?

答:
One way to fix this is:

```<code>var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = (function (id) {
        return function () {
            console.log("this.id: " + this.id);
            console.log("entry.id: " + id);
        };
    })(entry.id);

}
</code>```

You can use a self-executing function (whose purpose is to provide a closure that entry.id will be bound to) to return you a new onclick handler that is bound to the particular id.

If you don't do this, all your onclick handlers get bound to the same entry variable and end up with the last value it received during the for loop.

Body:
I am trying to get an object inside the onclick event handler function.

But it is not working the way I expect it to.

For example, if I run this code:

var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = function () {
        console.log("this.id: " + this.id);
        console.log("entry.id: " + entry.id);
    };

}

What I expect is:

this.id: 1
entry.id: 1

this.id: 2
entry.id: 2

this.id: 3
entry.id: 3

But what I get is:

this.id: 1
entry.id: 3

this.id: 2
entry.id: 3

this.id: 3
entry.id: 3

Why is the entry object always the entry with the id 3?

How can I get the correct entry object inside the click event handler?

Body:
One way to fix this is:

var entries = [{id: 1},{id: 2},{id: 3}];

for (var i = 0; i < entries.length; i++) {

    var entry = entries[i];

    document.getElementById(entry.id).onclick = (function (id) {
        return function () {
            console.log("this.id: " + this.id);
            console.log("entry.id: " + id);
        };
    })(entry.id);

}

You can use a self-executing function (whose purpose is to provide a closure that entry.id will be bound to) to return you a new onclick handler that is bound to the particular id.

If you don't do this, all your onclick handlers get bound to the same entry variable and end up with the last value it received during the for loop.


来源: stackexchange

问:
Could not find or load main class org.gradle.launcher.GradleMain
I am trying to build build.xml file to to build Elasticsearchproject. Simply the build file is called the gradle build and then run the tests. However I am getting error regarding gradle. This is the first time for me using gradle. The error is

```<code>    Could not find or load main class org.gradle.launcher.GradleMain
</code>```

I already set the PATH and GRADLE_HOME in variable environment . I am using version 3.3.
This this part of the code of build.xml where I am calling the gradle

```<code>  <target name="compile" description="Compile the  source code.">
    <exec executable="/bin/bash">
        <arg value="gradle"/>
        <arg value="build"/>
    </exec>
  </target>
</code>```

Am I missing something?

Any suggestion that could solve this problem.
This question had asked before but there is only one answer and it did not solve the problem.

Error: Could not find or load main class org.gradle.launcher.GradleMain

Thanks

答:
I was getting this error, so I checked the zip file that I had downloaded with unzip -t gradle.zip and it got me some errors. So I downloaded it again and unzip again. Check if the unzip folder has all the *.jar files at the lib folder.
After that add the path of the gradle bin folder to your PATH variable. I did not included any other dependencies or any other variable to the path.

The problem is that gradle cannot find the gradle wrapper.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to build build.xml file to to build Elasticsearchproject. Simply the build file is called the gradle build and then run the tests. However I am getting error regarding gradle. This is the first time for me using gradle. The error is

    Could not find or load main class org.gradle.launcher.GradleMain

I already set the PATH and GRADLE_HOME in variable environment . I am using version 3.3.
This this part of the code of build.xml where I am calling the gradle

  <target name="compile" description="Compile the  source code.">
    <exec executable="/bin/bash">
        <arg value="gradle"/>
        <arg value="build"/>
    </exec>
  </target>

Am I missing something?

Any suggestion that could solve this problem.
This question had asked before but there is only one answer and it did not solve the problem.

Error: Could not find or load main class org.gradle.launcher.GradleMain

Thanks


问:
Wrap img in div on click
I would like to wrap an image in a div element when the image is clicked. Once this is done, I would like to add a class attribute on the div. I'm looking for a utility in jQuery that could help achieve the first task.

```<code>$(img).on('click', function() {
   // wrap this image in div
})
</code>```

While a jQuery implementation is preferable, vanilla dom scripting is ok as well.

答:
```<code>$(this).wrap("<div class='new'></div>");
</code>```

The wrap function of jQuery should be your best bet. This would refer to the clicked  but you can be more precise if you want.

http://api.jquery.com/wrap/

Title: Wrap img in div on click

Body:
I would like to wrap an image in a div element when the image is clicked. Once this is done, I would like to add a class attribute on the div. I'm looking for a utility in jQuery that could help achieve the first task.

$(img).on('click', function() {
   // wrap this image in div
})

While a jQuery implementation is preferable, vanilla dom scripting is ok as well.

Body:
$(this).wrap("<div class='new'></div>");

The wrap function of jQuery should be your best bet. This would refer to the clicked  but you can be more precise if you want.

http://api.jquery.com/wrap/


问:
Need div to return to previous background color with JavaScript (no jquery)
I am close to finishing this but as a relative noobie to JavaScript I am not quite there. I have created a pop-up to alert users that their session will time out. While the pop-up is up, I am turning the DIV on the main page to have a background color of gray. Once the pop-up goes away, I want the DIV to return to its original state. I have tried using a setTimeout, but I am doing it incorrectly. It would also be nice to know how to make the "Continue Session" button make the pop-up go away.

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
For your security, this session is about to end due to inactivity.
<button id="contBtn" type="button">Continue Session</button>
';
  setTimeout(function() {
    document.getElementById('example').innerHTML = '';
  }, 10000);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}</code>```

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

```

答:
To reset the color of the page, you could use a click handler on your modal button, like this:

```<code>document.getElementById('contBtn').addEventListener('click', function() {
  document.getElementById('e1').style.backgroundColor = "white";
});
</code>```

When the modal button is clicked, the page background resets to white (or whatever color you want to use).

Here's a (slightly streamlined) working example, which also hides the modal when the modal button is clicked:

var example = document.getElementById('example');

document.getElementById('contBtn').addEventListener('click', hideModal); // hide modal on click

function addAlert(event) {
  setTimeout(hideModal, 10000); // hide modal on timeout
}

function setBgColorById(id, sColor) {
  if (example.style.display == "inline-block") { // if modal already visible
    return;
  }
  example.style.display = "inline-block";
  addAlert();
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}

function hideModal() { // hide modal on click or timeout
  document.getElementById('e1').style.backgroundColor = "white"; // reset background color
  example.style.display = "none"; // hide modal
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
  display: none;
}</code>```

      <svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>

For your security, this session is about to end due to inactivity.

    <button id="contBtn" type="button">Continue Session</button>

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

```

I moved the HTML for your modal into the HTML section, rather than adding it with JavaScript; feel free to move it back if you want. I also removed a couple of variables that weren't needed and shortened up some of the code.

Body:
I am close to finishing this but as a relative noobie to JavaScript I am not quite there. I have created a pop-up to alert users that their session will time out. While the pop-up is up, I am turning the DIV on the main page to have a background color of gray. Once the pop-up goes away, I want the DIV to return to its original state. I have tried using a setTimeout, but I am doing it incorrectly. It would also be nice to know how to make the "Continue Session" button make the pop-up go away.

window.addEventListener('load', function() {
  var button = document.getElementById('alert-trigger');
  button.addEventListener('click', addAlert);
});

function addAlert(event) {
  var example = document.getElementById('example');
  var template = document.getElementById('example').innerHTML;
  example.innerHTML = template;
  document.getElementById('example').innerHTML = '
<svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
For your security, this session is about to end due to inactivity.
<button id="contBtn" type="button">Continue Session</button>
';
  setTimeout(function() {
    document.getElementById('example').innerHTML = '';
  }, 10000);
}

function setBgColorById(id, sColor) {
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}

[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
}

[role="alert"]:empty {
  display: none;
}

Testing Banner Timeout

This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.

If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.

  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>

Body:
To reset the color of the page, you could use a click handler on your modal button, like this:

document.getElementById('contBtn').addEventListener('click', function() {
  document.getElementById('e1').style.backgroundColor = "white";
});

When the modal button is clicked, the page background resets to white (or whatever color you want to use).

Here's a (slightly streamlined) working example, which also hides the modal when the modal button is clicked:

var example = document.getElementById('example');

document.getElementById('contBtn').addEventListener('click', hideModal); // hide modal on click

function addAlert(event) {
  setTimeout(hideModal, 10000); // hide modal on timeout
}

function setBgColorById(id, sColor) {
  if (example.style.display == "inline-block") { // if modal already visible
    return;
  }
  example.style.display = "inline-block";
  addAlert();
  var elem;
  if (document.getElementById) {
    if (elem = document.getElementById(id)) {
      if (elem.style) {
        elem.style.backgroundColor = sColor;
        return 1; // success
      }
    }
  }
  return 0; // failure
}

function hideModal() { // hide modal on click or timeout
  document.getElementById('e1').style.backgroundColor = "white"; // reset background color
  example.style.display = "none"; // hide modal
}

[role="alert"] {
  padding: 10px;
  background: #ffffff;
  border: 1px solid;
  border-color: #000000;
  position: absolute;
  z-index: 1;
  display: none;
}

<div id="example" role="alert">
  <div>
    <span style="display:inline-block;width:28px;height:28px;">
      <svg xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="yui_3_18_1_1_1510613031292_67-title" viewBox="0 0 48 48" focusable="false"><title>Timeout Warning</title><path class="svgMainColor-yui_3_18_1_1_1510613031292_67" d="M 32.4 29.15 h 3.53 l -0.47 9.73 h -2.53 Z m 0.17 12.51 a 1.59 1.59 0 1 1 3.19 0 a 1.59 1.59 0 0 1 -3.19 0 Z m 0.5 -20.77 a 1.28 1.28 0 0 1 2.27 0 l 12.51 23.65 a 1.51 1.51 0 0 1 0 1.37 a 1.38 1.38 0 0 1 -1.1 0.74 h -25 a 1.44 1.44 0 0 1 -1.14 -2.06 Z m -13.4 19.73 a 17.73 17.73 0 1 1 19.7 -17.73 l 3.11 5.89 a 21.45 21.45 0 0 0 0.8 -5.78 a 21.64 21.64 0 1 0 -25.54 21.27 Z M 13.12 30 l -1.51 -2.6 l 9.21 -5.34 V 11.88 h 3 l 0.01 11.92 Z" / ></svg>
    </span>
    <p>For your security, this session is about to end due to inactivity.</p>
    <button id="contBtn" type="button">Continue Session</button>
  </div>
</div>
<div id="e1">
  <h1>Testing Banner Timeout</h1>
  <p>This page is supposed to act like the home page. It will timeout after 10 seconds of inactivity.</p>
  <p>If you dismiss the banner before it reaches 10 seconds, you will be able to remain on this page for another 10 seconds, where the banner will appear once again. If you let the banner reach 0, you will be redirected to the login page.</p>
  <button id="alert-trigger" onclick="setBgColorById('e1','#848484');return false;">Display Session Manager</button>
</div>

I moved the HTML for your modal into the HTML section, rather than adding it with JavaScript; feel free to move it back if you want. I also removed a couple of variables that weren't needed and shortened up some of the code.


问:
flow type question mark before or after param?
Can someone explain the difference between:

```<code>function foo(bar: ?string) {
  console.log(bar);
}
</code>```

and:

```<code>function foo(bar?: string) {
  console.log(bar);
}
</code>```

When to use one over the other?

答:
Basically

```<code>bar: ?string
</code>```

accepts a string, null or void:

```<code>foo("test");
foo(null);
foo()
</code>```

While

```<code>bar?: string
</code>```

Accepts only a string or void:

```<code>foo("test");
foo();
</code>```

As passing null instead of a string is somewhat senseless, theres no real life difference between them.

Body:
Can someone explain the difference between:

function foo(bar: ?string) {
  console.log(bar);
}

and:

function foo(bar?: string) {
  console.log(bar);
}

When to use one over the other?

Body:
Basically

bar: ?string

accepts a string, null or void:

foo("test");
foo(null);
foo()

While

bar?: string

Accepts only a string or void:

foo("test");
foo();

As passing null instead of a string is somewhat senseless, theres no real life difference between them.


问:
How to get the frame using camera2 api
I am using camera2 api to get the camera frames and this is the code I have written

```<code>private void startPreview() {
    SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
    surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface previewSurface = new Surface(surfaceTexture);

    try {
        mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mCaptureRequestBuilder.addTarget(previewSurface);

        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        try {
                            session.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    new CameraCaptureSession.CaptureCallback() {

                                        @Override
                                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                                            super.onCaptureCompleted(session, request, result);
                                            Log.i("State preview", "process: frame");

                                        }
                                    }, mBackgoundThreadHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                        Toast.makeText(getApplicationContext(),
                                "Unable to setup camera preview", Toast.LENGTH_SHORT).show();
                    }
                }, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}
</code>```

I am able to see the frame log through this line:

```<code>session.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    new CameraCaptureSession.CaptureCallback() {

                                        @Override
                                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                                            super.onCaptureCompleted(session, request, result);
                                            Log.i("State preview", "process: frame");

                                        }
                                    }, mBackgoundThreadHandler);
</code>```

So from this function how do I get the frame.
I am totally new to camera2 api so could someone please help me.

答:
Your code just currently drawing camera preview to your TextureView; if you want a second output that your application code can read, you need to create a second output and give it to camera.

Depending on what kind of processing you want to do, you want either a ImageReader for Java-level access, a SurfaceTexture (for reading in OpenGL), or a Allocation (for RenderScript).  From each of these, you can get a Surface to include in the session creation and in creating the capture request.

Each of them has a callback that fires when new frames become available. onCaptureCompleted only provides the capture metadata.

Title: How to get the frame using camera2 api

Body:
I am using camera2 api to get the camera frames and this is the code I have written

private void startPreview() {
    SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture();
    surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
    Surface previewSurface = new Surface(surfaceTexture);

    try {
        mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mCaptureRequestBuilder.addTarget(previewSurface);

        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface),
                new CameraCaptureSession.StateCallback() {
                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession session) {
                        try {
                            session.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    new CameraCaptureSession.CaptureCallback() {

                                        @Override
                                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                                            super.onCaptureCompleted(session, request, result);
                                            Log.i("State preview", "process: frame");

                                        }
                                    }, mBackgoundThreadHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                        Toast.makeText(getApplicationContext(),
                                "Unable to setup camera preview", Toast.LENGTH_SHORT).show();
                    }
                }, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

}

I am able to see the frame log through this line:

session.setRepeatingRequest(mCaptureRequestBuilder.build(),
                                    new CameraCaptureSession.CaptureCallback() {

                                        @Override
                                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                                            super.onCaptureCompleted(session, request, result);
                                            Log.i("State preview", "process: frame");

                                        }
                                    }, mBackgoundThreadHandler);

So from this function how do I get the frame.
I am totally new to camera2 api so could someone please help me.


问:
Iterate over struct and perform database queries
So I'm new to go and I come from a javascript/node background and for practice, I've been rewriting some of my javascript code into go.

I have a situation where I have an struct (in node it was my object) and I need to iterate over it and perform two database queries. I have something that works but it seems costly and repetitive.

Struct:

```<code>type SiteUsers struct {
    Active struct {
        Moderators []string `json:"moderators"`
        Admins     []string `json:"admins"`
        Regulars   []string `json:"regulars"`
    } `json:"active"`
}
</code>```

Then in the function where I handle an api request that returns JSON binded to this struct I use a for range loop for each role under active. For each one I perform the same first query and then a second one that is specific to each one.

```<code>v := getSiteUsers(&usrs, website)

for _, moderators := range v.Active.Moderators {
    // Insert into user table
    // Insert into user table with role of moderator
}

for _, admins := range v.Active.Admins {
    // Insert into user table
    // Insert into user table with role of admin
}

for _, regulars := range v.Active.Regulars {
    // Insert into user table
    // Insert into user table with role of regular
}
</code>```

This method will work but it doesn't feel completely right and I would love to get some input from people experienced with go.

答:
Would something like this be better?</p>

```<code>v := getSiteUsers(&usrs, website)

insertUsers := func(users []string, role roleType) {
    for _, user := range users {
        // Insert into user table
        // Insert into user table with given role
    }
}

insertUsers(v.Active.Moderators, moderatorRole)
insertUsers(v.Active.Admins, adminRole)
insertUsers(v.Active.Regulars, regularRole)
</code>```

Body:
So I'm new to go and I come from a javascript/node background and for practice, I've been rewriting some of my javascript code into go.

I have a situation where I have an struct (in node it was my object) and I need to iterate over it and perform two database queries. I have something that works but it seems costly and repetitive.

Struct:

type SiteUsers struct {
    Active struct {
        Moderators []string `json:"moderators"`
        Admins     []string `json:"admins"`
        Regulars   []string `json:"regulars"`
    } `json:"active"`
}

Then in the function where I handle an api request that returns JSON binded to this struct I use a for range loop for each role under active. For each one I perform the same first query and then a second one that is specific to each one.

v := getSiteUsers(&usrs, website)

for _, moderators := range v.Active.Moderators {
    // Insert into user table
    // Insert into user table with role of moderator
}

for _, admins := range v.Active.Admins {
    // Insert into user table
    // Insert into user table with role of admin
}

for _, regulars := range v.Active.Regulars {
    // Insert into user table
    // Insert into user table with role of regular
}

This method will work but it doesn't feel completely right and I would love to get some input from people experienced with go.

Body:
Would something like this be better?

v := getSiteUsers(&usrs, website)

insertUsers := func(users []string, role roleType) {
    for _, user := range users {
        // Insert into user table
        // Insert into user table with given role
    }
}

insertUsers(v.Active.Moderators, moderatorRole)
insertUsers(v.Active.Admins, adminRole)
insertUsers(v.Active.Regulars, regularRole)


问:
Get the value of select jquery
```<code><select id="my-select">
<option value="1">This is one</option>
<option value="2" selected>This is two</option>
...
</select>
</code>```

Is there a way to get the text value of the selected option?

```<code>$('#my-select').val();
</code>```

gives me 2, i want to get This is Two instead.

How?

答:
What you want is

Get the selector for finding the selected option in the select box

Use .text() on the selector.

```<code>$('#my-select option:selected').text();
</code>```

See a working demo

ContentLicense: CC BY-SA 2.5

Title: Get the value of select jquery

Body:
<select id="my-select">
<option value="1">This is one</option>
<option value="2" selected>This is two</option>
...
</select>

Is there a way to get the text value of the selected option?

$('#my-select').val();

gives me 2, i want to get This is Two instead.

How?

Body:
What you want is

Get the selector for finding the selected option in the select box

Use .text() on the selector.

$('#my-select option:selected').text();

See a working demo


问:
Rails: jquery autocomplete in a search form
I'm trying to implement jquery autocomplete in a search, but the autocomplete dropdown suggestion doesn't appear.

This is the basic search I have inside the item.rb:

```<code>def self.search(term)
  return where("0=1") if term !~ /\w{4}/
  where("lower(title) LIKE lower(:term)", term: "%#{term}%")
end
</code>```

and inside the application.html.erb I have <%= javascript_include_tag 'application' %>

Now this is the setup I have regarding the autocomplete.... I have a sass bootstrap setup on my app and this is what I have done thus far:

Installed the gem 'jquery-ui-sass-rails'.

Added //= require jquery.ui.all in my application.js file.

Added the following jQuery inside the items.cooffee file

```<code>jQuery ->
  $('#search').autocomplete
    source: "/search_suggestions"
</code>```

Created the controller and model:

```<code>rails g resource search_suggestion term popularity:integer
rails db:migrate

class SearchSuggestionsController < ApplicationController
  def index
    render json: SearchSuggestion.terms_for(params[:term])
  end
end

class SearchSuggestion < ApplicationRecord

  def self.terms_for(prefix)
    suggestions = where("term like ?", "#{prefix}_%")
    suggestions.order("popularity desc").limit(10).pluck(:term)
  end

  def self.index_items
    Item.find_each do |item|
      index_term(item.title)
      item.title.split.each { |t| index_term(t) }
      index_term(item.category)
    end
  end

  def self.index_term(term)
    where(term: term.to_s.downcase.gsub(/\s+/, '')).first_or_initialize.tap do |suggestion|
      suggestion.increment! :popularity
    end
  end
end
</code>```

created and tested the following rake task

search_suggestions.rake

```<code>namespace :search_suggestions do
  desc "Generate search suggestions from items"
  task :index => :environment do
    SearchSuggestion.index_items
  end
end
</code>```

and finally the search form looks like this:

```<code><%= form_tag items_path, method: :get do %>
   <%= text_field_tag :search, params[:search], autofocus: true, placeholder: 'Enter keyword', data: {autocomplete_source: items_path} , :class=> "search-query search_size" %>
      <%= submit_tag 'Search', :style => "display: none;" %>
</code>```

Any ideas what I might be missing here?

Update 1

I changed the gem to gem 'jquery-ui-rails'

and have this inside the application.js file:

```<code>//= require rails-ujs
//= require jquery-ui/widgets/autocomplete
//= require bootstrap-sprockets
//= require_tree
</code>```

and if I load the page and inspect the source the jQuery's are loaded it seems, so I have no idea what wrong!!

```<code><script src="/assets/rails-ujs.self-817d9a8cb641f7125060cb18fefada3f35339170767c4e003105f92d4c204e39.js?body=1"></script>
<script src="/assets/jquery-ui/version.self-c8e3d1203da26ea7efdf83c1eabb3f0ba55cb68e463f5ccf0d77bd15ce6a8e61.js?body=1"></script>
<script src="/assets/jquery-ui/keycode.self-ad63cd20acf49dd333bbbc537454d7d475bd610eb5b88de0dca009f0c3d314b1.js?body=1"></script>
<script src="/assets/jquery-ui/position.self-1b49c8c521e67a4a88bfdad6b4d944d33686d25009a0e40a1e170acdd7b6962a.js?body=1"></script>
<script src="/assets/jquery-ui/safe-active-element.self-a1f1a1a7dae3269ce03f6fffb2dcc9b4a7490f5d546c65d54417bec3be24b668.js?body=1"></script>
<script src="/assets/jquery-ui/unique-id.self-66e85ac85cd0b6b8b1bb89369fc65f608f716869dc0930862a8d421a57a9580a.js?body=1"></script>
<script src="/assets/jquery-ui/widget.self-fca20bcec06d192f97cffa6e734e24360e227237b8ae7d7e7e60754df7d5444f.js?body=1"></script>
<script src="/assets/jquery-ui/widgets/menu.self-0730fe713007bd93e6db569352a20ed92448299505ff6f525bc0dc6dd488254e.js?body=1"></script>
<script src="/assets/jquery-ui/widgets/autocomplete.self-6a89d7a43741ec810ef95de143a7c0297e2e4368ebecff64493ebb7a9ac3a524.js?body=1"></script
</code>```

答:
This is the form erb code

```<code><%= form_tag products_path, method: :get do %>
    <%= text_field_tag :search, params[:search], size: 30 %>
<%= submit_tag "Search", name: nil %>
</code>```

for this element

Inspect that element with your developer tolls and check the id generated from the erb code <%= text_field_tag :search, params[:search], size: 30 %>

This is just an example, I don't have your app. On chrome you simply use the shortcut CTRL + SHIFT + c and then click with the mouse on the element you want to inspect (in this case that input form)

The developer toolbar pops up already selecting that div, you can also do right click and then inspect, with the mouse

I believe text_field_tag :search should have id: 'search', but you are getting error in the console about the variable.

Test this on your chrome developer toolbar console $('#search') and see if it return an error or the Javascript object associated to the <input id='search'>

Maybe there is another reason. You are wondering if this is connected to jquery-ui, then check if you have the jquery-ui assets in the asset pipeline in the sources of your chrome developer tools

Or go in your console, test the jquery-ui effect in your page

```<code>$( "div" ).effect( "bounce", "slow" );
</code>```

Debug this,

first. find out if you can trigger a breakpoint in this code

```<code>$('#search').autocomplete
</code>```

second. test if you can trigger a breakpoint in this code

```<code>class SearchSuggestionsController < ApplicationController
  def index
    binding.pry
    render json: %w[foo bar]
  end
end
</code>```

Also you need to understand that to achieve this, your app is using AJAX asynchronous request, so that your page without refreshing calls the server and gets the response json: %w[foo bar] with the element to display in the search suggestions

This is why you are calling source: "/search_suggestions" in your jquery-ui effect, because that is where you client/jquery is expecting to retrieve the search results

Jquery will hit your server at the url source: "/search_suggestions" and your server will return foo bar in json format, without reloading the webbrowser, jquery will display it

This is explained well on the ruby on rails documentation and in several videos

https://www.youtube.com/watch?v=I0crKwijP0Q

https://www.youtube.com/watch?v=FBxVN7U1Qsk

https://www.youtube.com/watch?v=fEYx8dQr_cQ&t=4s

I could keep writing and write you the code to fix quickly your problem, the reality is that you will never become auto-sufficient if you do not do the required training and understand the concepts and architecture behind this functionality

AJAX is supercool and I really wish you to enjoy those vides

Good luck
Bye
Fabrizio

Body:
I'm trying to implement jquery autocomplete in a search, but the autocomplete dropdown suggestion doesn't appear.

This is the basic search I have inside the item.rb:

def self.search(term)
  return where("0=1") if term !~ /\w{4}/
  where("lower(title) LIKE lower(:term)", term: "%#{term}%")
end

and inside the application.html.erb I have <%= javascript_include_tag 'application' %>

Now this is the setup I have regarding the autocomplete.... I have a sass bootstrap setup on my app and this is what I have done thus far:

Installed the gem 'jquery-ui-sass-rails'.

Added //= require jquery.ui.all in my application.js file.

Added the following jQuery inside the items.cooffee file

jQuery ->
  $('#search').autocomplete
    source: "/search_suggestions"

Created the controller and model:

rails g resource search_suggestion term popularity:integer
rails db:migrate

class SearchSuggestionsController < ApplicationController
  def index
    render json: SearchSuggestion.terms_for(params[:term])
  end
end

class SearchSuggestion < ApplicationRecord

  def self.terms_for(prefix)
    suggestions = where("term like ?", "#{prefix}_%")
    suggestions.order("popularity desc").limit(10).pluck(:term)
  end

  def self.index_items
    Item.find_each do |item|
      index_term(item.title)
      item.title.split.each { |t| index_term(t) }
      index_term(item.category)
    end
  end

  def self.index_term(term)
    where(term: term.to_s.downcase.gsub(/\s+/, '')).first_or_initialize.tap do |suggestion|
      suggestion.increment! :popularity
    end
  end
end

created and tested the following rake task

search_suggestions.rake

namespace :search_suggestions do
  desc "Generate search suggestions from items"
  task :index => :environment do
    SearchSuggestion.index_items
  end
end

and finally the search form looks like this:

<%= form_tag items_path, method: :get do %>
   <%= text_field_tag :search, params[:search], autofocus: true, placeholder: 'Enter keyword', data: {autocomplete_source: items_path} , :class=> "search-query search_size" %>
      <%= submit_tag 'Search', :style => "display: none;" %>

Any ideas what I might be missing here?

Update 1

I changed the gem to gem 'jquery-ui-rails'

and have this inside the application.js file:

//= require rails-ujs
//= require jquery-ui/widgets/autocomplete
//= require bootstrap-sprockets
//= require_tree

and if I load the page and inspect the source the jQuery's are loaded it seems, so I have no idea what wrong!!

Body:
This is the form erb code

<%= form_tag products_path, method: :get do %>
    <%= text_field_tag :search, params[:search], size: 30 %>
<%= submit_tag "Search", name: nil %>

for this element

Inspect that element with your developer tolls and check the id generated from the erb code <%= text_field_tag :search, params[:search], size: 30 %>

This is just an example, I don't have your app. On chrome you simply use the shortcut CTRL + SHIFT + c and then click with the mouse on the element you want to inspect (in this case that input form)

The developer toolbar pops up already selecting that div, you can also do right click and then inspect, with the mouse

I believe text_field_tag :search should have id: 'search', but you are getting error in the console about the variable.

Test this on your chrome developer toolbar console $('#search') and see if it return an error or the Javascript object associated to the <input id='search'>

Maybe there is another reason. You are wondering if this is connected to jquery-ui, then check if you have the jquery-ui assets in the asset pipeline in the sources of your chrome developer tools

Or go in your console, test the jquery-ui effect in your page

$( "div" ).effect( "bounce", "slow" );

Debug this,

first. find out if you can trigger a breakpoint in this code

$('#search').autocomplete

second. test if you can trigger a breakpoint in this code

class SearchSuggestionsController < ApplicationController
  def index
    binding.pry
    render json: %w[foo bar]
  end
end

Also you need to understand that to achieve this, your app is using AJAX asynchronous request, so that your page without refreshing calls the server and gets the response json: %w[foo bar] with the element to display in the search suggestions

This is why you are calling source: "/search_suggestions" in your jquery-ui effect, because that is where you client/jquery is expecting to retrieve the search results

Jquery will hit your server at the url source: "/search_suggestions" and your server will return foo bar in json format, without reloading the webbrowser, jquery will display it

This is explained well on the ruby on rails documentation and in several videos

https://www.youtube.com/watch?v=I0crKwijP0Q

https://www.youtube.com/watch?v=FBxVN7U1Qsk

https://www.youtube.com/watch?v=fEYx8dQr_cQ&t=4s

I could keep writing and write you the code to fix quickly your problem, the reality is that you will never become auto-sufficient if you do not do the required training and understand the concepts and architecture behind this functionality

AJAX is supercool and I really wish you to enjoy those vides

Good luck
Bye
Fabrizio


问:
How to filter a typed Spark Dataset using pattern matching
I try to jump on the typed Dataset API but I'm stuck with filtering:

```<code>val ds: Dataset[(Int, Int)] = Seq((1,1)).toDS

ds.filter(ij => ij._1 > ij._2) // does work, but is not readable
ds.filter{case (i,j) => i<j} // does not work
</code>```

Error:(36, 14) missing parameter type for expanded function The
  argument types of an anonymous function must be fully known. (SLS 8.5)
  Expected type was: ?

I don't understand why pattern matching does not work with filter, while it works fine with map:

```<code>ds.map{case (i,j) => i+j}
</code>```

答:
This is a little bit more readable:

```<code>val ds: Dataset[(Int, Int)] = Seq((1,1)).toDS
ds.filter('_1 > '_2)
</code>```

Note: you need to import spark.implicits._

Body:
I try to jump on the typed Dataset API but I'm stuck with filtering:

val ds: Dataset[(Int, Int)] = Seq((1,1)).toDS

ds.filter(ij => ij._1 > ij._2) // does work, but is not readable
ds.filter{case (i,j) => i<j} // does not work

Error:(36, 14) missing parameter type for expanded function The
  argument types of an anonymous function must be fully known. (SLS 8.5)
  Expected type was: ?

I don't understand why pattern matching does not work with filter, while it works fine with map:

ds.map{case (i,j) => i+j}

Body:
This is a little bit more readable:

val ds: Dataset[(Int, Int)] = Seq((1,1)).toDS
ds.filter('_1 > '_2)

Note: you need to import spark.implicits._


答:
You can use JQuery wrap function  here is the wrap

var img=document.getElementById('img1')
$(img).on('click', function() {
   $(this).wrap('

')
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="img1"></code>```

Title: Wrap img in div on click

Body:
You can use JQuery wrap function  here is the wrap

var img=document.getElementById('img1')
$(img).on('click', function() {
   $(this).wrap('<div class="newClass"></div>')
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="img1">


问:
delim command only reading parts of a txt file
I'm a newbie to programming.

I have a txt fileA containing the list of files within a directory.

Scenario:
I'm running the delim command to remove new line special character codes and replace with commas from the list of jpg file names (cicra 10000) in the txt fileA and output the result to output fileB.

Problem:
Only a random amount of file names reach the output file! Some or many are missing.

Here's the code...

========================================

```<code>dir /o /b > fileA.txt
set "txt="
for /f "delims=" %%a in (fileA.txt) do (
  set "txt=!txt!%%a,"
)
set "txt=!txt:~0,-1!"
>fileB.txt echo !txt!
</code>```

=========================================

Any help appreciated :)
Thank you

答:
The problem is that you are collecting all data in a single string, so you quickly reach the limit of about 8190 characters/bytes for strings in the Windows command prompt cmd.

One way to work around that is to use set/P, which is intended to prompt the user for the value of a variable, using a display message; this message is output without any trailing line-breaks:

> "fileA.txt" dir /O /B
> "fileB.txt" < nul (
    set "FLAG=#"
    for /F "usebackq delims= eol=|" %%a in ("fileA.txt") do @(
        if defined FLAG (
            set /P ="%%a"
            set "FLAG="
        ) else (
            set /P =",%%a"
        )
    )
)
```

<p>Actually you do not need the interim file <code>fileA.txt</code>:</p>

<pre class="lang-cmd prettyprint-override"><code>> "fileB.txt" < nul (
    set "FLAG=#"
    for /F "delims= eol=|" %%a in ('dir /O /B') do @(
        if defined FLAG (
            set /P ="%%a"
            set "FLAG="
        ) else (
            set /P =",%%a"
        )
    )
)
</code>```

However, there are the following restrictions:

a single item must not contain more than 1021 characters/bytes (this is a limitation of set /P);

leading white-spaces (and also some trailing ones) become lost;

no string must begin with an = sign (a syntax error arises in case);

Body:
I'm a newbie to programming.

I have a txt fileA containing the list of files within a directory.

Scenario:
I'm running the delim command to remove new line special character codes and replace with commas from the list of jpg file names (cicra 10000) in the txt fileA and output the result to output fileB.

Problem:
Only a random amount of file names reach the output file! Some or many are missing.

Here's the code...

========================================

dir /o /b > fileA.txt
set "txt="
for /f "delims=" %%a in (fileA.txt) do (
  set "txt=!txt!%%a,"
)
set "txt=!txt:~0,-1!"
>fileB.txt echo !txt!

=========================================

Any help appreciated :)
Thank you

Body:
The problem is that you are collecting all data in a single string, so you quickly reach the limit of about 8190 characters/bytes for strings in the Windows command prompt cmd.

One way to work around that is to use set/P, which is intended to prompt the user for the value of a variable, using a display message; this message is output without any trailing line-breaks:

> "fileA.txt" dir /O /B
> "fileB.txt" < nul (
    set "FLAG=#"
    for /F "usebackq delims= eol=|" %%a in ("fileA.txt") do @(
        if defined FLAG (
            set /P ="%%a"
            set "FLAG="
        ) else (
            set /P =",%%a"
        )
    )
)

Actually you do not need the interim file fileA.txt:

> "fileB.txt" < nul (
    set "FLAG=#"
    for /F "delims= eol=|" %%a in ('dir /O /B') do @(
        if defined FLAG (
            set /P ="%%a"
            set "FLAG="
        ) else (
            set /P =",%%a"
        )
    )
)

However, there are the following restrictions:

a single item must not contain more than 1021 characters/bytes (this is a limitation of set /P);

leading white-spaces (and also some trailing ones) become lost;

no string must begin with an = sign (a syntax error arises in case);


问:
Is using output buffering considered a bad practice?
Are ob_start / ob_get_clean() considered bad practice by php programmers in general?

Are there any disadvantages of output buffering?

答:
It's not considered bad (or good). Some people like it, some don't
Personally I think there are reasons not to use it. I think of it as a last resort. Sometimes you may have situation where output buffering may be your only choice to solve a particular problem, so save this option for just such situations.

I don't think there is any performance gain or speeding up of page load by using it, but it also depends on what server you using and if you using php as mod_php or as cgi or fastcgi.


问:
Azure Cosmos DB Implementation Failure
I'm having a problem whenever I try to create a new Cosmos DB database through Azure Portal. I'm using a free subscription so I do not have access to CosmosDB support.

Basically, all values seem to be valid but after creation everything fails. I'm doing the following:

Input a unique ID with no spaces or uppercases or symbols.

Chose "Azure Table" as API type.

Use my "Free Trial" subscription.

Create a new resource group (again with no spaces or uppercases of symbols).

Choose a server in either "South UK" and "North Europe" (tried both on different tries).

Whenever I click finish, after some seconds, I get the following message:

Invalid capability EnableTable. ActivityId: ...

  Microsoft.Azure.Documents.Common/1.10.106.1 (Code: BadRequest)

Error Message:

{
   "code": "BadRequest",
 "message": "Invalid capability
  EnableTable.\r\nActivityId: 9cb0e2eb-3b62-4bda-a0f9-e3945eb8148b,
  Microsoft.Azure.Documents.Common/1.19.106.1"
}

I also tried Edge and Chrome and neither work. I find funny that Microsoft says that we can try Azure's CosmosDB for free but in fact we can't because creation fails and they offer no support for free.

答:
You need to use the below url and select the required service to try Cosmos DB free.
I just created one Cosmos SQL DB for free.

https://azure.microsoft.com/en-us/try/cosmosdb/

Title: Azure Cosmos DB Implementation Failure


问:
Calculate number of business days between two dates
I have requirement to calculate number of business days between two given dates

I have the list of holidays as an Array list provided by the user.

So I can investigate each and every day between the dates and check if its weekday and not federal holiday like the code I provided below (which is working fine)

But this is very expensive, lets say 12 federal holidays and each day I will   have to check its not a weekend,

so if I need to count between 5 years it will take 365 * 5 * 12  its 21,000  iterations! its crazy (not even including the calculation for business day)

Is there a better way?

```<code>package test;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;

public class TestDiff {

    public static void main(String[] args) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
        // add 4 years as an example
        Date fromDate = formatter.parse("11/06/2017"),toDate = formatter.parse("11/29/2017");// DateUtils.addDays(fromDate,365 * 4);
        int numberOfDaysCount=0;
        int daysBetween  = daysBetween(fromDate,toDate);
        Date caurDate = fromDate;

        for(int i=0;i<=daysBetween ; i++ ) {
            if(isWeekDay(caurDate) && !isFederalHoliday(caurDate) )
                numberOfDaysCount++;
            caurDate = DateUtils.addDays(caurDate,1); // add one day
        }
        System.out.println("number of business days between "+fromDate+" and "+toDate+" is: "+numberOfDaysCount);
    }

   private static boolean isWeekDay(Date caurDate) {
             Calendar c = Calendar.getInstance();
             c.setTime(caurDate);
              int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
              return dayOfWeek!= Calendar.SATURDAY && dayOfWeek!= Calendar.SUNDAY ;
    }

        private static boolean isFederalHoliday(Date caurDate) throws ParseException {
            DateFormat formatter = new SimpleDateFormat("MM/dd/yy");    //list will come from dao.getFederalHoliday();
                List<Date> federalHolidays =  Arrays.asList(formatter.parse("01/02/2017"),formatter.parse("01/16/2017"),formatter.parse("02/20/2017"),formatter.parse("05/29/2017"),formatter.parse("07/04/2017"),formatter.parse("09/04/2017"),formatter.parse("10/09/2017"),formatter.parse("07/04/2017"),formatter.parse("11/10/2017"),formatter.parse("11/23/2017"),formatter.parse("12/25/2017"));
                for (Date holiday : federalHolidays) {
                    if(DateUtils.isSameDay(caurDate,holiday)) //using Apache commons-lang
                        return true;
                }
                return false;
    }

        public static int daysBetween(Date d1, Date d2){
             return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
     }

}
</code>```

答:
There are many example already given in the comments to calculate how many weekdays are between the two dates.

As far as subtracting the the federal holidays goes. Instead of looping over all the days in your fromdate-todate range, why don't you loop over all the entries in your federalHoliday array once per year in your fromDate-toDate range.

Excuse the pseudo code:

```<code>int workdays = getWeekdayCount();
for(int i = 0, count = getYearsBetween(); i < count; ++i)
{
    startIndex = (i==0?getIndexFirstHoliday():0);
    endIndex   = (i==(count-1)?getIndexLastHoliday():11);
    for(; startIndex <= endIndex; ++startIndex)
    {
        if(!federalHolidays[startIndex].IsWeekday(count))
            workdays--;
    }
}
</code>```

getWeekdayCount: gets you all of the weekdays in the range.

getIndexFirstHoliday: loops through your federalHolidays array and returns the first index where the date is bigger than the fromDate

getIndexLastHoliday: loops through your federalHolidays array (backwards) and returns the last index where the date is smaller than the toDate.

isWeekday: determines if the date is a weekday in the year you're looping through (if it is, it's already been discarded in getWeekdayCount so we don't need to subtract!)

This way, you're looping max 12 times per year, plus another 2 * 12 to get the first and the last index.

Body:
I have requirement to calculate number of business days between two given dates

I have the list of holidays as an Array list provided by the user.

So I can investigate each and every day between the dates and check if its weekday and not federal holiday like the code I provided below (which is working fine)

But this is very expensive, lets say 12 federal holidays and each day I will   have to check its not a weekend,

so if I need to count between 5 years it will take 365 * 5 * 12  its 21,000  iterations! its crazy (not even including the calculation for business day)

Is there a better way?

package test;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;

public class TestDiff {

    public static void main(String[] args) throws ParseException {
        DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
        // add 4 years as an example
        Date fromDate = formatter.parse("11/06/2017"),toDate = formatter.parse("11/29/2017");// DateUtils.addDays(fromDate,365 * 4);
        int numberOfDaysCount=0;
        int daysBetween  = daysBetween(fromDate,toDate);
        Date caurDate = fromDate;

        for(int i=0;i<=daysBetween ; i++ ) {
            if(isWeekDay(caurDate) && !isFederalHoliday(caurDate) )
                numberOfDaysCount++;
            caurDate = DateUtils.addDays(caurDate,1); // add one day
        }
        System.out.println("number of business days between "+fromDate+" and "+toDate+" is: "+numberOfDaysCount);
    }

   private static boolean isWeekDay(Date caurDate) {
             Calendar c = Calendar.getInstance();
             c.setTime(caurDate);
              int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
              return dayOfWeek!= Calendar.SATURDAY && dayOfWeek!= Calendar.SUNDAY ;
    }

        private static boolean isFederalHoliday(Date caurDate) throws ParseException {
            DateFormat formatter = new SimpleDateFormat("MM/dd/yy");    //list will come from dao.getFederalHoliday();
                List<Date> federalHolidays =  Arrays.asList(formatter.parse("01/02/2017"),formatter.parse("01/16/2017"),formatter.parse("02/20/2017"),formatter.parse("05/29/2017"),formatter.parse("07/04/2017"),formatter.parse("09/04/2017"),formatter.parse("10/09/2017"),formatter.parse("07/04/2017"),formatter.parse("11/10/2017"),formatter.parse("11/23/2017"),formatter.parse("12/25/2017"));
                for (Date holiday : federalHolidays) {
                    if(DateUtils.isSameDay(caurDate,holiday)) //using Apache commons-lang
                        return true;
                }
                return false;
    }

        public static int daysBetween(Date d1, Date d2){
             return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
     }

}

Body:
There are many example already given in the comments to calculate how many weekdays are between the two dates.

As far as subtracting the the federal holidays goes. Instead of looping over all the days in your fromdate-todate range, why don't you loop over all the entries in your federalHoliday array once per year in your fromDate-toDate range.

Excuse the pseudo code:

int workdays = getWeekdayCount();
for(int i = 0, count = getYearsBetween(); i < count; ++i)
{
    startIndex = (i==0?getIndexFirstHoliday():0);
    endIndex   = (i==(count-1)?getIndexLastHoliday():11);
    for(; startIndex <= endIndex; ++startIndex)
    {
        if(!federalHolidays[startIndex].IsWeekday(count))
            workdays--;
    }
}

getWeekdayCount: gets you all of the weekdays in the range.

getIndexFirstHoliday: loops through your federalHolidays array and returns the first index where the date is bigger than the fromDate

getIndexLastHoliday: loops through your federalHolidays array (backwards) and returns the last index where the date is smaller than the toDate.

isWeekday: determines if the date is a weekday in the year you're looping through (if it is, it's already been discarded in getWeekdayCount so we don't need to subtract!)

This way, you're looping max 12 times per year, plus another 2 * 12 to get the first and the last index.


问:
Remove spacing between two paragraphs when displaying WYSIWIGS with ckeditor 4 in Angular
I'm using Angular 4 with ckeditor 4.x for WYSIWYG.

So when I'm displaying the code from database, the view is not the same in ckeditor, even if there's no style applying with paragraph.

I've tryed to reduce the line-height with CSS but no-way, it's the same result.

I removed the margin between lines but the same matters.

This is the code of the CSS where I've tryed to solve the problem:

p, p + p{
    color:rgb(51, 51, 51);
    display:block;
    font-family:sans-serif, Arial, Verdana, "Trebuchet MS";
    font-size:13px;
    line-height:normal;
    margin: 0;
    word-wrap:break-word;
    -webkit-margin-after:0px;
    -webkit-margin-before:0px;
    -webkit-margin-end:0px;
    -webkit-margin-start:0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>This one line</p>
<p>this is the second lines</p>
<p>And another one</p>
<p>And a last lines</p></code>```

This is the view:

Here's the computed code in dev tools

答: I solve the problem by removing the white-space:pre-wrap;. I Don't kwon why it's add a space between lines.

ContentLicense: CC BY-SA 4.0

Body:
I'm using Angular 4 with ckeditor 4.x for WYSIWYG.

So when I'm displaying the code from database, the view is not the same in ckeditor, even if there's no style applying with paragraph.

I've tryed to reduce the line-height with CSS but no-way, it's the same result.

I removed the margin between lines but the same matters.

This is the code of the CSS where I've tryed to solve the problem:

p, p + p{
    color:rgb(51, 51, 51);
    display:block;
    font-family:sans-serif, Arial, Verdana, "Trebuchet MS";
    font-size:13px;
    line-height:normal;
    margin: 0;
    word-wrap:break-word;
    -webkit-margin-after:0px;
    -webkit-margin-before:0px;
    -webkit-margin-end:0px;
    -webkit-margin-start:0px;
}

This one line

this is the second lines

And another one

And a last lines

This is the view:

Here's the computed code in dev tools


问:
R error: unknown timezone with as.POSIXct()
I am trying to convert a unix epoch timestamps to a date-time object using as.POSIXct()

I need to specify timezones (either Europe/London or UTC) when I call as.POSIXct().

If I run

```<code>> t<-as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01")
> t
</code>```

R returns
    "2015-10-20 09:22:10 BST"
    Warning messages:
    1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
    2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'

I have tried specifying tz="BST", but this also returns warnings

```<code>Warning messages:
1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
3: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
4: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
</code>```

I have looked up the zoneinfo/zone.tab as per Joshua Ulrich's post and "Europe/London" does appear in the zone.tab file, while "BST" does not. So I think that Europe/London should be a valid tz option. Is this correct?

Does anyone have suggestions as to why I am getting warnings, and why the specified timezone is not being assigned to the as.POSIXct object?

It should be noted that my scripts which call as.POSIXct() were running without warnings prior to updating MacOS to High Sierra. Could the OS update lead to these warnings? When I run Sys.timezone() it returns NA

Many thanks in advance

Iris

答:
Looking at the output it is not actually giving a warning about 'Europe/London', just about other variations ('BST' and 'default/Europe/London').

Could it be that it are errors of previous commands still lingering? Do you get the same if run you the as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01") again, or even restart R?

I still get the error about BST even if using the correct timezone

```<code>> as.POSIXct(1445329330, tz="BST", origin="1970-01-01")
[1] "2015-10-20 08:22:10 GMT"
Warning message:
In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST'
> as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01")
[1] "2015-10-20 09:22:10 BST"
Warning message:
In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST'
</code>```

Body:
I am trying to convert a unix epoch timestamps to a date-time object using as.POSIXct()

I need to specify timezones (either Europe/London or UTC) when I call as.POSIXct().

If I run

> t<-as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01")
> t

R returns
    "2015-10-20 09:22:10 BST"
    Warning messages:
    1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
    2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'

I have tried specifying tz="BST", but this also returns warnings

Warning messages:
1: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
2: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'
3: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST
          '
4: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'default/Europe/London'

I have looked up the zoneinfo/zone.tab as per Joshua Ulrich's post and "Europe/London" does appear in the zone.tab file, while "BST" does not. So I think that Europe/London should be a valid tz option. Is this correct?

Does anyone have suggestions as to why I am getting warnings, and why the specified timezone is not being assigned to the as.POSIXct object?

It should be noted that my scripts which call as.POSIXct() were running without warnings prior to updating MacOS to High Sierra. Could the OS update lead to these warnings? When I run Sys.timezone() it returns NA

Many thanks in advance

Iris

Body:
Looking at the output it is not actually giving a warning about 'Europe/London', just about other variations ('BST' and 'default/Europe/London').

Could it be that it are errors of previous commands still lingering? Do you get the same if run you the as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01") again, or even restart R?

I still get the error about BST even if using the correct timezone

> as.POSIXct(1445329330, tz="BST", origin="1970-01-01")
[1] "2015-10-20 08:22:10 GMT"
Warning message:
In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST'
> as.POSIXct(1445329330, tz="Europe/London", origin="1970-01-01")
[1] "2015-10-20 09:22:10 BST"
Warning message:
In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'BST'


问:
Connect to mercurial via ssh on windows
Can anyone point me in the direction of a simple step by step guide as to how to connect to a mercurial repo via ssh on windows. Im really struggling to get my head around it, and so far i jus keep getting a string of errors. Any help would be appreciated.</p>

答:
Assumes: you have a putty suite installed, a ppk and using TortoiseHg.

Here is my original c:\somerepo\.hg\hgrc file:

```<code>[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo
</code>```

So what's happening with ssh?  Let's debug a pull statement, hg pull --debug on the command-line.  I noticed it is running C:\Program Files\TortoiseHg\lib\TortoisePlink.exe instead of ssh to make the call:

```<code>PS C:\somerepo> hg pull --debug
pulling from ssh://hg@bitbucket.org/someuser/somerepo
running "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 hg@bitbucket.org "hg -R someuser/somerepo serve --stdio"
sending hello command
sending between command
abort: no suitable response from remote hg!
</code>```

So let's just reuse the call, add compression (yay!), non-interactive (batch) and our key:

```<code>[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo

[ui]
ssh = "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 -C -batch -i "c:\keys\somekey.ppk"
</code>```

Title: Connect to mercurial via ssh on windows

Body:
Assumes: you have a putty suite installed, a ppk and using TortoiseHg.

Here is my original c:\somerepo\.hg\hgrc file:

[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo

So what's happening with ssh?  Let's debug a pull statement, hg pull --debug on the command-line.  I noticed it is running C:\Program Files\TortoiseHg\lib\TortoisePlink.exe instead of ssh to make the call:

PS C:\somerepo> hg pull --debug
pulling from ssh://hg@bitbucket.org/someuser/somerepo
running "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 hg@bitbucket.org "hg -R someuser/somerepo serve --stdio"
sending hello command
sending between command
abort: no suitable response from remote hg!

So let's just reuse the call, add compression (yay!), non-interactive (batch) and our key:

[paths]
default = ssh://hg@bitbucket.org/someuser/somerepo

[ui]
ssh = "C:\Program Files\TortoiseHg\lib\TortoisePlink.exe" -ssh -2 -C -batch -i "c:\keys\somekey.ppk"


问:
Sort Points Using C++
I have an array of std::vector<cv::Point> that looks like-

```<code>[49, 500]
[49, 129]
[441, 501]
[49, 374]
[440, 374]
[440, 259]
[440, 128]
[49, 260]
</code>```

Let consider array elements as [x, y]. Now I need to get 4 elements from the array having-

lowest x with highest y

lowest x with lowest y

highest x with lowest y

highest x with highest y

currently, I am using functions to sort based on conditions and then fetch a point.

```<code>bool SortForMinXMaxY(const Point & a, const Point &b)
{
    return (a.x < b.x || a.y > b.y) ;
}
</code>```

What should be the standard approach with C++ and OpenCV to achieve the goal?

答:
The C++ sort function your are calling is quicksort, so each elemento will be evaluated multiple times. You need a more strict to make sure each possibility is evaluated by the function.</p>

```<code>bool SortForMinXMaxY(const Point & a, const Point &b)
{
   if ( a.x == b.x )
   {
      return (a.y > b.y);
   }
   if ( a.y == b.y)
   {
      return (a.x < b.x);
   }
   return (a.x < b.x || a.y > b.y);
}
</code>```

Title: Sort Points Using C++

Body:
I have an array of std::vector<cv::Point> that looks like-

[49, 500]
[49, 129]
[441, 501]
[49, 374]
[440, 374]
[440, 259]
[440, 128]
[49, 260]

Let consider array elements as [x, y]. Now I need to get 4 elements from the array having-

lowest x with highest y

lowest x with lowest y

highest x with lowest y

highest x with highest y

currently, I am using functions to sort based on conditions and then fetch a point.

bool SortForMinXMaxY(const Point & a, const Point &b)
{
    return (a.x  b.y) ;
}

What should be the standard approach with C++ and OpenCV to achieve the goal?

Body:
The C++ sort function your are calling is quicksort, so each elemento will be evaluated multiple times. You need a more strict to make sure each possibility is evaluated by the function.

bool SortForMinXMaxY(const Point & a, const Point &b)
{
   if ( a.x == b.x )
   {
      return (a.y > b.y);
   }
   if ( a.y == b.y)
   {
      return (a.x < b.x);
   }
   return (a.x < b.x || a.y > b.y);
}


问:
EXCEL FORMULA IN PIVOT TABLE
How to apply the following excel formula in pivot calculated field.

```<code>=IF(DAY(TODAY())>10,IF(SUM(K2:N2)>499,"Locked",""),IF(SUM(L2:N2)>499,"Locked",""))
</code>```

Please help and advise
Thanks
CSGanesh

答: Calculated Fields can't reference cell references...they can only reference other PivotTable fields. </p>

Title: EXCEL FORMULA IN PIVOT TABLE

Body:
How to apply the following excel formula in pivot calculated field.

=IF(DAY(TODAY())>10,IF(SUM(K2:N2)>499,"Locked",""),IF(SUM(L2:N2)>499,"Locked",""))

Please help and advise
Thanks
CSGanesh


问:
Regex to select all characters that do not match a pattern
I'm weak with regexes but have put together the following regex which selects when my pattern is met, the problem is that i need to select any characters that do not fit the pattern.

```<code>/^\d{1,2}[ ]\d{1,2}[ ]\d{1,2}[ ][AB]/i
</code>```

Correct pattern is:

```<code>## ## ## A|B aka [0 < x <= 90]*space*[0 < x <= 90] [0 < x <= 90] [A|B]
</code>```

EG:

12 34 56 A → good

12 34 56 B  → good

12 34 5.6 A  → bad - select  .

12 34 5.6 C  → bad - select . and C

1A 23 45 6  → bad - select A and 6

Edit:
As my impression was that regex is used to perform validation of both characters and pattern/sequence at the same time. The simple question is how to select characters that do not fit the category of non negative numbers, spaces and distinct characters.

答:
Answer 1

Brief

This isn't really realizable with 1 regex due to the nature of the regex. This answer provides a regex that will capture the last incorrect entry. For multiple incorrect entries, a loop must be used. You can correct the incorrect entries by running some code logic on the resulting captured groups to determine why it isn't valid.

My ultimate suggestion would be to split the string by a known delimiter (in this case the space character  and then using some logic (or even a small regex) to determine why it's incorrect and how to fix it, as seen in Answer 2.

Non-matches

The following logic is applied in my second answer.

For any users wondering what I did to catch incorrect matches: At the most basic level, all this regex is doing is adding |(.*) to every subsection of the regex. Some sections required additional changes for catching specific invalid string formats, but the |(.*) or slight modifications of this will likely solve anyone else's issues.

Other modifications include:

Using opposite tokens

For example: Matching a digit

Original regex: \d

Opposite regex \D

For example: Matching a digit or whitepace

Original regex: [\d\s]

Opposite regex: [^\d\s]

Note [\D\S] is incorrect as it matches both sets of characters, thus, any non-whitespace or non-digit character (since non-whitespace includes digits and non-digits include whitespace, both will be matched)

Negative lookaheads

For example: Catching up to 31 days in a month

Original regex \b(?:[0-2]?\d|3[01])\b

Opposite regex: \b(?![0-2]?\d\b|3[01]\b)\d+\b

Code

First, creating a more correct regex that also ensures 0 < x <= 90 as per the OP's question.

```<code>^(?:(?:[0-8]?\d|90) ){3}[AB]$
</code>```

See regex in use here

```<code>^(?:(?:(?:[0-8]?\d|90) |(\S*) ?)){3}(?:[AB]|(.*))$
</code>```

Note: This regex uses the mi flags (multiline - assuming input is in that format, and case-insensitive)

Other Formats

Realistically, this following regex would be ideal. Unfortunately, JavaScript doesn't support some of the tokens used in the regex, but I feel it may be useful to the OP or other users that see this question.

See regex in use here

```<code>^(?:(?:(?:[0-8]?\d|90) |(?<n>\S*?) |(?<n>\S*?) ?)){3}(?:(?<n>\S*) )?(?:[AB]|(.*))$
</code>```

Results

Input

The first section (sections separated by the extra newline/break) shows valid strings, while the second shows invalid strings.

```<code>0 45 90 A
0 45 90 B

-1 45 90 A
0 45 91 A
12 34 5.6 A
12 34 56 C
1A 23 45 6
11 1A 12 12 A
12 12  A
12 12 A
</code>```

Output

```<code>0 45 90 A        VALID
0 45 90 B        VALID

-1 45 90 A       INVALID: -1
0 45 91 A        INVALID: 91
12 34 5.6 A      INVALID: 5.6
12 34 56 C       INVALID: C
1A 23 45 6       INVALID: 1A, 6
11 1A 12 12 A    INVALID: 12 A
12 12  A         INVALID: (missing value)
12 12 A          INVALID: A, (missing value)
</code>```

Note: The last entry shows an odd output, but that's due to a limitation with JavaScript's regex engine. The Other Formats section describes this and another method to use to properly catch these cases (using a different regex engine)

Explanation

This uses a simple | (OR) and captures the incorrect matches into a capture group.

^ Assert position at the start of the line

(?:(?:(?:[0-8]?\d|90) |(\S*) ?)){3} Match the following exactly 3 times

(?:(?:[0-8]?\d|90) |(.+)) Match either of the following

(?:[0-8]?\d|90) Match either of the following, followed by a space character  literally

[0-8]?\d Match between zero and one of the characters in the set 0-8 (a digit between 0 and 8), followed by any digit

90 Match 90 literally

(\S*) ? Capture any non-whitespace character one or more times into capture group 1, followed by zero or one space character  literally

(?:[AB]|(.*)) Match either of the following

[AB] Match any character present in the set (A or B)

(.*) Capture any character any number of times into capture group 2

$ Assert position at the end of the line

Answer 2

Brief

This method splits the string on the given delimiter and tests each section for the proper set of characters. It outputs a message if the value is incorrect. You would likely replace the console outputs with whatever logic you want use.

Code

var arr = [
  "0 45 90 A",
  "0 45 90 B",
  "-1 45 90 A",
  "0 45 91 A",
  "12 34 5.6 A",
  "12 34 56 C",
  "1A 23 45 6",
  "11 1A 12 12 A",
  "12 12  A",
  "12 12 A"
];

arr.forEach(function(e) {
  var s = e.split(" ");
  var l = s.pop();
  var numElements = 3;
  var maxNum = 90;
  var syntaxErrors = [];
  if(s.length != numElements) {
    syntaxErrors.push(`Invalid number of elements: Number = ${numElements}, Given = ${s.length}`);
  }
  s.forEach(function(v) {
    if(v.match(/\D/)) {
      syntaxErrors.push(`Invalid value "${v}" exists`);
    } else if(!v.length) {
      syntaxErrors.push(`An empty value or double space exists`);
    } else if(Number(v) > maxNum) {
      syntaxErrors.push(`Value greater than ${maxNum} exists: ${v}`);
    }
  });
  if(l.match(/[^AB]/)) {
    syntaxErrors.push(`Last element ${l} in "${e}" is invalid`);
  }
  if(syntaxErrors.length) {
    console.log(`"${e}" [\n\t${syntaxErrors.join('\n\t')}\n]`);
  } else {
    console.log(`No errors found in "${e}"`);
  }
});```

Body:
I'm weak with regexes but have put together the following regex which selects when my pattern is met, the problem is that i need to select any characters that do not fit the pattern.

/^\d{1,2}[ ]\d{1,2}[ ]\d{1,2}[ ][AB]/i

Correct pattern is:

## ## ## A|B aka [0 < x <= 90]*space*[0 < x <= 90] [0 < x <= 90] [A|B]

EG:

12 34 56 A → good

12 34 56 B  → good

12 34 5.6 A  → bad - select  .

12 34 5.6 C  → bad - select . and C

1A 23 45 6  → bad - select A and 6

Edit:
As my impression was that regex is used to perform validation of both characters and pattern/sequence at the same time. The simple question is how to select characters that do not fit the category of non negative numbers, spaces and distinct characters.

Body:
Answer 1

Brief

This isn't really realizable with 1 regex due to the nature of the regex. This answer provides a regex that will capture the last incorrect entry. For multiple incorrect entries, a loop must be used. You can correct the incorrect entries by running some code logic on the resulting captured groups to determine why it isn't valid.

My ultimate suggestion would be to split the string by a known delimiter (in this case the space character  and then using some logic (or even a small regex) to determine why it's incorrect and how to fix it, as seen in Answer 2.

Non-matches

The following logic is applied in my second answer.

For any users wondering what I did to catch incorrect matches: At the most basic level, all this regex is doing is adding |(.*) to every subsection of the regex. Some sections required additional changes for catching specific invalid string formats, but the |(.*) or slight modifications of this will likely solve anyone else's issues.

Other modifications include:

Using opposite tokens

For example: Matching a digit

Original regex: \d

Opposite regex \D

For example: Matching a digit or whitepace

Original regex: [\d\s]

Opposite regex: [^\d\s]

Note [\D\S] is incorrect as it matches both sets of characters, thus, any non-whitespace or non-digit character (since non-whitespace includes digits and non-digits include whitespace, both will be matched)

Negative lookaheads

For example: Catching up to 31 days in a month

Original regex \b(?:[0-2]?\d|3[01])\b

Opposite regex: \b(?![0-2]?\d\b|3[01]\b)\d+\b

Code

First, creating a more correct regex that also ensures 0 < x <= 90 as per the OP's question.

^(?:(?:[0-8]?\d|90) ){3}[AB]$

See regex in use here

^(?:(?:(?:[0-8]?\d|90) |(\S*) ?)){3}(?:[AB]|(.*))$

Note: This regex uses the mi flags (multiline - assuming input is in that format, and case-insensitive)

Other Formats

Realistically, this following regex would be ideal. Unfortunately, JavaScript doesn't support some of the tokens used in the regex, but I feel it may be useful to the OP or other users that see this question.

See regex in use here

^(?:(?:(?:[0-8]?\d|90) |(?<n>\S*?) |(?<n>\S*?) ?)){3}(?:(?<n>\S*) )?(?:[AB]|(.*))$

Results

Input

The first section (sections separated by the extra newline/break) shows valid strings, while the second shows invalid strings.

0 45 90 A
0 45 90 B

-1 45 90 A
0 45 91 A
12 34 5.6 A
12 34 56 C
1A 23 45 6
11 1A 12 12 A
12 12  A
12 12 A

Output

0 45 90 A        VALID
0 45 90 B        VALID

-1 45 90 A       INVALID: -1
0 45 91 A        INVALID: 91
12 34 5.6 A      INVALID: 5.6
12 34 56 C       INVALID: C
1A 23 45 6       INVALID: 1A, 6
11 1A 12 12 A    INVALID: 12 A
12 12  A         INVALID: (missing value)
12 12 A          INVALID: A, (missing value)

Note: The last entry shows an odd output, but that's due to a limitation with JavaScript's regex engine. The Other Formats section describes this and another method to use to properly catch these cases (using a different regex engine)

Explanation

This uses a simple | (OR) and captures the incorrect matches into a capture group.

^ Assert position at the start of the line

(?:(?:(?:[0-8]?\d|90) |(\S*) ?)){3} Match the following exactly 3 times

(?:(?:[0-8]?\d|90) |(.+)) Match either of the following

(?:[0-8]?\d|90) Match either of the following, followed by a space character  literally

[0-8]?\d Match between zero and one of the characters in the set 0-8 (a digit between 0 and 8), followed by any digit

90 Match 90 literally

(\S*) ? Capture any non-whitespace character one or more times into capture group 1, followed by zero or one space character  literally

(?:[AB]|(.*)) Match either of the following

[AB] Match any character present in the set (A or B)

(.*) Capture any character any number of times into capture group 2

$ Assert position at the end of the line

Answer 2

Brief

This method splits the string on the given delimiter and tests each section for the proper set of characters. It outputs a message if the value is incorrect. You would likely replace the console outputs with whatever logic you want use.

Code

var arr = [
  "0 45 90 A",
  "0 45 90 B",
  "-1 45 90 A",
  "0 45 91 A",
  "12 34 5.6 A",
  "12 34 56 C",
  "1A 23 45 6",
  "11 1A 12 12 A",
  "12 12  A",
  "12 12 A"
];

arr.forEach(function(e) {
  var s = e.split(" ");
  var l = s.pop();
  var numElements = 3;
  var maxNum = 90;
  var syntaxErrors = [];
  if(s.length != numElements) {
    syntaxErrors.push(`Invalid number of elements: Number = ${numElements}, Given = ${s.length}`);
  }
  s.forEach(function(v) {
    if(v.match(/\D/)) {
      syntaxErrors.push(`Invalid value "${v}" exists`);
    } else if(!v.length) {
      syntaxErrors.push(`An empty value or double space exists`);
    } else if(Number(v) > maxNum) {
      syntaxErrors.push(`Value greater than ${maxNum} exists: ${v}`);
    }
  });
  if(l.match(/[^AB]/)) {
    syntaxErrors.push(`Last element ${l} in "${e}" is invalid`);
  }
  if(syntaxErrors.length) {
    console.log(`"${e}" [\n\t${syntaxErrors.join('\n\t')}\n]`);
  } else {
    console.log(`No errors found in "${e}"`);
  }
});


问:
Comma separated cells to rows, but preserve data in surrounding columns
Excel Macro - Comma Separated Cells to Rows Preserve/Aggregate Column

My problem is almost exactly the same as the above link except I have data surrounding the columns I want to break out like the following:

```<code> <- A (Category) ->   <- B (Items) -> <- B (Items) -> <- B (Items) -> <- B (Items) ->
  1   Cat1                 date1          a,b,c            a1,b1,c1        item1
  2   Cat2                 date2           d                  d1           item2
  3   Cat3                 date3           e,f                e1,f1        item3
  4   Cat4                 date4           g                  g1           item4
</code>```

What I want is this:

```<code> <- A (Category) ->   <- B (Items) -> <- C (Items) -> <- D (Items) -> <- E (Items) ->
  1   Cat1                 date1           a                  a1           item1
  1   Cat1                 date1           b                  b1           item1
  1   Cat1                 date1           c                  c1           item1
  2   Cat2                 date2           d                  d1           item2
  3   Cat3                 date3           e                  e1           item3
  3   Cat3                 date3           f                  f1           item3
  4   Cat4                 date4           g                  g1           item4
</code>```

I want to break out Columns C and D into new rows and copy the items in A, B, and E. There's actually more columns, but I did this to make it easier.

The code below works perfect for only 2 adjacent columns. I was wondering could a range of columns be input to be copied?

```<code>Sub ExpandData()
    Const FirstRow = 2
    Dim LastRow As Long
    LastRow = Range("A" & CStr(Rows.Count)).End(xlUp).Row

    ' Get the values from the worksheet
    Dim SourceRange As Range
    Set SourceRange = Range("A" & CStr(FirstRow) & ":B" & CStr(LastRow))

    ' Get sourcerange values into an array
    Dim Vals() As Variant
    Vals = SourceRange.Value

    ' Loop through the rows in the array and split each comma-delimited list of items and put each on its own row
    Dim ArrIdx As Long
    Dim RowCount As Long
    For ArrIdx = LBound(Vals, 1) To UBound(Vals, 1)

        Dim CurrCat As String
        CurrCat = Vals(ArrIdx, 1)

        Dim CurrList As String
        CurrList = Replace(Vals(ArrIdx, 2), " ", "")

        Dim ListItems() As String
        ListItems = Split(CurrList, ",")

        Dim ListIdx As Integer
        For ListIdx = LBound(ListItems) To UBound(ListItems)

            Range("A" & CStr(FirstRow + RowCount)).Value = CurrCat
            Range("B" & CStr(FirstRow + RowCount)).Value = ListItems(ListIdx)
            RowCount = RowCount + 1

        Next ListIdx

    Next ArrIdx

End Sub
</code>```

答:
One immediate simplification is to

```<code> Set SourceRange = [A1].CurrentRegion
</code>```

For the rest, it looks like you're on the right track, but you want to change the ListItems... logic to set a Boolean to tell you to split up the other columns.

You end up with an If Then Else with one side handling simple rows and the
other side handling the multi-item rows. More code, but simple and unlikely to harbour errors.

Body:
Excel Macro - Comma Separated Cells to Rows Preserve/Aggregate Column

My problem is almost exactly the same as the above link except I have data surrounding the columns I want to break out like the following:

 <- A (Category) ->   <- B (Items) -> <- B (Items) -> <- B (Items) -> <- B (Items) ->
  1   Cat1                 date1          a,b,c            a1,b1,c1        item1
  2   Cat2                 date2           d                  d1           item2
  3   Cat3                 date3           e,f                e1,f1        item3
  4   Cat4                 date4           g                  g1           item4

What I want is this:

 <- A (Category) ->   <- B (Items) -> <- C (Items) -> <- D (Items) -> <- E (Items) ->
  1   Cat1                 date1           a                  a1           item1
  1   Cat1                 date1           b                  b1           item1
  1   Cat1                 date1           c                  c1           item1
  2   Cat2                 date2           d                  d1           item2
  3   Cat3                 date3           e                  e1           item3
  3   Cat3                 date3           f                  f1           item3
  4   Cat4                 date4           g                  g1           item4

I want to break out Columns C and D into new rows and copy the items in A, B, and E. There's actually more columns, but I did this to make it easier.

The code below works perfect for only 2 adjacent columns. I was wondering could a range of columns be input to be copied?

Sub ExpandData()
    Const FirstRow = 2
    Dim LastRow As Long
    LastRow = Range("A" & CStr(Rows.Count)).End(xlUp).Row

    ' Get the values from the worksheet
    Dim SourceRange As Range
    Set SourceRange = Range("A" & CStr(FirstRow) & ":B" & CStr(LastRow))

    ' Get sourcerange values into an array
    Dim Vals() As Variant
    Vals = SourceRange.Value

    ' Loop through the rows in the array and split each comma-delimited list of items and put each on its own row
    Dim ArrIdx As Long
    Dim RowCount As Long
    For ArrIdx = LBound(Vals, 1) To UBound(Vals, 1)

        Dim CurrCat As String
        CurrCat = Vals(ArrIdx, 1)

        Dim CurrList As String
        CurrList = Replace(Vals(ArrIdx, 2), " ", "")

        Dim ListItems() As String
        ListItems = Split(CurrList, ",")

        Dim ListIdx As Integer
        For ListIdx = LBound(ListItems) To UBound(ListItems)

            Range("A" & CStr(FirstRow + RowCount)).Value = CurrCat
            Range("B" & CStr(FirstRow + RowCount)).Value = ListItems(ListIdx)
            RowCount = RowCount + 1

        Next ListIdx

    Next ArrIdx

End Sub

Body:
One immediate simplification is to

 Set SourceRange = [A1].CurrentRegion

For the rest, it looks like you're on the right track, but you want to change the ListItems... logic to set a Boolean to tell you to split up the other columns.

You end up with an If Then Else with one side handling simple rows and the
other side handling the multi-item rows. More code, but simple and unlikely to harbour errors.


问:
How to restart Jenkins manually?
I've just started working with Jenkins and have run into a problem. After installing several plugins it said it needs to be restarted and went into a "shutting down" mode, but never restarts.

How do I do a manual restart?

答:
jenkins_url/restart is the safest way of doing it.

For service- Service Jenkins restart.

Title: How to restart Jenkins manually?