问:
How do I make the width of each character the same?
I'm using a custom font. The design doesn't allow me to change font.

While the number change, the content after it got pushed around due to the different width of digits.

Is there a way to make all the digits same width? I don't want to assign the width of the span component because I need this to be inline and the width should be determined by the number of digits it has.

const numberDom = document.querySelector('.number');
let number = 0;

function tick() {
  number += 1;
  numberDom.innerText = number;
}

setInterval(tick, 50);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {
  font-size: 1rem;
}

.number {
  font-family: 'Carter One', cursive;
  font-size: 1.5rem;
  color: #365;
}

.number::after {
  content: 'pt';
  font-size: 0.75em;
  margin-left: 0.1em;
  color: #587;
}</code>```

<link href="https://fonts.googleapis.com/css?family=Carter+One&display=swap" rel="stylesheet">

You got , good job!
```

答:
Change your number class as:</p>

```<code>.number {
    font-family: 'Carter One', cursive;
    font-size: 1.5rem;
    color: #365;
    width: 56px;
    display: inline-flex;
}
</code>```

Body:
I'm using a custom font. The design doesn't allow me to change font.

While the number change, the content after it got pushed around due to the different width of digits.

Is there a way to make all the digits same width? I don't want to assign the width of the span component because I need this to be inline and the width should be determined by the number of digits it has.

const numberDom = document.querySelector('.number');
let number = 0;

function tick() {
  number += 1;
  numberDom.innerText = number;
}

setInterval(tick, 50);

p {
  font-size: 1rem;
}

.number {
  font-family: 'Carter One', cursive;
  font-size: 1.5rem;
  color: #365;
}

.number::after {
  content: 'pt';
  font-size: 0.75em;
  margin-left: 0.1em;
  color: #587;
}

<link href="https://fonts.googleapis.com/css?family=Carter+One&display=swap" rel="stylesheet">

You got , good job!

Body:
Change your number class as:

.number {
    font-family: 'Carter One', cursive;
    font-size: 1.5rem;
    color: #365;
    width: 56px;
    display: inline-flex;
}


来源: stackexchange

问:
Typescript error messages for javascript file
I only have a minified version of the javascript code below. It works as is but I needed to integrate this code inside of a typescript file. It still works pretty well at runtime but in my editor (Visual Studio Code) I got errors.

Below is the code.

```<code>!function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});
</code>```

What can be done on this code to avoid TypeScript errors in my editor ?

EDIT

For this moment, I copy/paste minified javascript code inside another TypeScript file (wrap it in panel function) and it works at runtime but got errors in my editor.

ContentLicense: CC BY-SA 4.0

Body:
I only have a minified version of the javascript code below. It works as is but I needed to integrate this code inside of a typescript file. It still works pretty well at runtime but in my editor (Visual Studio Code) I got errors.

Below is the code.

!function(e){"use strict";function i(i,a){var s=i.outerWidth(!0),o={};if(!i.is(":visible")&&!n){switch(n=!0,i.addClass("ps-active-panel").css({position:"fixed",top:0,height:"100%","z-index":9999999999}),i.data(a),e("html").addClass("overflow-hidden"),e("body").addClass("overflow-hidden"),e("#eskimo-overlay").bind("touchmove",!1),e("#eskimo-overlay").fadeIn(200),a.side){case"left":i.css({left:"-"+s+"px",right:"auto"}),o.left="+="+s;break;case"right":i.css({left:"auto",right:"-"+s+"px"}),o.right="+="+s}t.animate({},a.duration),i.show().animate(o,a.duration,function(){n=!1,"function"==typeof a.onOpen&&a.onOpen()})}}var t=e("body"),n=!1;e.panelslider=function(t,n){var a=e(".ps-active-panel");n=e.extend({},{side:"left",duration:200,clickClose:!0,onOpen:null},n),a.is(":visible")&&a[0]!=t[0]?e.panelslider.close(function(){i(t,n)}):a.length&&!a.is(":hidden")||i(t,n)},e.panelslider.close=function(i){var a=e(".ps-active-panel"),s=a.data("duration"),o=a.outerWidth(!0),l={};if(a.length&&!a.is(":hidden")&&!n){switch(n=!0,a.data("side")){case"left":l.left="-="+o;break;case"right":l.right="-="+o}a.animate(l,s),t.animate({},s,function(){a.fadeOut(200),a.removeClass("ps-active-panel"),e("html").removeClass("overflow-hidden"),e("body").removeClass("overflow-hidden"),e("#eskimo-overlay").fadeOut(200),n=!1,i&&i()})}},e(document).bind("click keyup",function(i){var t=e(".ps-active-panel");"keyup"==i.type&&27!=i.keyCode||t.is(":visible")&&t.data("clickClose")&&e.panelslider.close()}),e(document).on("click",".ps-active-panel",function(e){e.stopPropagation()}),e.fn.panelslider=function(i){return this.on("click",function(t){var n=e(".ps-active-panel"),a=e(this.getAttribute("href"));n.is(":visible")&&a[0]==n[0]?e.panelslider.close():e.panelslider(a,i),t.preventDefault(),t.stopPropagation()}),this}}(jQuery);
jQuery(document).ready(function(){jQuery("body").find(".eskimo-panel-open").panelslider({side:"right",clickClose:!0,duration:400}),jQuery("body").find(".eskimo-panel-close").on("click",function(){return jQuery.panelslider.close(),!1})});

What can be done on this code to avoid TypeScript errors in my editor ?

EDIT

For this moment, I copy/paste minified javascript code inside another TypeScript file (wrap it in panel function) and it works at runtime but got errors in my editor.


问:
Google Vision API : java.lang.NoClassDefFoundError: com/google/cloud/vision/v1/ImageAnnotatorClient ERROR
I'm trying to run the Google Api Vision sample code but I'm getting this error:

java.lang.NoClassDefFoundError:com/google/cloud/vision/v1/ImageAnnotatorClient

These are the dependencies that imported into my project.

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-vision</artifactId>
  <version>1.74.0</version>
</dependency>
<dependency>
  <groupId>com.google.api.grpc</groupId>
  <artifactId>proto-google-common-protos</artifactId>
  <version>1.7.0</version>
</dependency>
<dependency>
  <groupId>com.google.code.findbugs</groupId>
  <artifactId>jsr305</artifactId>
  <version>3.0.2</version>
</dependency>
<dependency>
  <groupId>javax.annotation</groupId>
  <artifactId>javax.annotation-api</artifactId>
  <version>1.3.2</version>
</dependency>
```

<p>Code that I'm using. Which is provided google Vision API from: https://cloud.google.com/vision/docs/libraries</p>

<pre class="lang-java prettyprint-override"><code>package com.google.cloud.vision.api.utils;

//Imports the Google Cloud client library

import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class QuickstartSample {

    public static void main(String... args) throws Exception {
      // Instantiates a client
      try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {

        // The path to the image file to annotate
        String fileName = "/content/dam/USGBoral/Australia/Website/Images/products/steel_framing/SteelFraming-335x135_en.jpg";

        // Reads the image file into memory
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString imgBytes = ByteString.copyFrom(data);

        // Builds the image annotation request
        List<AnnotateImageRequest> requests = new ArrayList<>();
        Image img = Image.newBuilder().setContent(imgBytes).build();
        Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
        AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
                                                         .addFeatures(feat)
                                                         .setImage(img)
                                                         .build();
        requests.add(request);

        // Performs label detection on the image file
        BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();

        for (AnnotateImageResponse res : responses) {
          if (res.hasError()) {
            System.out.printf("Error: %s\n", res.getError().getMessage());
            return;
          }

          for (EntityAnnotation annotation :res.getLabelAnnotationsList()) {
            annotation.getAllFields()
                      .forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString()));
          }
        }
      }
   }
}
</code>```

答: Use package Google.Cloud.Vision.V1 or you might also want to check the correct Client Library to use depending on your framework. </p>

Body:
I'm trying to run the Google Api Vision sample code but I'm getting this error:

java.lang.NoClassDefFoundError:com/google/cloud/vision/v1/ImageAnnotatorClient

These are the dependencies that imported into my project.

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-vision</artifactId>
  <version>1.74.0</version>
</dependency>
<dependency>
  <groupId>com.google.api.grpc</groupId>
  <artifactId>proto-google-common-protos</artifactId>
  <version>1.7.0</version>
</dependency>
<dependency>
  <groupId>com.google.code.findbugs</groupId>
  <artifactId>jsr305</artifactId>
  <version>3.0.2</version>
</dependency>
<dependency>
  <groupId>javax.annotation</groupId>
  <artifactId>javax.annotation-api</artifactId>
  <version>1.3.2</version>
</dependency>

Code that I'm using. Which is provided google Vision API from: https://cloud.google.com/vision/docs/libraries

package com.google.cloud.vision.api.utils;

//Imports the Google Cloud client library

import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.protobuf.ByteString;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class QuickstartSample {

    public static void main(String... args) throws Exception {
      // Instantiates a client
      try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) {

        // The path to the image file to annotate
        String fileName = "/content/dam/USGBoral/Australia/Website/Images/products/steel_framing/SteelFraming-335x135_en.jpg";

        // Reads the image file into memory
        Path path = Paths.get(fileName);
        byte[] data = Files.readAllBytes(path);
        ByteString imgBytes = ByteString.copyFrom(data);

        // Builds the image annotation request
        List<AnnotateImageRequest> requests = new ArrayList<>();
        Image img = Image.newBuilder().setContent(imgBytes).build();
        Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
        AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
                                                         .addFeatures(feat)
                                                         .setImage(img)
                                                         .build();
        requests.add(request);

        // Performs label detection on the image file
        BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
        List<AnnotateImageResponse> responses = response.getResponsesList();

        for (AnnotateImageResponse res : responses) {
          if (res.hasError()) {
            System.out.printf("Error: %s\n", res.getError().getMessage());
            return;
          }

          for (EntityAnnotation annotation :res.getLabelAnnotationsList()) {
            annotation.getAllFields()
                      .forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString()));
          }
        }
      }
   }
}


问:
Deleting N matching patterns using sed, awk, perl etc
I have this situation, the file contains

```<code>abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5
</code>```

I would like to delete whenever I find matching 2 lines of

```<code>abcd
vwxyz
</code>```

to be deleted so that it becomes

```<code>abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

答:
Could you please try following, considering your actual Input_file is same as shown samples.</p>

```<code>awk -v RS="" '{gsub(/abcd\nvwxyz/,"");gsub(/[[:space:]]+\n/,ORS)} 1' Input_file
</code>```

Body:
I have this situation, the file contains

abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5

I would like to delete whenever I find matching 2 lines of

abcd
vwxyz

to be deleted so that it becomes

abcd
line1
line2
line3
vwxyz
line4
line5

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

Body:
Could you please try following, considering your actual Input_file is same as shown samples.

awk -v RS="" '{gsub(/abcd\nvwxyz/,"");gsub(/[[:space:]]+\n/,ORS)} 1' Input_file


问:
How to filter DataGridView to keep only a given set of rows
In C# I have DataGridView populated via DataSource. With some custom made filter I determine a subset of rows (by looping through the rows and checking the conditions on columns, to be precise) and need to keep/show only these rows in the DatGridView.

One option I understand is to loop through the grid and hide the rows which are outside my index set. This, however, is painfully slow for larger set of rows.
My question is:

given a datagridview which is bind to a datasource, and a subset of its rows, is there an efficient way to keep only those rows in datagridview?

答: How about you fill the Dgv from a code.  Write a Select Statement to populate a DataTable then,  proceed to setting the Datatable as DS for your datagridview then finally if you need to filter just call the querying method then it will call others aswell. </p>


问:
Should I create a new file for consts?
I'm wondering where should I keep my constants?
I've read about creating a new file where I can store all my constants. The problem is that more variables like that mean more code. In case of creating a big project should I create several files? Not sure.
I also used to keep my constants in the xml file(strings.xml).
The third option is to have those consts as top-level variables. I have noticed that when I had added such constant before the name of class Kotlin has changed that class to a file. It's uncommon for me behavior that's why I am asking. I used to store my const in Java in that class/package where I have needed them. Const in Kotlin are compile-time. Is this similar to the action of #DEFINE in C?

I hope I will solve my problems on how to properly use and store constants in Kotlin. Thanks :D

答:
I would suggest to just use separate Kotlin object file Constants.kt.

This will help you to manage constants at one place in a big project, particularly on scale, it'll be needed.

```<code>object Constants {

  object BundleKeys {
    val A = "a"
  }

  object ActivityResultCodes {
    val B = 1092
  }

  object FragmentTags {
    val C = "c"
  }

  object BundleExtraParams {
    val D = "d"
  }

}
</code>```

This will help you to keep separate constants in separate objects inside Constants.kt object

So you can access those like Constants.BundleKeys.A or Constants.ActivityResultCodes.B

Title: Should I create a new file for consts?

Body:
I would suggest to just use separate Kotlin object file Constants.kt.

This will help you to manage constants at one place in a big project, particularly on scale, it'll be needed.

object Constants {

  object BundleKeys {
    val A = "a"
  }

  object ActivityResultCodes {
    val B = 1092
  }

  object FragmentTags {
    val C = "c"
  }

  object BundleExtraParams {
    val D = "d"
  }

}

This will help you to keep separate constants in separate objects inside Constants.kt object

So you can access those like Constants.BundleKeys.A or Constants.ActivityResultCodes.B


问:
How to remove dangerous characters(ie script tags)?
I am wondering is there any sort of C# class or 3rd party library that removes dangerous characters such as script tags?

I know you can use regex but I also know people can write their script tags so many ways that you can fool the regex into thinking it is OK.

I also heard that HTML Agility Pack is good so I am wondering is there any script removal class made for it?

Edit

http://htmlagilitypack.codeplex.com/Thread/View.aspx?ThreadId=24346

I found this on their forms. However I am not sure if this is complete solution as the guy does not have any tests to back it up and it would be nicer if this was on some site where tons of people where using this script every day to test to see if anything gets by.

Great example (almost), Thanks!  A few
  ways to make it stronger that I saw,
  though:

1) Use case-insensitive search when
  looking for links with "javascript:",
  "vbscript:", "jscript:".  For example,
  the original example would not remove
  the HTML:

```<code><a href="JAVAscRipt:alert('hi')">click> me</a>
</code>```

2) Remove any style attributes that
  contain an expression rule.  Internet
  Explorer evaluates the CSS rule
  express as script.  For example, the
  following would product a message box:

```<code><div style="width:expression(alert('hi'));">bad> code</div>
</code>```

3) Also remove  tags

I honestly have no idea why
  "expression" has not been removed from
  IE - major flaw in my opinion. (Try
  the div example in internet explorer
  and you'll see why - even IE8.)  I
  just wish there was an easier/standard
  way to clean-up html input from a
  user.

Here's the code updated with these improvements.  Let me know if you see anything wrong:

```<code>    public string ScrubHTML(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);

        //Remove potentially harmful elements
        HtmlNodeCollection nc = doc.DocumentNode.SelectNodes("//script|//link|//iframe|//frameset|//frame|//applet|//object|//embed");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.ParentNode.RemoveChild(node, false);

            }
        }

        //remove hrefs to java/j/vbscript URLs
        nc = doc.DocumentNode.SelectNodes("//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]");
        if (nc != null)
        {

            foreach (HtmlNode node in nc)
            {
                node.SetAttributeValue("href", "#");
            }
        }

        //remove img with refs to java/j/vbscript URLs
        nc = doc.DocumentNode.SelectNodes("//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.SetAttributeValue("src", "#");
            }
        }

        //remove on<Event> handlers from all tags
        nc = doc.DocumentNode.SelectNodes("//*[@onclick or @onmouseover or @onfocus or @onblur or @onmouseout or @ondoubleclick or @onload or @onunload]");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.Attributes.Remove("onFocus");
                node.Attributes.Remove("onBlur");
                node.Attributes.Remove("onClick");
                node.Attributes.Remove("onMouseOver");
                node.Attributes.Remove("onMouseOut");
                node.Attributes.Remove("onDoubleClick");
                node.Attributes.Remove("onLoad");
                node.Attributes.Remove("onUnload");
            }
        }

        // remove any style attributes that contain the word expression (IE evaluates this as script)
        nc = doc.DocumentNode.SelectNodes("//*[contains(translate(@style, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'expression')]");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.Attributes.Remove("stYle");
            }
        }

        return doc.DocumentNode.WriteTo();
    }
</code>```

答:
string value = "Here alert('hello') we go. Visit the " +
            "http://west-wind.com'>West Wind site. " +
            "http://west-wind.com/images/new.gif' /> ";
            string safestring = Microsoft.Security.Application.Sanitizer.GetSafeHtmlFragment(value);

the above code will remove script tags from string

ContentLicense: CC BY-SA 3.0

Body:
I am wondering is there any sort of C# class or 3rd party library that removes dangerous characters such as script tags?

I know you can use regex but I also know people can write their script tags so many ways that you can fool the regex into thinking it is OK.

I also heard that HTML Agility Pack is good so I am wondering is there any script removal class made for it?

Edit

http://htmlagilitypack.codeplex.com/Thread/View.aspx?ThreadId=24346

I found this on their forms. However I am not sure if this is complete solution as the guy does not have any tests to back it up and it would be nicer if this was on some site where tons of people where using this script every day to test to see if anything gets by.

Great example (almost), Thanks!  A few
  ways to make it stronger that I saw,
  though:

1) Use case-insensitive search when
  looking for links with "javascript:",
  "vbscript:", "jscript:".  For example,
  the original example would not remove
  the HTML:

click> me

2) Remove any style attributes that
  contain an expression rule.  Internet
  Explorer evaluates the CSS rule
  express as script.  For example, the
  following would product a message box:

bad> code

3) Also remove  tags

I honestly have no idea why
  "expression" has not been removed from
  IE - major flaw in my opinion. (Try
  the div example in internet explorer
  and you'll see why - even IE8.)  I
  just wish there was an easier/standard
  way to clean-up html input from a
  user.

Here's the code updated with these improvements.  Let me know if you see anything wrong:

    public string ScrubHTML(string html)
    {
        HtmlDocument doc = new HtmlDocument();
        doc.LoadHtml(html);

        //Remove potentially harmful elements
        HtmlNodeCollection nc = doc.DocumentNode.SelectNodes("//script|//link|//iframe|//frameset|//frame|//applet|//object|//embed");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.ParentNode.RemoveChild(node, false);

            }
        }

        //remove hrefs to java/j/vbscript URLs
        nc = doc.DocumentNode.SelectNodes("//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//a[starts-with(translate(@href, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]");
        if (nc != null)
        {

            foreach (HtmlNode node in nc)
            {
                node.SetAttributeValue("href", "#");
            }
        }

        //remove img with refs to java/j/vbscript URLs
        nc = doc.DocumentNode.SelectNodes("//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'javascript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'jscript')]|//img[starts-with(translate(@src, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'vbscript')]");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.SetAttributeValue("src", "#");
            }
        }

        //remove on<Event> handlers from all tags
        nc = doc.DocumentNode.SelectNodes("//*[@onclick or @onmouseover or @onfocus or @onblur or @onmouseout or @ondoubleclick or @onload or @onunload]");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.Attributes.Remove("onFocus");
                node.Attributes.Remove("onBlur");
                node.Attributes.Remove("onClick");
                node.Attributes.Remove("onMouseOver");
                node.Attributes.Remove("onMouseOut");
                node.Attributes.Remove("onDoubleClick");
                node.Attributes.Remove("onLoad");
                node.Attributes.Remove("onUnload");
            }
        }

        // remove any style attributes that contain the word expression (IE evaluates this as script)
        nc = doc.DocumentNode.SelectNodes("//*[contains(translate(@style, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'expression')]");
        if (nc != null)
        {
            foreach (HtmlNode node in nc)
            {
                node.Attributes.Remove("stYle");
            }
        }

        return doc.DocumentNode.WriteTo();
    }


问:
PHP mike42/escpos-php print from iPhone (remote website) to localhost printer
I have a website (on a remote server)and this is viewed by the user on the iPhone (Safari).

I'm trying to achieve the user being able to print a text file from that site to a POS Printer (REGO Thermal Printer, RG-MTP58B). This printer does not support AirPrint but is a wifi printer and lives on 172.20.10.2:9100 IP and port.

As far as I understand I cannot directly print from the server as the Printer is not in the server network but local network.

I'm using this package: https://github.com/mike42/escpos-php as I see is the only still maintained.

I've tried this way:

$connector = new FilePrintConnector("php://stdout");
$printer   = new Printer($connector);
$printer->text("Hello World!\n");
$printer->cut();
$printer->close();
```

<p>But this just gives a white page and the printer does not receive anything.</p>

<p>I've tried saving the file in the server, open it in Safari but Safari doesn't provide an option to print it (not even in the "Share" area).</p>

<p>So i found out the package Author does this:</p>

<pre class="lang-php prettyprint-override"><code>$connector = new DummyPrintConnector();
$profile = CapabilityProfile::load("TSP600");
$printer = new Printer($connector);
$printer->text("Hello world!\n");
$printer->cut();
// Get the data out as a string
$data = $connector->getData();
// Return it, check the manual for specifics.
header('Content-type: application/octet-stream');
header('Content-Length: '.strlen($data));
echo $data;
// Close the printer when done.
$printer->close();
</code>```

(original code: here)

In this case it creates a file and it shows it like this:

Again it does not provide an option to print it (not even in the "Share" area).

The file content is a binary:

```<code><0x1b>@Hello world!
<0x1d>VA<0x03>
</code>```

How do I send this data to the printer?

答: I contacted the Printer (Rego Printer) manufacturer and basically they don't allow external connection, this means you must print locally.</p>

Body:
I have a website (on a remote server)and this is viewed by the user on the iPhone (Safari).

I'm trying to achieve the user being able to print a text file from that site to a POS Printer (REGO Thermal Printer, RG-MTP58B). This printer does not support AirPrint but is a wifi printer and lives on 172.20.10.2:9100 IP and port.

As far as I understand I cannot directly print from the server as the Printer is not in the server network but local network.

I'm using this package: https://github.com/mike42/escpos-php as I see is the only still maintained.

I've tried this way:

$connector = new FilePrintConnector("php://stdout");
$printer   = new Printer($connector);
$printer->text("Hello World!\n");
$printer->cut();
$printer->close();

But this just gives a white page and the printer does not receive anything.

I've tried saving the file in the server, open it in Safari but Safari doesn't provide an option to print it (not even in the "Share" area).

So i found out the package Author does this:

$connector = new DummyPrintConnector();
$profile = CapabilityProfile::load("TSP600");
$printer = new Printer($connector);
$printer->text("Hello world!\n");
$printer->cut();
// Get the data out as a string
$data = $connector->getData();
// Return it, check the manual for specifics.
header('Content-type: application/octet-stream');
header('Content-Length: '.strlen($data));
echo $data;
// Close the printer when done.
$printer->close();

(original code: here)

In this case it creates a file and it shows it like this:

Again it does not provide an option to print it (not even in the "Share" area).

The file content is a binary:

<0x1b>@Hello world!
<0x1d>VA<0x03>

How do I send this data to the printer?


问:
Vue js vee validate password confirmation with custom components
I use vee-validate in my project with custom components with no problems.

But now for a Password Confirmation input field, I'm not able to make it work properly.

I have custom components for the input fields, somethink like <base-input-field>.

If I add a ref="password" attribute in my custom component (<base-input-field ref="password">), it will not reference the <input> inside my custom component, but the
 wrapper that encapsulates the <input> html component.

Code example:

```<code>            <!-- Password -->
            <div class="row">
              <base-text-field
                ref="password"
                name="password"
                type="password"
                :error="isVisible && errors.first('password')"
                v-validate="{
                  required: true,
                  min: 6,
                  max: 30,
                }"
                v-model.trim="password"
                required
              />
            </div>

            <!-- Confirm Password -->
            <div class="row">
              <base-text-field
                name="password_conf"
                type="password"
                :error="isVisible && errors.first('password_conf')"
                v-validate="{
                  required: true,
                  confirmed: 'password',
                }"
                :data-vv-as="password"
                v-model.trim="password_conf"
                required
              />
            </div>
</code>```

答:
Can u check which events are supported on your custom component(May be @input/@change)?

If any of events are fired on change of your input there is an option data-vv-validate-on in v-validate where you can set on which event you want to check the validation. Read more here

```<code><base-text-field
            ref="password"
            name="password"
            type="password"
            :error="isVisible && errors.first('password')"
            v-validate="{
              required: true,
              min: 6,
              max: 30,
            }"
            v-model.trim="password"
            data-vv-validate-on="change"
            required
          />
</code>```

Body:
I use vee-validate in my project with custom components with no problems.

But now for a Password Confirmation input field, I'm not able to make it work properly.

I have custom components for the input fields, somethink like <base-input-field>.

If I add a ref="password" attribute in my custom component (<base-input-field ref="password">), it will not reference the <input> inside my custom component, but the
 wrapper that encapsulates the <input> html component.

Code example:

              <base-text-field
                ref="password"
                name="password"
                type="password"
                :error="isVisible && errors.first('password')"
                v-validate="{
                  required: true,
                  min: 6,
                  max: 30,
                }"
                v-model.trim="password"
                required
              />

              <base-text-field
                name="password_conf"
                type="password"
                :error="isVisible && errors.first('password_conf')"
                v-validate="{
                  required: true,
                  confirmed: 'password',
                }"
                :data-vv-as="password"
                v-model.trim="password_conf"
                required
              />

Body:
Can u check which events are supported on your custom component(May be @input/@change)?

If any of events are fired on change of your input there is an option data-vv-validate-on in v-validate where you can set on which event you want to check the validation. Read more here

<base-text-field
            ref="password"
            name="password"
            type="password"
            :error="isVisible && errors.first('password')"
            v-validate="{
              required: true,
              min: 6,
              max: 30,
            }"
            v-model.trim="password"
            data-vv-validate-on="change"
            required
          />


问:
How to compare similar XMLs with PHPUnit?
So let's say I want to compare two DOMDocument objects. They have the same content but order and formatting might be off. For example, first one outputs this XML:

```<code><responses>
    <response id="12">
        <foo>bar</foo>

 <lorem>ipsum</lorem>
           <sit>dolor</sit>

    </response></responses>
</code>```

Other one outputs:

```<code><responses>
<response id="12">

            <lorem>ipsum</lorem><sit>dolor</sit>
        <foo>bar</foo>
                            </response>
</responses>
</code>```

As you can see, they contain the same XML structure but some elements might be in different order and formatting is completely random.

If I do:

```<code>$this->assertEquals();
</code>```

The test will of course fail. I don't want to test just XML structure but also contents.

Any ideas?

答:
Use the following assertion:</p>

```<code>$this->assertXmlStringEqualsXmlString($expected, $actual);
</code>```

Body:
So let's say I want to compare two DOMDocument objects. They have the same content but order and formatting might be off. For example, first one outputs this XML:

<responses>
    <response id="12">
        <foo>bar</foo>

 <lorem>ipsum</lorem>
           <sit>dolor</sit>

    </response></responses>

Other one outputs:

<responses>
<response id="12">

            <lorem>ipsum</lorem><sit>dolor</sit>
        <foo>bar</foo>
                            </response>
</responses>

As you can see, they contain the same XML structure but some elements might be in different order and formatting is completely random.

If I do:

$this->assertEquals();

The test will of course fail. I don't want to test just XML structure but also contents.

Any ideas?

Body:
Use the following assertion:

$this->assertXmlStringEqualsXmlString($expected, $actual);


问:
Java - Create a web service from an available class
I had a java project and after lots of research I managed to convert it to a Dynamic Web Project in Eclipse. Now I want to add a new Web Service to it. I have already developed a class. I want to convert it to a standard Web service so I can call it from my silverlight application. Here's my current class:

```<code>public class MyWebService
{
    @Resource
    WebServiceContext context;

    @WebMethod
    public String ProcessQuery(@WebParam(name="query") String q)
    {
        MessageContext messageContext = context.getMessageContext();
        HttpServletRequest request = (HttpServletRequest) messageContext.get(SOAPMessageContext.SERVLET_REQUEST);
        // now you can get anything you want from the request
    }

    public static void main(String[] args) throws Exception
    {
        String address = "http://127.0.0.1:8023/_WebServiceDemo";
        Endpoint.publish(address, new MyWebService());
        new DocumentServer();
        System.out.println("Listening: " + address);
    }
}
</code>```

How can I do it in Eclipse? Please post a link to a tutorial or a quick step by step guide. I'm a .Net developer and I'm very new to Java.

Thank you.

PS: So basically I want to publish this service in a standard way rather than calling this main function and using Endpoint.publish() method.

答:
The Eclipse wiki has a tutorial using the Web Tools Platform to do just what you are looking for.  It requires WTP and Tomcat, if you don't have those already available to Eclipse.  It starts with an unannotated class and finishes with a WSDL and test client.  It allows you to view generated SOAP messages.

To create, it instructs you to select the file you want to convert into a web service and run File -> New -> Other... -> Web Services -> Web Service.  Then you click Next, move the slider to the Start Service position, and client to Test Client.  You select Monitor the Web Service and then click Finish.  Then you can play with your Test Client and see your generated WSDL.

Note that the above paragraph is a summary of the tutorial, which you can find in full at the provided link.

Body:
I had a java project and after lots of research I managed to convert it to a Dynamic Web Project in Eclipse. Now I want to add a new Web Service to it. I have already developed a class. I want to convert it to a standard Web service so I can call it from my silverlight application. Here's my current class:

public class MyWebService
{
    @Resource
    WebServiceContext context;

    @WebMethod
    public String ProcessQuery(@WebParam(name="query") String q)
    {
        MessageContext messageContext = context.getMessageContext();
        HttpServletRequest request = (HttpServletRequest) messageContext.get(SOAPMessageContext.SERVLET_REQUEST);
        // now you can get anything you want from the request
    }

    public static void main(String[] args) throws Exception
    {
        String address = "http://127.0.0.1:8023/_WebServiceDemo";
        Endpoint.publish(address, new MyWebService());
        new DocumentServer();
        System.out.println("Listening: " + address);
    }
}

How can I do it in Eclipse? Please post a link to a tutorial or a quick step by step guide. I'm a .Net developer and I'm very new to Java.

Thank you.

PS: So basically I want to publish this service in a standard way rather than calling this main function and using Endpoint.publish() method.


问:
How to style a PrimeNG Chips?
I have a form in my application where I use the following code from Primafaces:

```<code>...other inputs...

<label for="workshopTags">Tags</label>
<p-chips
    [(ngModel)]="values"
    name="workshopTags"
    id="workshopTags"
></p-chips>
</code>```

I am able to display the Chip element correctly but I would like to style it putting its width to 100% and the height to 100px, but nothing seems to work to change those. This solution didn't work for me. I tried to set a styleClass or an inline style as the documentation suggest but they didn't work either. If I write inline:

```<code>style="width: 100%"
</code>```

The following error is thrown:

Error: Cannot find a differ supporting object 'width: 100%;'

How can I make it work?

答:
there are tow methos to style primeng component overwrite the original style or by create a custom style base on custome class

overwrite

add the style to global style.css or style.scss , this method for overwrite primeng component style without add extra class to the component.

```<code>.ui-chips {
  display: inline-block
}

.ui-chips ul {
  border:2px dashed green !important; /*  I have use important */
}

 .ui-chips > ul.ui-inputtext .ui-chips-token {
    font-size: 14px;
    background: green !important; /*  I have use important */
    border:1px solid #005555;
    box-shadow: 0 0 25px #ccc;
}
</code>```

stackblitz demo

custome style

the method above will change the style of all p-chips component in the entier project , by this method you need to set styleClass property so you can create different style like the example here  , but you need to set styleClass property for every component

```<code><p-chips [(ngModel)]="values" styleClass="p-chips"></p-chips>
</code>```

style.css

```<code>.p-chips.ui-chips {
  /* border:1px solid #ff2200; */
  display: inline-block
}

.p-chips.ui-chips ul {
  border:2px dashed orange;
}

 .p-chips.ui-chips > ul.ui-inputtext .ui-chips-token {
    font-size: 14px;
    background: orange;
    border:1px solid #ff5555;
    box-shadow: 0 0 25px #ccc;
}
</code>```

stackblitz demo

Title: How to style a PrimeNG Chips?

Body:
I have a form in my application where I use the following code from Primafaces:

...other inputs...

Tags

I am able to display the Chip element correctly but I would like to style it putting its width to 100% and the height to 100px, but nothing seems to work to change those. This solution didn't work for me. I tried to set a styleClass or an inline style as the documentation suggest but they didn't work either. If I write inline:

style="width: 100%"

The following error is thrown:

Error: Cannot find a differ supporting object 'width: 100%;'

How can I make it work?

Body:
there are tow methos to style primeng component overwrite the original style or by create a custom style base on custome class

overwrite

add the style to global style.css or style.scss , this method for overwrite primeng component style without add extra class to the component.

.ui-chips {
  display: inline-block
}

.ui-chips ul {
  border:2px dashed green !important; /*  I have use important */
}

 .ui-chips > ul.ui-inputtext .ui-chips-token {
    font-size: 14px;
    background: green !important; /*  I have use important */
    border:1px solid #005555;
    box-shadow: 0 0 25px #ccc;
}

stackblitz demo

custome style

the method above will change the style of all p-chips component in the entier project , by this method you need to set styleClass property so you can create different style like the example here  , but you need to set styleClass property for every component

<p-chips [(ngModel)]="values" styleClass="p-chips"></p-chips>

style.css

.p-chips.ui-chips {
  /* border:1px solid #ff2200; */
  display: inline-block
}

.p-chips.ui-chips ul {
  border:2px dashed orange;
}

 .p-chips.ui-chips > ul.ui-inputtext .ui-chips-token {
    font-size: 14px;
    background: orange;
    border:1px solid #ff5555;
    box-shadow: 0 0 25px #ccc;
}

stackblitz demo


问:
How to further reduce Angular 7 build size, when all modules are already being lazy loaded?
My initial production build size of main.js was 1.5M. Clearly unacceptable, the cold start loading time was around 17 seconds. So I checked some online sources on how to tackle this, and employed lazy loading of modules. That reduced the main.js to 541kB. An improvement to be sure, but I'd like to squeeze it further, possibly down to 200 or so kB. I start the build process by using npm run build (I am primarily a java dev, so I don't know if this is the right way), which in turn calls ng build --prod. Now here come the questions:

Does the --prod flag include all the optimizations I could possibly want? Or should I enable more of them explicitly by using more command options. The official documentation on this is not very clear to me. Specifically, it says :

When true, sets the build configuration to the production target. All builds make use of bundling and limited tree-shaking. A production build also runs limited dead code elimination.

Why only limited? Don't I want the full tree shaking and dead code elimination? Are there any other flags besides --prod I should know of? It appears that options such as --buildOptimizer and others are set to true in angular.json for prod builds, so it seems I can't get any more benefits by tweaking the build process. AOT, uglification, etc. should also be used by default.

What other techniques could I possibly use? I could of course use gzip on my server, but that is outside of the scope of angular itself. I find it hard to believe that my simple app could be that large, I am probably missing something.

答:
541kB is peanuts.

As you have said, you have several flags in the angular.json files that are enabled when using the --prod flag. By default, that would be

```<code>          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true,
          "budgets": [{
            "type": "initial",
            "maximumWarning": "2mb",
            "maximumError": "5mb"
          }]
</code>```

You can find all the possible flags here

In the end, if you want to further reduce the size of your main script, you will have to do it by hand : Angular optimization can go so far, the rest depends on how you code.

For instance, factorizing your code, removing the unused code, reusing common components, reducing the size of the initial module, reduce the amount of repeated HTML & CSS ... It all comes down to how many letters are in your file, so the fewer letters you have, the lighter the main script will be.

Finally, somme techniques are available to you to further increase the performance for the first rendering of your application, such as service workers or server-side rendering.

Body:
541kB is peanuts.

As you have said, you have several flags in the angular.json files that are enabled when using the --prod flag. By default, that would be

          "optimization": true,
          "outputHashing": "all",
          "sourceMap": false,
          "extractCss": true,
          "namedChunks": false,
          "aot": true,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true,
          "budgets": [{
            "type": "initial",
            "maximumWarning": "2mb",
            "maximumError": "5mb"
          }]

You can find all the possible flags here

In the end, if you want to further reduce the size of your main script, you will have to do it by hand : Angular optimization can go so far, the rest depends on how you code.

For instance, factorizing your code, removing the unused code, reusing common components, reducing the size of the initial module, reduce the amount of repeated HTML & CSS ... It all comes down to how many letters are in your file, so the fewer letters you have, the lighter the main script will be.

Finally, somme techniques are available to you to further increase the performance for the first rendering of your application, such as service workers or server-side rendering.


问:
How to get all matching iterations for a capture group
I made this regular expression and use it with re.findall():

```<code>SELECT.*{(?:\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\][,]{0,1}){1,}}.*
</code>```

to match these lists of strings:

["dimSales","Product Title","All"],
  ["test","Product Title","All"]

in this haystack:

```<code>SELECT NON EMPTY Hierarchize({DrilldownLevel({[dimSales].[Product Title].[All],[test].[Product Title].[All]},,,INCLUDE_CALC_MEMBERS)}) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS FROM [Model] CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS
</code>```

my regex only matches the last iteration of the outer capturing group

["test","Product Title","All"]

what do I need to change, so re.findall() returns all iterations. Not just the last iteration of the outer capturing group?

答:
What about this regex:

```<code>(\[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\],\s*\[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\])
</code>```

demo:

https://regex101.com/r/LaddaK/2/

Explanations:

parenthesis () to have your capturing group, can be removed if not necessary

\[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\] to match an open bracket literally followed by a double quote, 0 to N non double quote characters ([^\"]*) followed by a double quote and a comma. You might have to surround all commas by \s* if you have want to accept space characters around them.

you repeat another 2 times the pattern \"[^\"]*\" to match the first 3 words surround in brackets (you might have to adapt into \w* depending on your exact constraints on the strings.

you repeat the whole block[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\] after a ,\s* to accept the whole pattern made of 2 blocks of brackets.

Notes:

You might want to surround your regex with anchors (^ and $)

I don't know exactly your constraints but if you want to analyse some JSON or parse any other format with infinite nested patterns repeating themselves (ex: fractals) you should not use regex.

EDIT after change of requirements:

```<code>import re

inputStr = '[dimSales,Product Title,All], [test,Product Title,All]'
print(re.findall(r'\[(?:[a-zA-Z0-9 ]*)(?:,[a-zA-Z0-9 ]*)*\]', inputStr))
</code>```

output:

```<code>['[dimSales,Product Title,All]', '[test,Product Title,All]']
</code>```

Body:
I made this regular expression and use it with re.findall():

SELECT.*{(?:\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\]\.\[([a-zA-Z0-9 ]*)\][,]{0,1}){1,}}.*

to match these lists of strings:

["dimSales","Product Title","All"],
  ["test","Product Title","All"]

in this haystack:

SELECT NON EMPTY Hierarchize({DrilldownLevel({[dimSales].[Product Title].[All],[test].[Product Title].[All]},,,INCLUDE_CALC_MEMBERS)}) DIMENSION PROPERTIES PARENT_UNIQUE_NAME,HIERARCHY_UNIQUE_NAME ON COLUMNS FROM [Model] CELL PROPERTIES VALUE, FORMAT_STRING, LANGUAGE, BACK_COLOR, FORE_COLOR, FONT_FLAGS

my regex only matches the last iteration of the outer capturing group

["test","Product Title","All"]

what do I need to change, so re.findall() returns all iterations. Not just the last iteration of the outer capturing group?

Body:
What about this regex:

(\[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\],\s*\[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\])

demo:

https://regex101.com/r/LaddaK/2/

Explanations:

parenthesis () to have your capturing group, can be removed if not necessary

\[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\] to match an open bracket literally followed by a double quote, 0 to N non double quote characters ([^\"]*) followed by a double quote and a comma. You might have to surround all commas by \s* if you have want to accept space characters around them.

you repeat another 2 times the pattern \"[^\"]*\" to match the first 3 words surround in brackets (you might have to adapt into \w* depending on your exact constraints on the strings.

you repeat the whole block[\"[^\"]*\",\"[^\"]*\",\"[^\"]*\"\] after a ,\s* to accept the whole pattern made of 2 blocks of brackets.

Notes:

You might want to surround your regex with anchors (^ and $)

I don't know exactly your constraints but if you want to analyse some JSON or parse any other format with infinite nested patterns repeating themselves (ex: fractals) you should not use regex.

EDIT after change of requirements:

import re

inputStr = '[dimSales,Product Title,All], [test,Product Title,All]'
print(re.findall(r'\[(?:[a-zA-Z0-9 ]*)(?:,[a-zA-Z0-9 ]*)*\]', inputStr))

output:

['[dimSales,Product Title,All]', '[test,Product Title,All]']


问:
Disposing Maybe in RxAndroid
I'm new to the reactive world so please bear with me if what I'm saying is wrong (please correct me!).

So I was searching through google and here for something similar but I think I haven't seen anyting around the avenue of what I've done. I'm using the Rx2Firebase library to get some data from my database using the RxFirebaseDatabase.observeSingleValueEvent method and I couldn't wrap my head around how I would go about disposing the Observable I made. So this method returns a Maybe and I want to dispose of that Maybe after executing my code but I'm unsure as to how (read on below as to why).

My current code looks something like this:

```<code>private fun getUserStatus(callback: () -> Unit) {

RxFirebaseDatabase
    .observeSingleValueEvent(myQuery,(entry::class.java))
    .subscribe ({ item
     myEntry = item
     callback()
   },{ e
     Log.e("Error", e.message)
   })
}
</code>```

From what I've read, observables are assigned to a Disposable variable and then I think that variable would be disposed? something like var disposable: Disposable = <Insert my code above for calling Firebase> and you would do so (from what I've read) inside onDestroy. My question would be how would I do this if my code isn't executed within an Activity or a Fragment? I couldn't just add a dispose() at the end of my code after .subscribe since that would just end the call before it finished.

答:
You don't need to dispose of the Maybe after your code was executed. You should dispose any observable, whenever you need the cancel the underlying action to. Since you're using Android, the action is triggered from within some lifecycle aware component. This could be Activity, Fragment or Service. If you trigger the call from a BroadcastReceiver you should start a service to do this instead.

For any of these components you have a method onDestroy where you can dispose of the observable. The only thing you have to make sure is to propagate the Disposable up to this level:

```<code>private fun getUserStatus(callback: () -> Unit): Disposable =
    RxFirebaseDatabase
      .observeSingleValueEvent(myQuery,(entry::class.java))
      .subscribe ({ item ->
          myEntry = item
          callback()
      },{ e ->
          Log.e("Error", e.message)
      })
</code>```

Title: Disposing Maybe in RxAndroid

Body:
I'm new to the reactive world so please bear with me if what I'm saying is wrong (please correct me!).

So I was searching through google and here for something similar but I think I haven't seen anyting around the avenue of what I've done. I'm using the Rx2Firebase library to get some data from my database using the RxFirebaseDatabase.observeSingleValueEvent method and I couldn't wrap my head around how I would go about disposing the Observable I made. So this method returns a Maybe and I want to dispose of that Maybe after executing my code but I'm unsure as to how (read on below as to why).

My current code looks something like this:

private fun getUserStatus(callback: () -> Unit) {

RxFirebaseDatabase
    .observeSingleValueEvent(myQuery,(entry::class.java))
    .subscribe ({ item
     myEntry = item
     callback()
   },{ e
     Log.e("Error", e.message)
   })
}

From what I've read, observables are assigned to a Disposable variable and then I think that variable would be disposed? something like var disposable: Disposable = <Insert my code above for calling Firebase> and you would do so (from what I've read) inside onDestroy. My question would be how would I do this if my code isn't executed within an Activity or a Fragment? I couldn't just add a dispose() at the end of my code after .subscribe since that would just end the call before it finished.

Body:
You don't need to dispose of the Maybe after your code was executed. You should dispose any observable, whenever you need the cancel the underlying action to. Since you're using Android, the action is triggered from within some lifecycle aware component. This could be Activity, Fragment or Service. If you trigger the call from a BroadcastReceiver you should start a service to do this instead.

For any of these components you have a method onDestroy where you can dispose of the observable. The only thing you have to make sure is to propagate the Disposable up to this level:

private fun getUserStatus(callback: () -> Unit): Disposable =
    RxFirebaseDatabase
      .observeSingleValueEvent(myQuery,(entry::class.java))
      .subscribe ({ item ->
          myEntry = item
          callback()
      },{ e ->
          Log.e("Error", e.message)
      })


问:
how to fix this type error in python 3.0 ? whenever i use passing argument(dict{}) it shows this type of error "NameError: name 'P' is not defined"
```<code> def bowling(p1,p2,p3,p4,p5):
        x=1
        while x<6:
            print(px.get('role'))
</code>```

<p>"NameError: name 'P' is not defined"</p>

```<code> x=x+1
 p1={'name':'Virat Kohli', 'role':'bat', 'runs':112, '4':10, '6':0, 'balls':119, 'field':0}
 p2={'name':'du Plessis', 'role':'bat', 'runs':120, '4':11, '6':2, 'balls':112, 'field':0}
 p3={'name':'Bhuvneshwar Kumar', 'role':'bowl', 'wkts':1, 'overs':10, 'runs':71, 'field':1}
 p4={'name':'Yuzvendra Chahal', 'role':'bowl', 'wkts':2, 'overs':10, 'runs':45, 'field':0}
 p5={'name':'Kuldeep Yadav', 'role':'bowl', 'wkts':3, 'overs':10, 'runs':34, 'field':0}
 bowling(p1,p2,p3,p4,p5)    #passing dict as argument
</code>```

答:
python can not access variables the way you think it does... (with x=1 python will not be able to access p1 when you write px; px is just a new name that has not been defined yet).

what you could do is this:

```<code>def bowling(*args):
    for px in args:
        print(px.get("role"))

bowling(p1, p2, p3, p4, p5)
</code>```

i.e. use a variable number of arguments *args and iterate over them. you can find more information on how to use those in the python documentation or here or here for example.

Body:
 def bowling(p1,p2,p3,p4,p5):
        x=1
        while x<6:
            print(px.get('role'))

"NameError: name 'P' is not defined"

 x=x+1
 p1={'name':'Virat Kohli', 'role':'bat', 'runs':112, '4':10, '6':0, 'balls':119, 'field':0}
 p2={'name':'du Plessis', 'role':'bat', 'runs':120, '4':11, '6':2, 'balls':112, 'field':0}
 p3={'name':'Bhuvneshwar Kumar', 'role':'bowl', 'wkts':1, 'overs':10, 'runs':71, 'field':1}
 p4={'name':'Yuzvendra Chahal', 'role':'bowl', 'wkts':2, 'overs':10, 'runs':45, 'field':0}
 p5={'name':'Kuldeep Yadav', 'role':'bowl', 'wkts':3, 'overs':10, 'runs':34, 'field':0}
 bowling(p1,p2,p3,p4,p5)    #passing dict as argument

Body:
python can not access variables the way you think it does... (with x=1 python will not be able to access p1 when you write px; px is just a new name that has not been defined yet).

what you could do is this:

def bowling(*args):
    for px in args:
        print(px.get("role"))

bowling(p1, p2, p3, p4, p5)

i.e. use a variable number of arguments *args and iterate over them. you can find more information on how to use those in the python documentation or here or here for example.


问:
Rotate UIView around its center keeping its size
I'm trying to rotate an UIView a few radians but after applying the transformation it doesn't look to be keeping its size. What's the proper way to achieve this?

Here's what I'm doing and what I get (Blue box with the arrow is the View I'm trying to rotate -- it should keep same aspect as red box behind):

```<code>#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)

double rads = DEGREES_TO_RADIANS(240);
CGAffineTransform transform = CGAffineTransformRotate(CGAffineTransformIdentity, rads);
self.arrowView.transform = transform;
</code>```

Thanks!

答:
Swift 5:</p>

```<code>extension UIView {
    func setTransformRotation(toDegrees angleInDegrees: CGFloat) {
        let angleInRadians = angleInDegrees / 180.0 * CGFloat.pi
        let rotation = self.transform.rotated(by: angleInRadians)
        self.transform = rotation
    }
}
</code>```

Body:
I'm trying to rotate an UIView a few radians but after applying the transformation it doesn't look to be keeping its size. What's the proper way to achieve this?

Here's what I'm doing and what I get (Blue box with the arrow is the View I'm trying to rotate -- it should keep same aspect as red box behind):

#define DEGREES_TO_RADIANS(angle) ((angle) / 180.0 * M_PI)

double rads = DEGREES_TO_RADIANS(240);
CGAffineTransform transform = CGAffineTransformRotate(CGAffineTransformIdentity, rads);
self.arrowView.transform = transform;

Thanks!

Body:
Swift 5:

extension UIView {
    func setTransformRotation(toDegrees angleInDegrees: CGFloat) {
        let angleInRadians = angleInDegrees / 180.0 * CGFloat.pi
        let rotation = self.transform.rotated(by: angleInRadians)
        self.transform = rotation
    }
}


问:
Node Express Router /users/:id vs /users/login
I am building a restful api with a path /users/:id (for viewing a user's information) and /users/login (for logging in with credentials).
How do I prevent /users/:id only called when :id is a number? Is this even a good approach for building a restful api?

One way I could do it is I create a /users/:id route and inside I check if id is a number, otherwise switch between cases of login, signup, etc. Is this the right approach?

答:
Just order routes based on the priorities

Now user/login will not execute search function

```<code>app.post('/user/login', login);
app.post('/user/signup', signup);
app.post('/user/:id', search);

</code>```

Body:
Just order routes based on the priorities

Now user/login will not execute search function

app.post('/user/login', login);
app.post('/user/signup', signup);
app.post('/user/:id', search);


问:
Jquery Fade in fade out, with pause or delay
If have the following code but i cant get a pause AFTER ever fade in   and fade out:</p>

```<code>$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            img.animate({
                opacity: .3
            }, 400, function ()

            {
                // When finished, animate it back to solid.
                img.animate({
                    opacity: 1
                }, 400);

            });

            // Clear the interval once we've reached 1000.
            if (++img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});
</code>```

答:
Your code can be reduced significantly:

```<code>$.fn.fadeLoop = function()
{
    var that = this;
    $(this).data('fadeTimer', setTimeout(function() {
        $(that).fadeOut(400, function() {
            $(that).fadeIn(400,  $(that).fadeLoop);
        });
    }, 2000));
};

$(document).ready(function() {
    $('img.bttn_play').hover(function() {
        clearTimeout($(this).data('fadeTimer'));
        $(this).stop(true).css('opacity', 1);
    }, $(this).fadeLoop)
    .fadeLoop();
});
</code>```

Working fiddle available here: http://jsfiddle.net/BEMSD/89/

Body:
If have the following code but i cant get a pause AFTER ever fade in   and fade out:

$(document).ready(function () {
    $('#signupButtonFlash').each(function (i) {
        // Get the image, set the count and an interval.
        var img = $('.bttn_play');
        img[0].$count = 0;
        img[0].$interval = setInterval(function () {
            // Animate the opacity over .2 seconds
            img.animate({
                opacity: .3
            }, 400, function ()

            {
                // When finished, animate it back to solid.
                img.animate({
                    opacity: 1
                }, 400);

            });

            // Clear the interval once we've reached 1000.
            if (++img[0].$count >= 1000) {
                clearInterval(img[0].$interval);
            }
        }, 1000);
    });
});

Body:
Your code can be reduced significantly:

$.fn.fadeLoop = function()
{
    var that = this;
    $(this).data('fadeTimer', setTimeout(function() {
        $(that).fadeOut(400, function() {
            $(that).fadeIn(400,  $(that).fadeLoop);
        });
    }, 2000));
};

$(document).ready(function() {
    $('img.bttn_play').hover(function() {
        clearTimeout($(this).data('fadeTimer'));
        $(this).stop(true).css('opacity', 1);
    }, $(this).fadeLoop)
    .fadeLoop();
});

Working fiddle available here: http://jsfiddle.net/BEMSD/89/


问:
Getting errors whenever dealing with null or NaN types when working on csv files with pandas
I am trying to replace all the Country ISO codes to Full Country Names to keep everything consistent as part of cleaning some data. I managed to find the pycountry package, which helps a ton! There are some fields on the CSV file that are empty, which I believe is causing some issues when running my code below.

Also, an additional question, not sure if it's just me, but there are times when CSV reads empty files as null/NaN or simply empty. I don't really know what went wrong there, but if possible I would like to change all those empty cells into one "thing" or type for ease of filtering/dropping it out.

df = pd.read_csv("file.csv")
#use pycountry to match the Nationalities as actual country names
import pycountry
list_alpha_2 = [i.alpha_2 for i in list(pycountry.countries)]
list_alpha_3 = [i.alpha_3 for i in list(pycountry.countries)]

def country_flag(df):
    if (len(df['Nationality'])==2 and df['Nationality'] in list_alpha_2):
        return pycountry.countries.get(alpha_2=df['Nationality']).name
    elif (len(df['Nationality'])==3 and df['Nationality'] in list_alpha_3):
        return pycountry.countries.get(alpha_3=df['Nationality']).name
    elif (len(df['Nationality'])>3):
        return df['Nationality']
    else:
        return '#N/A'

df['Nationality']=df.apply(country_flag,axis =1)
df
```

<p>I was expecting the result to be something like:</p>

```
0   AF  100 Afghanistan

1           #N/A

2   AUS 140 Australia

3    Germany    400 Germany
```

<p>The error message I am getting is </p>

<pre class="lang-py prettyprint-override"><code>TypeError: ("object of type 'float' has no len()", 'occurred at index 0')
</code>```

Yet, there shouldn't be any float type values in the 'Nationality' column I am working on. I am guessing this is simply the empty/null/NaN values being considered a float type?

答:
One idea is remove misisng values first by Series.dropna and use Series.apply:

```<code>print (df)
  Nationality
0          AF
1         NaN
2         AUS
3     Germany

import pycountry
list_alpha_2 = [i.alpha_2 for i in list(pycountry.countries)]
list_alpha_3 = [i.alpha_3 for i in list(pycountry.countries)]

def country_flag(x):
    if (len(x)==2 and x in list_alpha_2):
        return pycountry.countries.get(alpha_2=x).name
    elif (len(x)==3 and x in list_alpha_3):
        return pycountry.countries.get(alpha_3=x).name
    elif (len(x)>=3):
        return x
    else:
        return np.nan

df['Nationality'] = df['Nationality'].dropna().astype(str).apply(country_flag)
print (df)
   Nationality
0  Afghanistan
1          NaN
2    Australia
3      Germany
</code>```

Body:
I am trying to replace all the Country ISO codes to Full Country Names to keep everything consistent as part of cleaning some data. I managed to find the pycountry package, which helps a ton! There are some fields on the CSV file that are empty, which I believe is causing some issues when running my code below.

Also, an additional question, not sure if it's just me, but there are times when CSV reads empty files as null/NaN or simply empty. I don't really know what went wrong there, but if possible I would like to change all those empty cells into one "thing" or type for ease of filtering/dropping it out.

df = pd.read_csv("file.csv")
#use pycountry to match the Nationalities as actual country names
import pycountry
list_alpha_2 = [i.alpha_2 for i in list(pycountry.countries)]
list_alpha_3 = [i.alpha_3 for i in list(pycountry.countries)]

def country_flag(df):
    if (len(df['Nationality'])==2 and df['Nationality'] in list_alpha_2):
        return pycountry.countries.get(alpha_2=df['Nationality']).name
    elif (len(df['Nationality'])==3 and df['Nationality'] in list_alpha_3):
        return pycountry.countries.get(alpha_3=df['Nationality']).name
    elif (len(df['Nationality'])>3):
        return df['Nationality']
    else:
        return '#N/A'

df['Nationality']=df.apply(country_flag,axis =1)
df

I was expecting the result to be something like:

0   AF  100 Afghanistan

1           #N/A

2   AUS 140 Australia

3    Germany    400 Germany

The error message I am getting is

TypeError: ("object of type 'float' has no len()", 'occurred at index 0')

Yet, there shouldn't be any float type values in the 'Nationality' column I am working on. I am guessing this is simply the empty/null/NaN values being considered a float type?

Body:
One idea is remove misisng values first by Series.dropna and use Series.apply:

print (df)
  Nationality
0          AF
1         NaN
2         AUS
3     Germany

import pycountry
list_alpha_2 = [i.alpha_2 for i in list(pycountry.countries)]
list_alpha_3 = [i.alpha_3 for i in list(pycountry.countries)]

def country_flag(x):
    if (len(x)==2 and x in list_alpha_2):
        return pycountry.countries.get(alpha_2=x).name
    elif (len(x)==3 and x in list_alpha_3):
        return pycountry.countries.get(alpha_3=x).name
    elif (len(x)>=3):
        return x
    else:
        return np.nan

df['Nationality'] = df['Nationality'].dropna().astype(str).apply(country_flag)
print (df)
   Nationality
0  Afghanistan
1          NaN
2    Australia
3      Germany


问:
LINQ update query is not updating database records in Xamarin forms app
I am trying to update database using LINQ query, to update 'SoccerAvailability' table records where x.Email == emailTextVal. I have written my update query and its not updating in my Xamarin forms app, please advise if there is anything to fix in my query</p>

```<code>var availability = context.SoccerAvailability.Where(x => x.Email == emailTextVal);

foreach (var available in availability )
{

    available.SoccerStatus += bonusToAdd;
    available.CurrentDate += scoreToAdd;
}
</code>```

答:
you are just updating the object that exists in memory.  To persist this change back to your database you need to call Update

```<code>var availability = context.SoccerAvailability.Where(x => x.Email == emailTextVal);

foreach (var available in availability )
{

    available.SoccerStatus += bonusToAdd;
    available.CurrentDate += scoreToAdd;

    // assuming context is an SQLiteConnection
    context.Update(available);
}
</code>```

Body:
I am trying to update database using LINQ query, to update 'SoccerAvailability' table records where x.Email == emailTextVal. I have written my update query and its not updating in my Xamarin forms app, please advise if there is anything to fix in my query

var availability = context.SoccerAvailability.Where(x => x.Email == emailTextVal);

foreach (var available in availability )
{

    available.SoccerStatus += bonusToAdd;
    available.CurrentDate += scoreToAdd;
}

Body:
you are just updating the object that exists in memory.  To persist this change back to your database you need to call Update

var availability = context.SoccerAvailability.Where(x => x.Email == emailTextVal);

foreach (var available in availability )
{

    available.SoccerStatus += bonusToAdd;
    available.CurrentDate += scoreToAdd;

    // assuming context is an SQLiteConnection
    context.Update(available);
}


问:
How to fix http error 400 with microsoft ASP.NET MVC create command
I'm setting up a first C# ASP.NET MVC application using Microsofts tutorial. https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-2.2&tabs=visual-studio

In the process of this tutorial, it asks to check if the create movies works, but when I attempt to use it, I get an HTTP error 400 - bad request. I believe the data I am entering is accurate, but I can't seem to get anything but a bad request, does anyone know how to fix this.

Model class:

```<code>using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }

        [Column(TypeName = "decimal(18, 2)")]
        public decimal Price { get; set; }
    }
}
</code>```

Razor view:

```<code>@model MvcMovie.Models.Movie

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Movie</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Title" class="control-label"></label>
                <input asp-for="Title" class="form-control" />
                <span asp-validation-for="Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ReleaseDate" class="control-label"></label>
                <input asp-for="ReleaseDate" class="form-control" />
                <span asp-validation-for="ReleaseDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Genre" class="control-label"></label>
                <input asp-for="Genre" class="form-control" />
                <span asp-validation-for="Genre" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Price" class="control-label"></label>
                <input asp-for="Price" class="form-control" />
                <span asp-validation-for="Price" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
</code>```

Controller action method:

```<code>    public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            _context.Add(movie);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(movie);
    }
</code>```

The expected output is to add to the database, but but the actual output is bad request.

答: I was using google chrome, and firefox. Apparently it won't let me test on anything except edge or IE</p>

Body:
I'm setting up a first C# ASP.NET MVC application using Microsofts tutorial. https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model?view=aspnetcore-2.2&tabs=visual-studio

In the process of this tutorial, it asks to check if the create movies works, but when I attempt to use it, I get an HTTP error 400 - bad request. I believe the data I am entering is accurate, but I can't seem to get anything but a bad request, does anyone know how to fix this.

Model class:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }

        [Display(Name = "Release Date")]
        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string Genre { get; set; }

        [Column(TypeName = "decimal(18, 2)")]
        public decimal Price { get; set; }
    }
}

Razor view:

@model MvcMovie.Models.Movie

@{
    ViewData["Title"] = "Create";
}

Create

Movie

        <form asp-action="Create">

                <input asp-for="Title" class="form-control" />

                <input asp-for="ReleaseDate" class="form-control" />

                <input asp-for="Genre" class="form-control" />

                <input asp-for="Price" class="form-control" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

    Back to List

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Controller action method:

    public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
    {
        if (ModelState.IsValid)
        {
            _context.Add(movie);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(movie);
    }

The expected output is to add to the database, but but the actual output is bad request.


问:
How to launch SLComposeServiceViewController from another UIViewController
I have an iOS app with a Share Extension.

The main class of the Share Extension inherits the SLComposeServiceViewController, and in the Storyboard, I have checked "Is initial view controller". However, I need another custom view to render with more options before eventually launching the Share Extension.

I added an additional ViewController in the Storyboard and added a button inside a container. This "Share" button should launch the original Share Extension, Share View Controller Scene

I added a UIViewController class, ActionsMenuController, and set that as a custom class for Àction Menu Controller.

class ActionMenuController: UIViewController {
    @IBAction func launchShareExtension(_ sender: Any) {
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}
```

Somehow, I need to make the button's action function, launchShareExtension, switch scenes to the Share View Controller.

It seems as I should use segues to perform this, but I haven't found a way to define a segue identifier for my Share View Controller

Are there any other ways of launching a ViewController or SLComposeServiceViewController, or is there a way to achieve this using segues?

答:
I found out that adding a segue between a normal UIViewController and SLComposeServiceViewController can be done directly in the storyboard editor, but
click+ctrl on the button and drag the appearing blue line to the Share View Controller Scene. A small segue option menu will appear, choose show which will launch and share extension and replace the action menu.

I found inspiration in this storyboard tutorial
about half way through. It covers the most basics in storyboard editing.

Body:
I have an iOS app with a Share Extension.

The main class of the Share Extension inherits the SLComposeServiceViewController, and in the Storyboard, I have checked "Is initial view controller". However, I need another custom view to render with more options before eventually launching the Share Extension.

I added an additional ViewController in the Storyboard and added a button inside a container. This "Share" button should launch the original Share Extension, Share View Controller Scene

I added a UIViewController class, ActionsMenuController, and set that as a custom class for Àction Menu Controller.

class ActionMenuController: UIViewController {
    @IBAction func launchShareExtension(_ sender: Any) {
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Somehow, I need to make the button's action function, launchShareExtension, switch scenes to the Share View Controller.

It seems as I should use segues to perform this, but I haven't found a way to define a segue identifier for my Share View Controller

Are there any other ways of launching a ViewController or SLComposeServiceViewController, or is there a way to achieve this using segues?


问:
How to fix Null Point Exception in Google Or-Tools solution?
When i create test for Google Or-Tools and send my distance matrix, solution the solution is always null.

When i use default distance matrix from here https://developers.google.com/optimization/routing/vrp
but when i use my custom distanceMatrix array Assigment solution is always null.

Where is mistake?

Full test class

```<code>import com.google.ortools.constraintsolver.*;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.logging.Logger;

@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrToolsTests {

    private static final Logger logger = Logger.getLogger(OrToolsTests.class.getName());

    static {
        System.loadLibrary("jniortools");
    }

    @Test
    public void b_googleOrTools() throws Exception {
        // Instantiate the data problem.
        final DataModel data = new DataModel();

        // Create Routing Index Manager
        RoutingIndexManager manager =
                new RoutingIndexManager(data.data.length, data.vehicleNumber, data.depot);

        // Create Routing Model.
        RoutingModel routing = new RoutingModel(manager);

        // Create and register a transit callback.
        final int transitCallbackIndex =
                routing.registerTransitCallback((long fromIndex, long toIndex) -> {
                    // Convert from routing variable Index to user NodeIndex.
                    int fromNode = manager.indexToNode(fromIndex);
                    int toNode = manager.indexToNode(toIndex);
                    return data.data[fromNode][toNode];
                });

        // Define cost of each arc.
        routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex);

        // Add Distance constraint.
        routing.addDimension(transitCallbackIndex, 0, 3000,
                true, // start cumul to zero
                "Distance");
        RoutingDimension distanceDimension = routing.getMutableDimension("Distance");
        distanceDimension.setGlobalSpanCostCoefficient(100);

        // Setting first solution heuristic.
        RoutingSearchParameters searchParameters =
                main.defaultRoutingSearchParameters()
                        .toBuilder()
                        .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
                        .build();

        // Solve the problem.
        Assignment solution = routing.solveWithParameters(searchParameters);

        // Print solution on console.
        printSolution(data, routing, manager, solution);
    }

    private void printSolution(
            DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) {
        // Inspect solution.
        long maxRouteDistance = 0;
        for (int i = 0; i < data.vehicleNumber; ++i) {
            long index = routing.start(i);
            logger.info("Route for Vehicle " + i + ":");
            long routeDistance = 0;
            String route = "";
            while (!routing.isEnd(index)) {
                route += manager.indexToNode(index) + " -> ";
                long previousIndex = index;
                index = solution.value(routing.nextVar(index));
                routeDistance += routing.getArcCostForVehicle(previousIndex, index, i);
            }
            logger.info(route + manager.indexToNode(index));
            logger.info("Distance of the route: " + routeDistance + "m");
            maxRouteDistance = Math.max(routeDistance, maxRouteDistance);
        }
        logger.info("Maximum of the route distances: " + maxRouteDistance + "m");
    }

    class DataModel {
        public final long[][] data = {
                {0, 58305, 41338, 16599, 22834, 36364, 24979, 9797, 22023, 5880, 21282, 39248},
                {58147, 0, 82634, 49102, 39605, 93558, 72909, 49687, 67379, 55889, 76274, 22047},
                {41663, 81167, 0, 47046, 58798, 56366, 18071, 41586, 60532, 36117, 49432, 74933},
                {15666, 49990, 53000, 0, 7358, 51077, 30428, 13558, 34534, 13408, 33793, 30933},
                {22151, 39552, 59486, 7391, 0, 57563, 36914, 20043, 41019, 19893, 40278, 24535},
                {36164, 93036, 56237, 51331, 57566, 0, 37419, 44529, 44381, 41822, 17567, 73980},
                {25224, 72585, 18046, 30880, 37115, 37483, 0, 25147, 44093, 19678, 30549, 53529},
                {9218, 49544, 41424, 13485, 19719, 44630, 25065, 0, 28086, 5966, 27345, 30488},
                {22816, 72597, 60379, 34430, 40665, 44423, 44020, 27629, 0, 24921, 27138, 57079},
                {6858, 56163, 36826, 14458, 20693, 42270, 20467, 6781, 25726, 0, 24985, 37107},
                {22678, 75998, 49002, 34292, 40527, 17284, 30184, 27490, 27342, 24783, 0, 56941},
                {38986, 22165, 76018, 29941, 24347, 74398, 53749, 30526, 57854, 36728, 57113, 0}};
        public final int vehicleNumber = 4;
        public final int depot = 0;
    }
}
</code>```

答:
The 3000 value in #addDimension represents the vehicle maximum travel distance. Since the values in your distance matrix are higher, or-tools is not able to find a solution.

To fix this you have to change the 3000 value so that it is higher than the highest value in your distance matrix. For example

change

```<code>// Add Distance constraint.
routing.addDimension(transitCallbackIndex, 0, 3000,
        true, // start cumul to zero
        "Distance");
</code>```

to

```<code>// Add Distance constraint.
routing.addDimension(transitCallbackIndex, 0, 100000,
        true, // start cumul to zero
        "Distance");
</code>```

and your code will work.

Body:
When i create test for Google Or-Tools and send my distance matrix, solution the solution is always null.

When i use default distance matrix from here https://developers.google.com/optimization/routing/vrp
but when i use my custom distanceMatrix array Assigment solution is always null.

Where is mistake?

Full test class

import com.google.ortools.constraintsolver.*;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.logging.Logger;

@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrToolsTests {

    private static final Logger logger = Logger.getLogger(OrToolsTests.class.getName());

    static {
        System.loadLibrary("jniortools");
    }

    @Test
    public void b_googleOrTools() throws Exception {
        // Instantiate the data problem.
        final DataModel data = new DataModel();

        // Create Routing Index Manager
        RoutingIndexManager manager =
                new RoutingIndexManager(data.data.length, data.vehicleNumber, data.depot);

        // Create Routing Model.
        RoutingModel routing = new RoutingModel(manager);

        // Create and register a transit callback.
        final int transitCallbackIndex =
                routing.registerTransitCallback((long fromIndex, long toIndex) -> {
                    // Convert from routing variable Index to user NodeIndex.
                    int fromNode = manager.indexToNode(fromIndex);
                    int toNode = manager.indexToNode(toIndex);
                    return data.data[fromNode][toNode];
                });

        // Define cost of each arc.
        routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex);

        // Add Distance constraint.
        routing.addDimension(transitCallbackIndex, 0, 3000,
                true, // start cumul to zero
                "Distance");
        RoutingDimension distanceDimension = routing.getMutableDimension("Distance");
        distanceDimension.setGlobalSpanCostCoefficient(100);

        // Setting first solution heuristic.
        RoutingSearchParameters searchParameters =
                main.defaultRoutingSearchParameters()
                        .toBuilder()
                        .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
                        .build();

        // Solve the problem.
        Assignment solution = routing.solveWithParameters(searchParameters);

        // Print solution on console.
        printSolution(data, routing, manager, solution);
    }

    private void printSolution(
            DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) {
        // Inspect solution.
        long maxRouteDistance = 0;
        for (int i = 0; i < data.vehicleNumber; ++i) {
            long index = routing.start(i);
            logger.info("Route for Vehicle " + i + ":");
            long routeDistance = 0;
            String route = "";
            while (!routing.isEnd(index)) {
                route += manager.indexToNode(index) + " -> ";
                long previousIndex = index;
                index = solution.value(routing.nextVar(index));
                routeDistance += routing.getArcCostForVehicle(previousIndex, index, i);
            }
            logger.info(route + manager.indexToNode(index));
            logger.info("Distance of the route: " + routeDistance + "m");
            maxRouteDistance = Math.max(routeDistance, maxRouteDistance);
        }
        logger.info("Maximum of the route distances: " + maxRouteDistance + "m");
    }

    class DataModel {
        public final long[][] data = {
                {0, 58305, 41338, 16599, 22834, 36364, 24979, 9797, 22023, 5880, 21282, 39248},
                {58147, 0, 82634, 49102, 39605, 93558, 72909, 49687, 67379, 55889, 76274, 22047},
                {41663, 81167, 0, 47046, 58798, 56366, 18071, 41586, 60532, 36117, 49432, 74933},
                {15666, 49990, 53000, 0, 7358, 51077, 30428, 13558, 34534, 13408, 33793, 30933},
                {22151, 39552, 59486, 7391, 0, 57563, 36914, 20043, 41019, 19893, 40278, 24535},
                {36164, 93036, 56237, 51331, 57566, 0, 37419, 44529, 44381, 41822, 17567, 73980},
                {25224, 72585, 18046, 30880, 37115, 37483, 0, 25147, 44093, 19678, 30549, 53529},
                {9218, 49544, 41424, 13485, 19719, 44630, 25065, 0, 28086, 5966, 27345, 30488},
                {22816, 72597, 60379, 34430, 40665, 44423, 44020, 27629, 0, 24921, 27138, 57079},
                {6858, 56163, 36826, 14458, 20693, 42270, 20467, 6781, 25726, 0, 24985, 37107},
                {22678, 75998, 49002, 34292, 40527, 17284, 30184, 27490, 27342, 24783, 0, 56941},
                {38986, 22165, 76018, 29941, 24347, 74398, 53749, 30526, 57854, 36728, 57113, 0}};
        public final int vehicleNumber = 4;
        public final int depot = 0;
    }
}

Body:
The 3000 value in #addDimension represents the vehicle maximum travel distance. Since the values in your distance matrix are higher, or-tools is not able to find a solution.

To fix this you have to change the 3000 value so that it is higher than the highest value in your distance matrix. For example

change

// Add Distance constraint.
routing.addDimension(transitCallbackIndex, 0, 3000,
        true, // start cumul to zero
        "Distance");

to

// Add Distance constraint.
routing.addDimension(transitCallbackIndex, 0, 100000,
        true, // start cumul to zero
        "Distance");

and your code will work.


问:
Validity of domain entity method based on context or caller
I am currently reading about DDD and have a issue how to implement a certain validation.

Scenario:

I have an entity Group that contains a list of Members which in turn consists of a User and a MemberState (Member, Admin). The entity has a method MakeAdmin(User user) that turns a member into an admin.

The rule is: Only if the current user is admin of the group, it is allowed to turn the member to an admin.

I have three possible implementations in mind, with some caveats each.

Variant 1

Group enitity gets a dependency IUserContext injected via constructor to get the current user. With that the entity can check if the current user is admin and is allowed to switch the member state.
Caveat: I don't like that the domain entity has such a dependency injected and I don't think that is correct in a DDD view.

Variant 2

Method MakeAdmin() gets an additional parameter which turns it into MakeAdmin(User user, User currentUser). That removes the requirement for the IUserContext dependency in the entity.
Caveat: I am not sure if it is correct at all that the entity validates this rule, because it is not really an invariant of the entity.

Variant 3

Validate this rule in an application service, and only call MakeAdmin(User user) if validation passed.
Caveat: I consider the rule domain specific, so I think it is not correct to put it in application layer.

So what would be the best option, or is there some totally different variant?

答:
My suggestion would be to go with your third option:  Authorise access in the application/integration layer and then call into the domain.

This goes for any domain functionality really.  The domain should not concern itself with whether the action may or may not be performed based on authorisation but rather only with domain concerns.  If that authorisation action happens to be a domain concern in a particular Identity & Access Control bounded context that it would make sense but you would not run into those too often.


问:
Get result of array elements which are not matched into a single array
I am new to Javascript. I have the following Mongodb Result Array

```<code>Result = [
          {
            "userId": "5cecfab4219aca350421b063",
            "providers": [
              "1689736266",
              "1598763690",
              "1528069614",
              "1831364272",
              "1548463045",
              "1245301159",
              "1386616399",
              "1790775971",
              "1629462130",
              "1992169783"
            ],
            "countByType": {
              "doctors": 6,
              "labs": 0,
              "hospitals": 0,
              "imagingCenters": 0,
              "other": 4
            },
            "id": "5cecfab4219aca350421b066"
          }
         ]
</code>```

I have another Array

```<code>newArray = [1689736266, 1831364272, 123456789, 235695654 ];
</code>```

how to get the array value in newArray which are not in MongoDBResult providers Array.

Eg: anotherArray = [123456789, 235695654];

Also how can I get the providers Array result using Javascript.

Body:
I am new to Javascript. I have the following Mongodb Result Array

Result = [
          {
            "userId": "5cecfab4219aca350421b063",
            "providers": [
              "1689736266",
              "1598763690",
              "1528069614",
              "1831364272",
              "1548463045",
              "1245301159",
              "1386616399",
              "1790775971",
              "1629462130",
              "1992169783"
            ],
            "countByType": {
              "doctors": 6,
              "labs": 0,
              "hospitals": 0,
              "imagingCenters": 0,
              "other": 4
            },
            "id": "5cecfab4219aca350421b066"
          }
         ]

I have another Array

newArray = [1689736266, 1831364272, 123456789, 235695654 ];

how to get the array value in newArray which are not in MongoDBResult providers Array.

Eg: anotherArray = [123456789, 235695654];

Also how can I get the providers Array result using Javascript.

Body:
Use filter():

const providers =  [
          "1689736266",
          "1598763690",
          "1528069614",
          "1831364272",
          "1548463045",
          "1245301159",
          "1386616399",
          "1790775971",
          "1629462130",
          "1992169783"
        ];

const newArray = [1689736266, 1831364272, 123456789, 235695654 ];

const res = providers.filter(e => !newArray.includes("" + e));
console.log(res);