问:
Spacing around NSTextAttachment
How do I make spacing around NSTextAttachments like in the example below?

In the example No spacing is the default behaviour I get when I append a NSTextAttachment to a NSAttributedString.

答:
```<code>NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] init];
// append NSTextAttachments instance to attributedText...
// then add non-printable string with NSKernAttributeName attributes
unichar c[] = { NSAttachmentCharacter };
NSString *nonprintableString = [NSString stringWithCharacters:c length:1];
NSAttributedString *spacing = [[NSAttributedString alloc] initWithString:nonprintableString attributes:@{
    NSKernAttributeName : @(4) // spacing in points
}];
[attributedText appendAttributedString:spacing];

// finally add other text...
</code>```

Title: Spacing around NSTextAttachment


来源: stackexchange

问:
Add and remove icon dynamically when the video is clicked
I have a div where I have list of video URL and I need to add the play icon dynamically, While the video is playing and I need to remove it. While the other video is clicked and add to that video. But I am not able to remove it while other one is clicked.

Here, is my html and script what i have tried so far,

```<code>    <div class="myDiv" >
    <ul>
    <li class="videoList" id="item-0" >
    <div class="row" href="#video1">
    <div>
    <img class="ImagContent">
    </div>
    <div>
    <label class="myClass">Text</label>
    </div>
    </div>
    </li>
<li class="videoList" id="item-1" >
    <div class="row" href="#video1">
    <div>
    <img class="ImagContent">
    </div>
    <div>
    <label class="myClass">Text</label>
    </div>
    </div>
    </li>
    </ul>
    </div>

$('.myDiv').click(function () {
var id=$(this).attr('id')
   $('#'+id).find('.myclass').append('<i style="font-size:24px" class="fa"></i>');
});
</code>```

Anyone Can help me to resolve this?

Thanks in Advance!!

答:
/*$(".videoList").click(function () {

  $('.videoList').find('.myClass').html(""); // remove icon from  myClass
    $(this).find('.myClass').append(''); // append icon
});*/

$(document).on('click',".videoList",function(e) {
  e.preventDefault();
  $('.videoList').find('.myClass').html(""); // remove icon from  myclass
    $(this).find('.myClass').append(''); // append icon
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<div class="myDiv" >
    <ul>
        <li class="videoList" id="item-0" >
            <div class="row" href="#video1">
                <div>
                    <img class="ImagContent">Image 1
                </div>
                <div>
                    <label class="myClass">Text</label>
                </div>
            </div>
        </li>
        <li class="videoList" id="item-1" >
            <div class="row" href="#video1">
                <div>
                    <img class="ImagContent">Image 2
                </div>
                <div>
                    <label class="myClass">Text</label>
                </div>
            </div>
        </li>
    </ul>
</div>

</form></code>```

Try the following

```<code>$('.videoList').click(function () {
    $('.videoList').find('.myClass').html(); // remove icon from  myclass
    $(this).find('.myClass').append('<i style="font-size:24px" class="fa"></i>'); // append icon
});
</code>```

you can also use html function

```<code>$(this).find('.myClass').html('<i style="font-size:24px" class="fa"></i>');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a div where I have list of video URL and I need to add the play icon dynamically, While the video is playing and I need to remove it. While the other video is clicked and add to that video. But I am not able to remove it while other one is clicked.

Here, is my html and script what i have tried so far,

    Text

    Text

$('.myDiv').click(function () {
var id=$(this).attr('id')
   $('#'+id).find('.myclass').append('');
});

Anyone Can help me to resolve this?

Thanks in Advance!!

Body:
/*$(".videoList").click(function () {

  $('.videoList').find('.myClass').html(""); // remove icon from  myClass
    $(this).find('.myClass').append('<i style="font-size:24px" class="fa">&#xf144;</i>'); // append icon
});*/

$(document).on('click',".videoList",function(e) {
  e.preventDefault();
  $('.videoList').find('.myClass').html(""); // remove icon from  myclass
    $(this).find('.myClass').append('<i style="font-size:24px" class="fa">&#xf144;</i>'); // append icon
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<div class="myDiv" >
    <ul>
        <li class="videoList" id="item-0" >
            <div class="row" href="#video1">
                <div>
                    <img class="ImagContent">Image 1
                </div>
                <div>
                    <label class="myClass">Text</label>
                </div>
            </div>
        </li>
        <li class="videoList" id="item-1" >
            <div class="row" href="#video1">
                <div>
                    <img class="ImagContent">Image 2
                </div>
                <div>
                    <label class="myClass">Text</label>
                </div>
            </div>
        </li>
    </ul>
</div>

</form>

Try the following

$('.videoList').click(function () {
    $('.videoList').find('.myClass').html(); // remove icon from  myclass
    $(this).find('.myClass').append('<i style="font-size:24px" class="fa">&#xf144;</i>'); // append icon
});

you can also use html function

$(this).find('.myClass').html('<i style="font-size:24px" class="fa">&#xf144;</i>');


问:
Replacing a portion of a string with an exact matching
I just want to replace a portion of a string only if matches the given text.
My use case is as follows:

```<code>    var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
    string result = text.Replace("wd:response", "response");

    /*
     * expecting the below text
      <response><wd:response-data></wd:response-data></response>
     *
     */
</code>```

I followed the following answers:

Way to have String.Replace only hit "whole words"

Regular expression for exact match of a string

But I failed to achieve what I want.

Please share your thoughts/solutions.

Sample on
https://dotnetfiddle.net/pMkO8Q

答:
You can capture the string wd-response in a capturing group and replace using Regex.Replace using the MatchEvaluator like this.

Regex explanation - <[/]?(wd:response)[\s+]?>

Match < literally

Match / optionally hence the ?

Match the string wd:response and place it in a capturing group enclosed with ()

Match one or more optional whitespace [\s+]?

Match > literally

```<code>public class Program
{
    public static void Main(string[] args)
    {
        string text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
        string replacePattern = "response";
        string pattern = @"<[/]?(wd:response)[\s+]?>";
        string replacedPattern = Regex.Replace(text, pattern, match =>
        {
            // Extract the first group
            Group group = match.Groups[1];

            // Replace the group value with the replacePattern
            return string.Format("{0}{1}{2}", match.Value.Substring(0, group.Index - match.Index), replacePattern, match.Value.Substring(group.Index - match.Index + group.Length));
        });
        Console.WriteLine(replacedPattern);
    }
}
</code>```

Outputting:

```<code><response><wd:response-data></wd:response-data></response >
</code>```

Body:
I just want to replace a portion of a string only if matches the given text.
My use case is as follows:

    var text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
    string result = text.Replace("wd:response", "response");

    /*
     * expecting the below text
      <response><wd:response-data></wd:response-data></response>
     *
     */

I followed the following answers:

Way to have String.Replace only hit "whole words"

Regular expression for exact match of a string

But I failed to achieve what I want.

Please share your thoughts/solutions.

Sample on
https://dotnetfiddle.net/pMkO8Q

Body:
You can capture the string wd-response in a capturing group and replace using Regex.Replace using the MatchEvaluator like this.

Regex explanation - <[/]?(wd:response)[\s+]?>

Match < literally

Match / optionally hence the ?

Match the string wd:response and place it in a capturing group enclosed with ()

Match one or more optional whitespace [\s+]?

Match > literally

public class Program
{
    public static void Main(string[] args)
    {
        string text = "<wd:response><wd:response-data></wd:response-data></wd:response >";
        string replacePattern = "response";
        string pattern = @"<[/]?(wd:response)[\s+]?>";
        string replacedPattern = Regex.Replace(text, pattern, match =>
        {
            // Extract the first group
            Group group = match.Groups[1];

            // Replace the group value with the replacePattern
            return string.Format("{0}{1}{2}", match.Value.Substring(0, group.Index - match.Index), replacePattern, match.Value.Substring(group.Index - match.Index + group.Length));
        });
        Console.WriteLine(replacedPattern);
    }
}

Outputting:

<response><wd:response-data></wd:response-data></response >


问:
Python reads 20 records in a loop through islice
I am reading a TXT file (1GB). The content is a lot of URL records. I want to call a function to return 20 records. How can the code be modified to allow him to return the remaining N records each time? which makes me confused.

```<code>from itertools import islice

def iter_list(start，stop):
    url = []
    with open("domain.txt") as file:
        for line in islice(file, start, stop):
            url.append(line)
        return url
</code>```

def get_html(url):
    req = requests.get(url)
    print(req.status_code)
"""
     I want to extract 20 pieces to process after the cycle is completed. I don't know if this expression can be       understood.
"""
url = iter_list(1, 20)
for i in url:
    get_html(i.strip())```

答:
```<code>from itertools import islice

def iter_list(start，stop):
    url = []
    tmp = []
    with open("domain.txt") as file:
        for line in islice(file, start, stop):
            url.append(line)
            if len(url) == 20:
               url.append(tmp)
               tmp = []
        return url

for i in iter_list(start，stop):
    print(i)
</code>```

Body:
I am reading a TXT file (1GB). The content is a lot of URL records. I want to call a function to return 20 records. How can the code be modified to allow him to return the remaining N records each time? which makes me confused.

from itertools import islice

def iter_list(start，stop):
    url = []
    with open("domain.txt") as file:
        for line in islice(file, start, stop):
            url.append(line)
        return url

def get_html(url):
    req = requests.get(url)
    print(req.status_code)
"""
     I want to extract 20 pieces to process after the cycle is completed. I don't know if this expression can be       understood.
"""
url = iter_list(1, 20)
for i in url:
    get_html(i.strip())


问:
Bootstrap tooltip in wrong position on initial hover, then in correct position
I am using the tooltips from the twitter bootstrap on a div on a webpage. The tooltip is initialized, but on the first hover it is in the wrong position; however, on the subsequent hovers the tooltip is in the correct position.

I think the problem is occurring because the div that the tooltip is attached to is absolutely positioned.

Here is the div tag in my html:

```<code><div class="btn-group" id="sample-menu" data-toggle="tooltip" data-placement="left" title="Tooltip on left">
</code>```

This is how the tooltip is displayed on the first hover:

And here is how it is displayed on every hover after that:

(sizes are not changing just the screenshot crop size)

The styles applied to the div are:

```<code>#sample-menu {
  position: absolute;
  top: 95px;
  right: 608px;
}
</code>```

I could probably position the div differently to get this to work, I am just wondering why the tooltip seems to work perfectly on the absolutely positioned div, but only after the first hover.

** I added a few more tooltips on divs that aren't absolutely positioned and I have the same problem (first appearance of the tooltip is removed from my element, and then after the first appearance it is correct). I have an svg on the page with elements that are being added and sized with javascript (d3). It seems like I need to call something to reposition the tooltips after all page elements are added/sized, however, none of the Bootstrap Tooltip or Tether repositioning solutions have worked for me.

答:
You can also specify other containers (not only 'body') in tooltip config.

I had project with HTML like this:

    ...

Test message with tooltip ?

    ...

```

<p>and have issues with tooltip positioning calculation, using this JS:</p>

```$('[data-toggle="tooltip"]').tooltip({
   container: 'body'
});
```

<p>As I understood, issue was caused by <code>margin: 0</code> style of <code>body</code> element.</p>

<hr>

<p>Trying to fix this problem without changing styles of <code>body</code> element and default markup, I've used other container, like this:</p>

```$('[data-toggle="tooltip"]').tooltip({
   container: '.wrapper'
});
```

<p>and all worked perfectly without any changes.</p>

<hr>

<p>From bootstrap documentation:</p>

<p>https://getbootstrap.com/docs/4.3/components/tooltips/#options</p>

```name:    container
values:  string | element | false
default: false
descr.:  Appends the tooltip to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the tooltip in the flow of the document near the triggering element - which will prevent the tooltip from floating away from the triggering element during a window resize.
```

If you'll check bootstrap's tooltip.js, you'll see, that if you set container value as a string, it'll try to find element with given selector in DOM (see _proto._getContainer() method)

ContentLicense: CC BY-SA 3.0

Body:
I am using the tooltips from the twitter bootstrap on a div on a webpage. The tooltip is initialized, but on the first hover it is in the wrong position; however, on the subsequent hovers the tooltip is in the correct position.

I think the problem is occurring because the div that the tooltip is attached to is absolutely positioned.

Here is the div tag in my html:

This is how the tooltip is displayed on the first hover:

And here is how it is displayed on every hover after that:

(sizes are not changing just the screenshot crop size)

The styles applied to the div are:

#sample-menu {
  position: absolute;
  top: 95px;
  right: 608px;
}

I could probably position the div differently to get this to work, I am just wondering why the tooltip seems to work perfectly on the absolutely positioned div, but only after the first hover.

** I added a few more tooltips on divs that aren't absolutely positioned and I have the same problem (first appearance of the tooltip is removed from my element, and then after the first appearance it is correct). I have an svg on the page with elements that are being added and sized with javascript (d3). It seems like I need to call something to reposition the tooltips after all page elements are added/sized, however, none of the Bootstrap Tooltip or Tether repositioning solutions have worked for me.

Body:
You can also specify other containers (not only 'body') in tooltip config.

I had project with HTML like this:

<body>
    <div class='wrapper'>
    ...
        <div>
            <p>Test message with tooltip <span class="tooltip-icon"
                     data-toggle="tooltip"
                     data-placement="right"
                     title="Tooltip test">?</span></p>
        </div>
    ...
    </div>
</body>

and have issues with tooltip positioning calculation, using this JS:

$('[data-toggle="tooltip"]').tooltip({
   container: 'body'
});

As I understood, issue was caused by margin: 0 style of body element.

Trying to fix this problem without changing styles of body element and default markup, I've used other container, like this:

$('[data-toggle="tooltip"]').tooltip({
   container: '.wrapper'
});

and all worked perfectly without any changes.

From bootstrap documentation:

https://getbootstrap.com/docs/4.3/components/tooltips/#options

name:    container
values:  string | element | false
default: false
descr.:  Appends the tooltip to a specific element. Example: container: 'body'. This option is particularly useful in that it allows you to position the tooltip in the flow of the document near the triggering element - which will prevent the tooltip from floating away from the triggering element during a window resize.

If you'll check bootstrap's tooltip.js, you'll see, that if you set container value as a string, it'll try to find element with given selector in DOM (see _proto._getContainer() method)


问:
Send element tr created dynamically to a function and in it, get the values of the input in the td
I have a table to which I am adding records as follows

```<code>    var rowCount = document.getElementById('tblParteDiario').rows.length;

var row = '<tr>' +
    '   <td class="div-table-cell" style="width:8%;text-align:left; font-size=small">' + //0 = Chofer
    '       <input style="width:100%" class="form-control txtChoferAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtChoferlID' + rowCount + ' " type="hidden" /> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:5%;text-align:left; font-size=small">' + //1 = Desde
    '        <input type="text"  id="horaDesde" class="timepickerD form-control txtDesde' + rowCount +'"/> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:5%;text-align:left; font-size=small">' + //2 = Hasta
    '        <input type="text" id="horaHasta" onBlur="testFunction(this.parentNode.parentNode);" class="timepickerH form-control txtHasta' + rowCount + '"/> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:3%;text-align:left; font-size=small">' + //3 = TiempoTranscurrido
    '        <input type="text" class="form-control txtTranscurrido' + rowCount + '"/> ' +
    '   </td> ' +
    '   <td class="div-table-cell" style="width:8%;text-align:left; font-size=small">' + //4 = Pozo
    '       <input style="width:100%" class="form-control txtPozoAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtPozolID' + rowCount + ' " type="hidden" /> ' +
    '   </td> ' +
    '</tr>';

$("#tblParteDiario").append(row);
</code>```

In the input of the column "2 = Hasta" I have specified that in the onBlur call a function and it receives the element tr, well, that works. How do I get the value of the inputs that are in the td 1 and 3, for example and in the case of the column "4 = Pozo" how do I get the value of the first input within the td

I leave the function that receives the tr with one of the many attempts that made to achieve the objective. In this case, the log tells me that .find is not a valid function

```<code>function testFunction(element) {
element.find('td:eq(3) input').each(function () {
    task = this.value;
    console.log(task);
});}
</code>```

答:
You can do it with jQuery but you are creating table rows in HTML text and jQuery functions might not always work with text HTML content. They work properly with HTML DOM content. Your text HTML may not always be detected as HTML table row. So, I think find will not always work correctly in all browsers.

I have created the testFunction as given below. It requires to add the child class or id property of tr, td and input elements.

```<code>function testFunction(element){
    var eltbl = $(element).parent().parent().attr("id");

    var txtChoferAutocomplete = $("#"+eltbl+" .div-table-cell > .txtChoferAutocomplete0").val();
    var txtChoferlID = $("#"+eltbl+" .div-table-cell > .txtChoferlID0").val();
    var horaDesde = $("#"+eltbl+" .div-table-cell > #horaDesde").val();
    var horaHasta = $("#"+eltbl+" .div-table-cell > #horaHasta").val();
    var txtTranscurrido = $("#"+eltbl+" .div-table-cell > .txtTranscurrido0").val();
    var txtPozoAutocomplete = $("#"+eltbl+" .div-table-cell > .txtPozoAutocomplete0").val();
    var txtPozolID = $("#"+eltbl+" .div-table-cell > .txtPozolID0").val();

    console.log(txtChoferAutocomplete);
    console.log(txtChoferlID);
    console.log(horaDesde);
    console.log(horaHasta);
    console.log(txtTranscurrido);
    console.log(txtPozoAutocomplete);
    console.log(txtPozolID);

}
</code>```

Body:
I have a table to which I am adding records as follows

    var rowCount = document.getElementById('tblParteDiario').rows.length;

var row = '
' +
    '   ' + //0 = Chofer
    '       <input style="width:100%" class="form-control txtChoferAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtChoferlID' + rowCount + ' " type="hidden" /> ' +
    '   	 ' +
    '   ' + //1 = Desde
    '        <input type="text"  id="horaDesde" class="timepickerD form-control txtDesde' + rowCount +'"/> ' +
    '   	 ' +
    '   ' + //2 = Hasta
    '        <input type="text" id="horaHasta" onBlur="testFunction(this.parentNode.parentNode);" class="timepickerH form-control txtHasta' + rowCount + '"/> ' +
    '   	 ' +
    '   ' + //3 = TiempoTranscurrido
    '        <input type="text" class="form-control txtTranscurrido' + rowCount + '"/> ' +
    '   	 ' +
    '   ' + //4 = Pozo
    '       <input style="width:100%" class="form-control txtPozoAutocomplete' + rowCount + ' " placeholder = "Búsqueda" /> ' +
    '       <input class="txtPozolID' + rowCount + ' " type="hidden" /> ' +
    '   	 ' +
    '
';

$("#tblParteDiario").append(row);

In the input of the column "2 = Hasta" I have specified that in the onBlur call a function and it receives the element tr, well, that works. How do I get the value of the inputs that are in the td 1 and 3, for example and in the case of the column "4 = Pozo" how do I get the value of the first input within the td

I leave the function that receives the tr with one of the many attempts that made to achieve the objective. In this case, the log tells me that .find is not a valid function

function testFunction(element) {
element.find('td:eq(3) input').each(function () {
    task = this.value;
    console.log(task);
});}

Body:
You can do it with jQuery but you are creating table rows in HTML text and jQuery functions might not always work with text HTML content. They work properly with HTML DOM content. Your text HTML may not always be detected as HTML table row. So, I think find will not always work correctly in all browsers.

I have created the testFunction as given below. It requires to add the child class or id property of tr, td and input elements.

function testFunction(element){
    var eltbl = $(element).parent().parent().attr("id");

    var txtChoferAutocomplete = $("#"+eltbl+" .div-table-cell > .txtChoferAutocomplete0").val();
    var txtChoferlID = $("#"+eltbl+" .div-table-cell > .txtChoferlID0").val();
    var horaDesde = $("#"+eltbl+" .div-table-cell > #horaDesde").val();
    var horaHasta = $("#"+eltbl+" .div-table-cell > #horaHasta").val();
    var txtTranscurrido = $("#"+eltbl+" .div-table-cell > .txtTranscurrido0").val();
    var txtPozoAutocomplete = $("#"+eltbl+" .div-table-cell > .txtPozoAutocomplete0").val();
    var txtPozolID = $("#"+eltbl+" .div-table-cell > .txtPozolID0").val();

    console.log(txtChoferAutocomplete);
    console.log(txtChoferlID);
    console.log(horaDesde);
    console.log(horaHasta);
    console.log(txtTranscurrido);
    console.log(txtPozoAutocomplete);
    console.log(txtPozolID);

}


问:
Return multiple elements using Lodash _.get?
I have this JavaScript object:

const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
}
```

<p>I was able to select only one item using Lodash's <code>_.get</code> method.</p>

<pre class="lang-js prettyprint-override"><code>_.get(object, 'categories[0].items[0].image')
// => "path/to/file-1.png"
</code>```

But I need an array with all occurrences, not just from position 0. Something like this:

_.get(object, 'categories[].items[].image')
// => ["path/to/file-1.png", "path/to/file-2.png", "path/to/file-3.png", "path/to/file-4.png", "path/to/file-5.png", "path/to/file-6.png"]
```

Is it possible to do it using Lodash?

If it's not possible, do you have any idea how to implement it?

EDIT: I'm looking for something like _.get from Lodash, where I can supply the "search schema" (path) as string. Obviously I know how to solve this with map, reduce, etc.

答:
This is pretty easy to do with flatMap, no library required:

const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
};

const images = object.categories.flatMap(({ items }) => items.map(({ image }) => image));
console.log(images);```
</div>
</div>
</p>

<p>Or, with <code>reduce</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
};

const images = object.categories.reduce((a, { items }) => {
  items.forEach(({ image }) => {
    a.push(image);
  });
  return a;
}, []);
console.log(images);</code>```

Body:
I have this JavaScript object:

const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
}

I was able to select only one item using Lodash's _.get method.

_.get(object, 'categories[0].items[0].image')
// => "path/to/file-1.png"

But I need an array with all occurrences, not just from position 0. Something like this:

_.get(object, 'categories[].items[].image')
// => ["path/to/file-1.png", "path/to/file-2.png", "path/to/file-3.png", "path/to/file-4.png", "path/to/file-5.png", "path/to/file-6.png"]

Is it possible to do it using Lodash?

If it's not possible, do you have any idea how to implement it?

EDIT: I'm looking for something like _.get from Lodash, where I can supply the "search schema" (path) as string. Obviously I know how to solve this with map, reduce, etc.

Body:
This is pretty easy to do with flatMap, no library required:

const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
};

const images = object.categories.flatMap(({ items }) => items.map(({ image }) => image));
console.log(images);

Or, with reduce:

const object = {
  categories: [
    {
      title: 'Category 1',
      items: [
        { title: 'Item 1', image: 'path/to/file-1.png' },
        { title: 'Item 2', image: 'path/to/file-2.png' },
        { title: 'Item 3', image: 'path/to/file-3.png' }
      ]
    },
    {
      title: 'Category 2',
      items: [
        { title: 'Item 4', image: 'path/to/file-4.png' },
        { title: 'Item 5', image: 'path/to/file-5.png' },
        { title: 'Item 6', image: 'path/to/file-6.png' }
      ]
    }
  ]
};

const images = object.categories.reduce((a, { items }) => {
  items.forEach(({ image }) => {
    a.push(image);
  });
  return a;
}, []);
console.log(images);


问:
Best approach to get notifications from database when table record changing in asp.net core web api
I'm working with asp.net-core 2.2 web api project with angular 7. In this I want to get notifications when a record inserting or updating in specific table. I read many of articles on it with sqldependancy class. But none of them didn't give me any satisfied answer. The thing I want to know is, are there any best approaches to do this work with another way. And if the best approach is,using sqldependecy how to combine it with EntityFramework core?</p>

答:
You could create an AFTER UPDATE TRIGGER on the table. Depending on how you want to get notified (SQL Mail for example) you could then code for it. </p>

<p>(on a personal note, I hate triggers but this is another way to do it)</p>

Body:
You could create an AFTER UPDATE TRIGGER on the table. Depending on how you want to get notified (SQL Mail for example) you could then code for it.

(on a personal note, I hate triggers but this is another way to do it)


问:
RegEx for capturing numbers in parentheses
Example

```<code>Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]
</code>```

I want to get 15.7 from Alarm Level 1 and -12.7 from Alarm Level 2.  I tried to use \((.*?)\) but it get both D1 and 15.7 in Alarm Level 1.

答:
Using regular expression with pattern of:

```<code>\[\w+\s\\([\d.-]+\\)\]
</code>```

To match either "[Low (15.7)]" or "[High (-12.7)]" by matching

a. "[" & "]"    to match square bracket

b. "\w+"          to match one or more words ("Low" or "High" in this case)

c. "\s"           to match a single whitespace

d. "\(" & "\)"    to match parenthesis

e. [\d.-]+         to match combination of digits, "." & "-"

Followed by pattern of:

```<code>[\d.-]+
</code>```

To capture the value required

Source Code:

```<code>    static void Main(string[] args)
    {
        string input = "Alarm Level 1 (D1) [Low (-15.7)]";
        string pattern = @"\[\w+\s\([\d.-]+\)\]";
        string outputA = Regex.Match(input, pattern).Value;
        string outputB = Regex.Match(outputA, @"[\d.-]+").Value;

        Console.WriteLine("A: " + outputA);
        Console.WriteLine("B: " + outputB);

        Double intOutput = Convert.ToDouble(outputB);

        Console.ReadLine();
    }
</code>```

Body:
Example

Alarm Level 1 (D1) [Low (15.7)]
Alarm Level 2 [High (-12.7)]

I want to get 15.7 from Alarm Level 1 and -12.7 from Alarm Level 2.  I tried to use \((.*?)\) but it get both D1 and 15.7 in Alarm Level 1.

Body:
Using regular expression with pattern of:

\[\w+\s\\([\d.-]+\\)\]

To match either "[Low (15.7)]" or "[High (-12.7)]" by matching

a. "[" & "]"    to match square bracket

b. "\w+"          to match one or more words ("Low" or "High" in this case)

c. "\s"           to match a single whitespace

d. "\(" & "\)"    to match parenthesis

e. [\d.-]+         to match combination of digits, "." & "-"

Followed by pattern of:

[\d.-]+

To capture the value required

Source Code:

    static void Main(string[] args)
    {
        string input = "Alarm Level 1 (D1) [Low (-15.7)]";
        string pattern = @"\[\w+\s\([\d.-]+\)\]";
        string outputA = Regex.Match(input, pattern).Value;
        string outputB = Regex.Match(outputA, @"[\d.-]+").Value;

        Console.WriteLine("A: " + outputA);
        Console.WriteLine("B: " + outputB);

        Double intOutput = Convert.ToDouble(outputB);

        Console.ReadLine();
    }


问:
Couldn't get text from a text field using selenium
I am trying to get value from a text field using selenium, but I am not able to. The value is neither present between the tags nor in the attribute "value".Please help me with this.

I have tried following ways but nothing worked.

```<code>Webelement.getAttribute("innerText");

Webelement.gettext();

Webelement.getAttribute("value");

Webelement.getAttribute("textcontent");
</code>```

Below is the HTML for the text field.

```<code><input name="quantityField_valueFieldKeyboard" id="quantityField_valueFieldKeyboard" data-mini="true" data-clear-btn="false" maxlength="61" seyctype="numeric" class="seyc-visually-important seyc-ui-input-icon-white seyc-ui-input-text">
</code>```

答:
is this what you are trying?</p>

```<code>driver.findElement(By.id("quantityField_valueFieldKeyboard")).getAttribute("value");
</code>```

Body:
I am trying to get value from a text field using selenium, but I am not able to. The value is neither present between the tags nor in the attribute "value".Please help me with this.

I have tried following ways but nothing worked.

Webelement.getAttribute("innerText");

Webelement.gettext();

Webelement.getAttribute("value");

Webelement.getAttribute("textcontent");

Below is the HTML for the text field.

<input name="quantityField_valueFieldKeyboard" id="quantityField_valueFieldKeyboard" data-mini="true" data-clear-btn="false" maxlength="61" seyctype="numeric" class="seyc-visually-important seyc-ui-input-icon-white seyc-ui-input-text">

Body:
is this what you are trying?

driver.findElement(By.id("quantityField_valueFieldKeyboard")).getAttribute("value");


问:
Delay Action in Javascript without stopping the rest of the code
Trying to delay shooting in a game, the action is done by clicking but currently, it shots every frame while holding click.

SetTimeInterval does not work in my case since it just loops the function
SetTimeout does not work as well because it stops the function the second it's played and after the interval.
Tried a sleep function but it freezes up the code while running

```<code>//sleepcode
var sleep = function(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
//called by:
if(self.pressingAttack){
    self.shootBullet(self.mouseAngle);
    sleep(3000);
}
</code>```

I want a function that shots the second its clicked but delays the second bullets, similar to every shooting game ever.

答:
You must use promises for "sleep".

```<code>function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
</code>```

And to use the promise to wait, IE use await, you can only do that in an async function. It should also be noted that you do not want this in your main game loop because the code will stop and wait ... so your main loop needs to call the attack loop and not wait for it.

```<code>async function Attackloop() {

// some code

     while (self.pressingAttack) {
         self.shootBullet(self.mouseAngle);
         await sleep(3000);
     }

// some code.

}
</code>```

Body:
Trying to delay shooting in a game, the action is done by clicking but currently, it shots every frame while holding click.

SetTimeInterval does not work in my case since it just loops the function
SetTimeout does not work as well because it stops the function the second it's played and after the interval.
Tried a sleep function but it freezes up the code while running

//sleepcode
var sleep = function(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}
//called by:
if(self.pressingAttack){
    self.shootBullet(self.mouseAngle);
    sleep(3000);
}

I want a function that shots the second its clicked but delays the second bullets, similar to every shooting game ever.

Body:
You must use promises for "sleep".

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

And to use the promise to wait, IE use await, you can only do that in an async function. It should also be noted that you do not want this in your main game loop because the code will stop and wait ... so your main loop needs to call the attack loop and not wait for it.

async function Attackloop() {

// some code

     while (self.pressingAttack) {
         self.shootBullet(self.mouseAngle);
         await sleep(3000);
     }

// some code.

}


问:
MismatchedInputException: Cannot construct instance of `java.util.LinkedHashMap`
I tried to map LinkedHashMap in JSON in my kotlin testcase. while I am converting json to object using jackson-objectmapper, I have got below issue, Kindly help me to solve this.

```<code>construct instance of java.util.LinkedHashMap (although at least one
Creator exists): no String-argument constructor/factory method to
deserialize from String value ('{e123f1dd-6c54-4b01-90e6-
d701748f0851=class MyClass {
</code>```

My Kotlin testcase below

```<code>fun `testcase success`() {

val mapId = UUID.fromString("e123f1dd-6c54-4b01-90e6-d701748f0851");
  val Idno = UUID.randomUUID();

  val order = MyClass();

  val map : LinkedHashMap<String, MyClass> = LinkedHashMap();

  order.collectiveSignature=true
  order.docId="5436576"
  order.status=OnboardOrderPoaStatusTPL.NOT_SIGNED
  order.createdAt=createdDate
  order.updatedAt=updatedDate
  order.portingAt=OffsetDateTime.parse("2018-09-21T14:22:24.682+02:00");
  order.fastPorting=true
  order.owner=MyAnotherClass();
  order.owner.company="test"
  order.owner.firstName="test"
  order.owner.lastName="test"
  order.owner.city="test"
  order.owner.zip="5436"
  order.owner.street="test"
  order.owner.house="test"

  map["e123f1dd-6c54-4b01-90e6-d701748f0851"] = order;

  val body = """{

          "mapId": "$mapId",
          "Idno": "$Idno",
          "name": "Abishek",
          "poas":"$map"

         }""".trimIndent()

  val mapper = ObjectMapper()
  mapper.findAndRegisterModules()

  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
  mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, false);

  val input = mapper.readValue<MainClass>(body)

}
</code>```

答:
The problem is poas value contains String representation of Map, which contains String representation of MyClass.
Indeed, insead of creating Json representation you called MyClass.toString() and purpose of toString is show debug information.

How to fix it?

Using ObjectMapper you should convert Map to json, instead of using toString()

```<code>  val body = """{

          "mapId": "$mapId",
          "Idno": "$Idno",
          "name": "Abishek",
          "poas": "${mapper.writeValue(map)}"

         }""".trimIndent()

</code>```

Body:
I tried to map LinkedHashMap in JSON in my kotlin testcase. while I am converting json to object using jackson-objectmapper, I have got below issue, Kindly help me to solve this.

construct instance of java.util.LinkedHashMap (although at least one
Creator exists): no String-argument constructor/factory method to
deserialize from String value ('{e123f1dd-6c54-4b01-90e6-
d701748f0851=class MyClass {

My Kotlin testcase below

fun `testcase success`() {

val mapId = UUID.fromString("e123f1dd-6c54-4b01-90e6-d701748f0851");
  val Idno = UUID.randomUUID();

  val order = MyClass();

  val map : LinkedHashMap<String, MyClass> = LinkedHashMap();

  order.collectiveSignature=true
  order.docId="5436576"
  order.status=OnboardOrderPoaStatusTPL.NOT_SIGNED
  order.createdAt=createdDate
  order.updatedAt=updatedDate
  order.portingAt=OffsetDateTime.parse("2018-09-21T14:22:24.682+02:00");
  order.fastPorting=true
  order.owner=MyAnotherClass();
  order.owner.company="test"
  order.owner.firstName="test"
  order.owner.lastName="test"
  order.owner.city="test"
  order.owner.zip="5436"
  order.owner.street="test"
  order.owner.house="test"

  map["e123f1dd-6c54-4b01-90e6-d701748f0851"] = order;

  val body = """{

          "mapId": "$mapId",
          "Idno": "$Idno",
          "name": "Abishek",
          "poas":"$map"

         }""".trimIndent()

  val mapper = ObjectMapper()
  mapper.findAndRegisterModules()

  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
  mapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, false);

  val input = mapper.readValue<MainClass>(body)

}

Body:
The problem is poas value contains String representation of Map, which contains String representation of MyClass.
Indeed, insead of creating Json representation you called MyClass.toString() and purpose of toString is show debug information.

How to fix it?

Using ObjectMapper you should convert Map to json, instead of using toString()

  val body = """{

          "mapId": "$mapId",
          "Idno": "$Idno",
          "name": "Abishek",
          "poas": "${mapper.writeValue(map)}"

         }""".trimIndent()


问:
I want to create image by passing list of tuple in python
```<code>import numpy as np

from PIL  import Image

img=Image.open("Car.jpg")

array= np.array(img)

a = array

rgb=250,0,0

for  i  in  range(768):
      for  j  in  range(500):
             a[ i ] [ j ]=rgb

new_image=Image.fromarray(array)

new_image.save( "new.jpg" )

new_image.show()
</code>```

I want to pass rgb values like list of tuple :

```<code>rgb = [(255,0,0),
(198, 252, 247), (255, 255, 250) ,(254, 253, 248) ,(251, 252, 246), (247, 248, 240) ...
(100, 144, 247), (255, 200, 250), (254, 253,0)]
</code>```

and rgb value change with i  and  j

```<code>a [ i ] [ j ] = rgb
</code>```

答:
from PIL import Image

img = Image.open("Car.jpg")
rgb = 250,0,0
for i in range(768):
    for j in range(500):
        im.putpixel((i, j), rgb)
img = img.convert("RGB")
img.save("new.jpg")
img.show()
```

Did you mean this way?

Body:
import numpy as np

from PIL  import Image

img=Image.open("Car.jpg")

array= np.array(img)

a = array

rgb=250,0,0

for  i  in  range(768):
      for  j  in  range(500):
             a[ i ] [ j ]=rgb

new_image=Image.fromarray(array)

new_image.save( "new.jpg" )

new_image.show()

I want to pass rgb values like list of tuple :

rgb = [(255,0,0),
(198, 252, 247), (255, 255, 250) ,(254, 253, 248) ,(251, 252, 246), (247, 248, 240) ...
(100, 144, 247), (255, 200, 250), (254, 253,0)]

and rgb value change with i  and  j

a [ i ] [ j ] = rgb

Body:
from PIL import Image

img = Image.open("Car.jpg")
rgb = 250,0,0
for i in range(768):
    for j in range(500):
        im.putpixel((i, j), rgb)
img = img.convert("RGB")
img.save("new.jpg")
img.show()

Did you mean this way?


问:
problem facing with android application on two different android platform O.S. device
I have build one android application in androids version(2.2) and i have specified minimum sdk version in android manifest file as 3 i.e (version-1.5) .so i have to make sure that this application should run successfully on api leval of device having from 3 i.e Version(1.5) to 8 Version(2.2but since contact content provider for android Api platform "leval(4)" and "leval(8)" are different,and in my application i am using contact content provider,i am facing exceptions as "illegal argument","null pointer","uncought exception" at runtime.

On the other side if i build the application with version(1.6),It not gives runtime exception but when i tried to get contact details from device e.g(phone number,email),it gives null value as "null pointer" exception.

do you have any proper solution for this.please replay..

答:
If you only want to ship one version of your app, you should use android.os.Build.VERSION to determine the API level, and thus the right API to use.

Hope this helps,

Phil Lello


问:
is there a way to know how many lanes in a road?
Currently, I'm working on a Mapping Project , and I'd like to know if there's a way to know how many lanes in a single road (same direction), using one of Maps API, like google map. Because at the end I have to display if a lane is blocked, which kind of vehicles can go on a lane, and also the speed limit. But for now I just need to display the number of lanes.

For my application, I'm using Xamarin and Xamarin.forms.maps to display the map and also the Plugin.geolocator for some geolocation informations.

答:
This feature has been requested in the Issue Tracker of Google Maps APIs. However, the request has been rejected as it will violate the compliance of the Google Maps Platform Terms of Service.

They said in the request:

Unfortunately, exposing this in the Directions API would encourage use
  of the Maps APIs in ways that would not be in compliance with the
  Google Maps/Google Earth APIs Terms of Service at
  https://developers.google.com/maps/terms#10-license-restrictions

10.4 Restrictions on Unfair Exploitation of the Service and Content.

c. Restrictions on your Maps API Implementations.

iii: No navigation. You will not use the Service or Content for or in
  connection with (a) real-time navigation or route guidance; or (b)
  automatic or autonomous vehicle control.

You may check the Feature Request here.

This is only applicable to Google Maps Platform, I'm not sure though with other Maps provider. Hope this helps.


问:
Is there an equivalent "eval" function for swift, like there is in Matlab?
If not, how can I loop through IBOutlets (like temp1, temp2, temp3) and chance a property sequentially?

In matlab, I would concatenate a string and use eval.

```<code>for k = 1:3
    eval(["temp",num2str(k)]);
end
</code>```

I'm new to Swift, and want to do this with IBOutlets. Something like,

```<code>for(var k = 0, ++k, k==4) {
    eval(["self.temp",String(k),".backgroundcolor"]);
end
</code>```

I know the eval function is in Matlab format, but I'm just expressing what I'd like to have done.

答:
Yes, you can do eval in swift. See here:

https://github.com/johnno1962/InjectionIII/tree/master/EvalApp

Source code:
https://github.com/johnno1962/InjectionIII/blob/master/InjectionBundle/SwiftEval.swift

Body:
If not, how can I loop through IBOutlets (like temp1, temp2, temp3) and chance a property sequentially?

In matlab, I would concatenate a string and use eval.

for k = 1:3
    eval(["temp",num2str(k)]);
end

I'm new to Swift, and want to do this with IBOutlets. Something like,

for(var k = 0, ++k, k==4) {
    eval(["self.temp",String(k),".backgroundcolor"]);
end

I know the eval function is in Matlab format, but I'm just expressing what I'd like to have done.


问:
regex pattern not fit well for code like assignment
i am trying to use a regular expression to match expression like code assignment
for example:

```<code>"k=++g677"
"k=--j77"
"k=++gfrf677frfr"
</code>```

i've tried:

```<code>([a-zA-Z])([a-zA-Z]|\d)*[=][+][+]|[-][-]|[*][*]|[\/][\/]([\d]*|([a-zA-Z]([a-zA-Z]\d)*))
</code>```

but it's seemds to match also things like

```<code>"k++"
"k=++@ff"
</code>```

can u help?

答:
You can use the following regular expression: ([a-zA-Z_](?:[a-zA-Z0-9_])*)\s*=\s*(\d+|(\+\+|--|\*\*|//)?((?:[a-zA-Z_](?:[a-zA-Z0-9_])*))|(?:[a-zA-Z_](?:[a-zA-Z0-9_])*)(\+\+|--))$

It is long because of its last part, so it will match for k = x++ too.

One problem was that you forgot to use some parenthesis. Use them everywhere, in that way you can make sure that nothing happens unintentionally.

[\d]* matches nothing, [\d]+ is what you shall use.

Note: A variable name can contain the _ character.

See explanation on regex101...

Body:
i am trying to use a regular expression to match expression like code assignment
for example:

"k=++g677"
"k=--j77"
"k=++gfrf677frfr"

i've tried:

([a-zA-Z])([a-zA-Z]|\d)*[=][+][+]|[-][-]|[*][*]|[\/][\/]([\d]*|([a-zA-Z]([a-zA-Z]\d)*))

but it's seemds to match also things like

"k++"
"k=++@ff"

can u help?


问:
Load related data without foreign key constraint in ef-core-2.1
I want to load related entities data Parent by using Eager Loading O/RM pattern. But I can't specify a foregin key constraint on ParentId because it creates a cycle which is not allowed. Currently, I'm using an inner join to load Parent data explicitly.

Here is my Domain Model that I'm using.

```<code>[Table("Category")]
public class CategoryDM
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    [Display(Name="Parent")]
    public int ParentId { get; set; }
    [NotMapped]
    public CategoryDM Parent { get; set; }
}
</code>```

Is there any way to load related entities like this? or any other recommended way to achieve this.

```<code>var result = _context.Category.Include(e => e.Parent);
</code>```

答:
This should work fine, here is an exemplary working model.

Model

```<code>    public class Category : ISelfRelated<Category>
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ThumbnailUrl { get; set; }
        public int? ParentId { get; set; }
        public Category Parent { get; set; }
        public IEnumerable<Category> Children { get; set; }
    }
</code>```

Model configuration

```<code>            category.HasOne(c => c.Parent)
                .WithMany(c => c.Children)
                .HasForeignKey(c => c.ParentId)
                .HasPrincipalKey(c => c.Id)
                .OnDelete(DeleteBehavior.Restrict)
                .IsRequired(false);
</code>```

Body:
I want to load related entities data Parent by using Eager Loading O/RM pattern. But I can't specify a foregin key constraint on ParentId because it creates a cycle which is not allowed. Currently, I'm using an inner join to load Parent data explicitly.

Here is my Domain Model that I'm using.

[Table("Category")]
public class CategoryDM
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    [Display(Name="Parent")]
    public int ParentId { get; set; }
    [NotMapped]
    public CategoryDM Parent { get; set; }
}

Is there any way to load related entities like this? or any other recommended way to achieve this.

var result = _context.Category.Include(e => e.Parent);

Body:
This should work fine, here is an exemplary working model.

Model

    public class Category : ISelfRelated<Category>
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ThumbnailUrl { get; set; }
        public int? ParentId { get; set; }
        public Category Parent { get; set; }
        public IEnumerable<Category> Children { get; set; }
    }

Model configuration

            category.HasOne(c => c.Parent)
                .WithMany(c => c.Children)
                .HasForeignKey(c => c.ParentId)
                .HasPrincipalKey(c => c.Id)
                .OnDelete(DeleteBehavior.Restrict)
                .IsRequired(false);


问:
absolute layout in scroll view on android
i want to Android xml design in the following format i did but it does not work.

xml layout:coding

```<code>    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <TableLayout android:id="@+id/widget836"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView android:id="@+id/widget837" android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </ImageView>
        </TableLayout>
        <ScrollView android:id="@+id/ScrollView111"
            android:layout_width="fill_parent" android:layout_height="fill_parent">

            <AbsoluteLayout android:id="@+id/widget883"
                android:layout_width="wrap_content" android:layout_height="wrap_content">

                <EditText android:id="@+id/email" android:layout_width="303px"
                    android:layout_height="56px" android:text="Email" android:textSize="18sp"
                    android:layout_x="1px" android:layout_y="15px">
                </EditText>
                <EditText android:id="@+id/pass" android:layout_width="303px"
                    android:layout_height="56px" android:text="password"
                    android:textSize="18sp" android:layout_x="3px" android:layout_y="57px">
                </EditText>

                <TextView android:id="@+id/enter" android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:text="Enter an email address and password above, and your accout will be created."
                    android:layout_x="0px" android:layout_y="65px">
                </TextView>
                <TextView android:id="@+id/primarydisplay"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Primary Display" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="75px">
                </TextView>
                <TextView android:id="@+id/gps" android:layout_width="100px"
                    android:layout_height="40px" android:text="Speed >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="75px">
                </TextView>
            </AbsoluteLayout>
            <AbsoluteLayout android:id="@+id/widget884"
                android:layout_width="wrap_content" android:layout_height="wrap_content">
                <TextView android:id="@+id/distanceunit"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Distance Unit" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="85px">
                </TextView>
                <TextView android:id="@+id/miles" android:layout_width="100px"
                    android:layout_height="40px" android:text="Miles >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="85px">
                </TextView>
            </AbsoluteLayout>
        </ScrollView>
    </LinearLayout>
</code>```

Log cat error:

Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child

pleae correct me.

答: As the error says, ScrollView is designed for a single child element. Yours contains two AbsoluteLayouts. Can these views be merged?

Body:
i want to Android xml design in the following format i did but it does not work.

xml layout:coding

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <TableLayout android:id="@+id/widget836"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:orientation="vertical">
            <ImageView android:id="@+id/widget837" android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </ImageView>
        </TableLayout>
        <ScrollView android:id="@+id/ScrollView111"
            android:layout_width="fill_parent" android:layout_height="fill_parent">

            <AbsoluteLayout android:id="@+id/widget883"
                android:layout_width="wrap_content" android:layout_height="wrap_content">

                <EditText android:id="@+id/email" android:layout_width="303px"
                    android:layout_height="56px" android:text="Email" android:textSize="18sp"
                    android:layout_x="1px" android:layout_y="15px">
                </EditText>
                <EditText android:id="@+id/pass" android:layout_width="303px"
                    android:layout_height="56px" android:text="password"
                    android:textSize="18sp" android:layout_x="3px" android:layout_y="57px">
                </EditText>

                <TextView android:id="@+id/enter" android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:text="Enter an email address and password above, and your accout will be created."
                    android:layout_x="0px" android:layout_y="65px">
                </TextView>
                <TextView android:id="@+id/primarydisplay"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Primary Display" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="75px">
                </TextView>
                <TextView android:id="@+id/gps" android:layout_width="100px"
                    android:layout_height="40px" android:text="Speed >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="75px">
                </TextView>
            </AbsoluteLayout>
            <AbsoluteLayout android:id="@+id/widget884"
                android:layout_width="wrap_content" android:layout_height="wrap_content">
                <TextView android:id="@+id/distanceunit"
                    android:layout_width="100px" android:layout_height="40px"
                    android:text="Distance Unit" android:textStyle="bold"
                    android:layout_x="0px" android:layout_y="85px">
                </TextView>
                <TextView android:id="@+id/miles" android:layout_width="100px"
                    android:layout_height="40px" android:text="Miles >"
                    android:textStyle="bold" android:layout_x="200px" android:layout_y="85px">
                </TextView>
            </AbsoluteLayout>
        </ScrollView>
    </LinearLayout>

Log cat error:

Caused by: java.lang.IllegalStateException: ScrollView can host only one direct child

pleae correct me.


问:
How to create Custom UITableViewCell with dynamic number of labels
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}
</code>```

答:
This can be achieved using a UIStackview. Here is the sample code for a view controller that has a tableview whose each row can show 1, 2 or 3 labels. The cellForRow datasource method has the logic to switch the count of lables according to the requirement.

```<code>import UIKit

class ViewController: UIViewController {

    // This array contains the sample data to populate the tableview. Each
       element dictates the number of labels to be shown in the cell
    var tableData = [1,2,3,2,3,2]
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
        return tableData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelRow",
for: indexPath) as! LabelTableViewCell

        let labelCount = tableData[indexPath.row]

        // Check the label count for the current row to decide how many labels to show.
        // Extra lables are hidden
        switch labelCount {
        case 1:
            cell.label1.isHidden = false
            cell.label2.isHidden = true
            cell.label3.isHidden = true
        case 2:
            cell.label1.isHidden = false
            cell.label2.isHidden = false
            cell.label3.isHidden = true
        default:
            cell.label1.isHidden = false
            cell.label2.isHidden = false
            cell.label3.isHidden = false
        }

        return cell
    }
}
</code>```

The LabelTableViewCell class is a subclass of UITableViewCell and it contains a UIStackView. The stack view handles the task of arranging the labels vertically. Also as one or more labels(which are added as arranged subviews of the stack view in Interface Builder) are hidden, the stack view's height gets adjusted. The trick is to have constraints between the stackview's top to the cell's content view's top and similar bottom constraints. This will ensure that when the stackview's height changes, the cell's height also changes accordingly.

I have added the project to GitHub for better understanding

Here is a screenshot of the result.

Body:
each custom cell in tableview can either have one or two or three or more labels depending on the number of data return from api.

I've tried creating dynamic number of labels into cell in cellForRowAtIndexPath method. But every time I scroll, all these labels overlap each other..Is there any other way to create a dynamic number of labels into a cell?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PracLabelCell", for: indexPath) as! PracLabelCell

    let w : CGFloat = CGFloat(self.tableview.frame.size.width/3)
    var x : CGFloat = 0

    for index in 0...2
    {
        let label = UILabel(frame: CGRect(x: x, y: cell.frame.origin.y, width: w , height: cell.frame.size.height))
        let str = String(index)
        print(str)
        label.text = str
        cell.contentView.addSubview(label)
        print("x is" , x)
        x += w

    }

    return cell
}

Body:
This can be achieved using a UIStackview. Here is the sample code for a view controller that has a tableview whose each row can show 1, 2 or 3 labels. The cellForRow datasource method has the logic to switch the count of lables according to the requirement.

import UIKit

class ViewController: UIViewController {

    // This array contains the sample data to populate the tableview. Each
       element dictates the number of labels to be shown in the cell
    var tableData = [1,2,3,2,3,2]
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section:
Int) -> Int {
        return tableData.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath:
IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelRow",
for: indexPath) as! LabelTableViewCell

        let labelCount = tableData[indexPath.row]

        // Check the label count for the current row to decide how many labels to show.
        // Extra lables are hidden
        switch labelCount {
        case 1:
            cell.label1.isHidden = false
            cell.label2.isHidden = true
            cell.label3.isHidden = true
        case 2:
            cell.label1.isHidden = false
            cell.label2.isHidden = false
            cell.label3.isHidden = true
        default:
            cell.label1.isHidden = false
            cell.label2.isHidden = false
            cell.label3.isHidden = false
        }

        return cell
    }
}

The LabelTableViewCell class is a subclass of UITableViewCell and it contains a UIStackView. The stack view handles the task of arranging the labels vertically. Also as one or more labels(which are added as arranged subviews of the stack view in Interface Builder) are hidden, the stack view's height gets adjusted. The trick is to have constraints between the stackview's top to the cell's content view's top and similar bottom constraints. This will ensure that when the stackview's height changes, the cell's height also changes accordingly.

I have added the project to GitHub for better understanding

Here is a screenshot of the result.


问:
Azure kubernetes deployment error - 0/1 nodes are available: 1 node(s) didn't match node selector
I am working on deploying one of my application to the Azure Kubernetes.
I have ACR and AKS configured, I am trying the deployment through azure CLI.

Here is the kubernetes deployment file content

```<code>kind: Deployment
metadata:
  name: pocaksimage1
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: pocaksimage1
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": windows
      containers:
      - name: pocaksimage1
        image: pocaksimage1
        ports:
        - containerPort: 6379
          name: pocaksimage1
---
apiVersion: v1
kind: Service
metadata:
  name: pocaksimage1
spec:
  ports:
  - port: 6379
  selector:
    app: pocaksimage1
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: pocaksimage1
spec:
  replicas: 1
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  minReadySeconds: 5
  template:
    metadata:
      labels:
        app: pocaksimage1
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": windows
      containers:
      - name: pocaksimage1
        image: repo
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 250m
          limits:
            cpu: 500m
        env:
        - name: PRE_PROD
          value: "pocaksimage1"
      imagePullSecrets:
        - name: pocsecret
---
apiVersion: v1
kind: Service
metadata:
  name: pocaksimage1-front
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: pocaksimage1-front
</code>```

The error I am getting is "0/1 nodes are available: 1 node(s) didn't match node selector."

Please help me to get this resolved.

Thanks

答:
I suppose the issue is with the fact AKS doesnt yet support windows nodes, so you dont really have windows nodes. You can create AKS with windows nodes, but its in preview at this point in time.

https://github.com/Azure/AKS/blob/master/previews.md#windows

Body:
I am working on deploying one of my application to the Azure Kubernetes.
I have ACR and AKS configured, I am trying the deployment through azure CLI.

Here is the kubernetes deployment file content

kind: Deployment
metadata:
  name: pocaksimage1
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: pocaksimage1
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": windows
      containers:
      - name: pocaksimage1
        image: pocaksimage1
        ports:
        - containerPort: 6379
          name: pocaksimage1
---
apiVersion: v1
kind: Service
metadata:
  name: pocaksimage1
spec:
  ports:
  - port: 6379
  selector:
    app: pocaksimage1
---
apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: pocaksimage1
spec:
  replicas: 1
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
  minReadySeconds: 5
  template:
    metadata:
      labels:
        app: pocaksimage1
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": windows
      containers:
      - name: pocaksimage1
        image: repo
        ports:
        - containerPort: 80
        resources:
          requests:
            cpu: 250m
          limits:
            cpu: 500m
        env:
        - name: PRE_PROD
          value: "pocaksimage1"
      imagePullSecrets:
        - name: pocsecret
---
apiVersion: v1
kind: Service
metadata:
  name: pocaksimage1-front
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: pocaksimage1-front

The error I am getting is "0/1 nodes are available: 1 node(s) didn't match node selector."

Please help me to get this resolved.

Thanks


问:
Why I'm getting java.lang.IndexOutOfBoundsException when I try to get an item of jsonArray?
In my app I have smth like attaching files to messages. These attached file are shown in RecyclerView with adapter. Each item of RV has it own btn for deleting it. The problem is when I have two items at my list and try to delete 1 item not the 2-nd I'm receiving an error. But when I try to remove 2-nd item and then 1-st everything ok. I used debugger and managed to locate problematic line but I don't know how to solve this problem. So, here is code from adapter for removing item from list:

```<code>val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   }

 }
}
</code>```

I have problem at this line:

```<code>val obj = array.get(i).asJsonObject
</code>```

I checked via logger this variable and everything seems to be ok,  I can get value with 0 index. Then I thought that problem is at the place where I send data to adapter, but everything ok. I used debugger and saw that method getAsJsonObject() throws this exception:

why does it happen and how I can solve this error. I tried to change this:
for (i in 0 until array.size()) to this for (i in 0 until array.size()-1) and it didn't work. Then I tried to change this loop to this for (i in 1 until array.size()) and it didn't help also. So, where I made mistake and how I can prevent this problem in future?

P.S. Sorry for attaching screenshot of debugger, because I couldn't get text data from it.

答:
Just add break statement inside the if condition.

```<code>val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   break;
   }

 }
}
</code>```

The reason your are getting exception after  removing first element is the loop gets executed after removing first element.
But if you had break,it wont execute next time.
The reason you are not getting exception when you try to remove second element is the loop ends exactly after removing the second element.

Body:
In my app I have smth like attaching files to messages. These attached file are shown in RecyclerView with adapter. Each item of RV has it own btn for deleting it. The problem is when I have two items at my list and try to delete 1 item not the 2-nd I'm receiving an error. But when I try to remove 2-nd item and then 1-st everything ok. I used debugger and managed to locate problematic line but I don't know how to solve this problem. So, here is code from adapter for removing item from list:

val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   }

 }
}

I have problem at this line:

val obj = array.get(i).asJsonObject

I checked via logger this variable and everything seems to be ok,  I can get value with 0 index. Then I thought that problem is at the place where I send data to adapter, but everything ok. I used debugger and saw that method getAsJsonObject() throws this exception:

why does it happen and how I can solve this error. I tried to change this:
for (i in 0 until array.size()) to this for (i in 0 until array.size()-1) and it didn't work. Then I tried to change this loop to this for (i in 1 until array.size()) and it didn't help also. So, where I made mistake and how I can prevent this problem in future?

P.S. Sorry for attaching screenshot of debugger, because I couldn't get text data from it.

Body:
Just add break statement inside the if condition.

val array = Singleton.array
if (array!!.size() > 0) {
  for (i in 0 until array.size()) {
   val obj = array.get(i).asJsonObject

   if (obj.get("filename").toString().substring(1, obj.get("filename").toString().length - 1) == mNames[position]) {
   array.remove(obj)
   mNames.removeAt(position)
   Singleton.array = array
   updateNames(mNames)
   break;
   }

 }
}

The reason your are getting exception after  removing first element is the loop gets executed after removing first element.
But if you had break,it wont execute next time.
The reason you are not getting exception when you try to remove second element is the loop ends exactly after removing the second element.


问:
Pattern matching problem with Prolog
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

```<code>prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).
</code>```

Here is the call:

```<code>prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).
</code>```

And here is the output:

```<code>┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.
</code>```

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

答:
The reason why it is returning true and then false upon backtracking is that you are leaving choicepoints in your clauses. Your applications flow will only execute one clause of prettier_print/2, but the prolog interpreter does not know that in advance, so it leaves a choicepoint and then, upon backtracking, will try to see if any of the remaining clauses of prettier_print/2 will succeed.

You can "cut" backtracking, commiting to one choice by using the cut (!):

```<code>prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    !,
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    !,
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    !,
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘'),
    !.
prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle),
    !.
</code>```

You may, as well, rewrite your solution so that you leave no choicepoints by using some other predicates instead of different clauses for prettier_print. This way you would not need to use the cut:

```<code>prettier_print(Puzzle) :-
  Puzzle \= [] ->
  (
    print_head,
    print_rows(Puzzle, NRows1),
    print_line,
    print_rows(Puzzle, NRows1),
    print_line,
    print_rows(Puzzle, NRows1),
    print_end
  ).

print_rows(Rows, NRows):-
  print_row(Rows, Rows1),
  print_row(Rows1, Rows2),
  print_row(Rows2, NRows).

print_head:-
    writeln('┌───────┬───────┬───────┐').

print_line:-
    writeln('│───────┼───────┼───────│').

print_end:-
    writeln('└───────┴───────┴───────┘').

print_row([Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | NRows], NRows) :-
    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]).
</code>```

Title: Pattern matching problem with Prolog

Body:
EDIT: See my answer below for why I am a fool. There is still a riddle in this that I would love to have answered though.

I've been stuck on this for far too long. I'm trying to print out a sudoku solution in a nice looking grid.

I think I'm running into problems because I don't understand some key part of how pattern matching works in Prolog.

Without further ado, my code:

prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘').

prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work
    % N =\= 0, N =\= 4, N =\= 8, N =\= 13,

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle).

Here is the call:

prettier_print(0, [1,2,3,4,5,6,7,8,9,
                   2,2,3,4,5,6,7,8,9,
                   3,2,3,4,5,6,7,8,9,
                   4,2,3,4,5,6,7,8,9,
                   5,2,3,4,5,6,7,8,9,
                   6,2,3,4,5,6,7,8,9,
                   7,2,3,4,5,6,7,8,9,
                   8,2,3,4,5,6,7,8,9,
                   9,2,3,4,5,6,7,8,9]).

And here is the output:

┌───────┬───────┬───────┐
│ 1 2 3 │ 4 5 6 │ 7 8 9 │
│ 2 2 3 │ 4 5 6 │ 7 8 9 │
│ 3 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 4 2 3 │ 4 5 6 │ 7 8 9 │
│ 5 2 3 │ 4 5 6 │ 7 8 9 │
│ 6 2 3 │ 4 5 6 │ 7 8 9 │
│───────┼───────┼───────│
│ 7 2 3 │ 4 5 6 │ 7 8 9 │
│ 8 2 3 │ 4 5 6 │ 7 8 9 │
│ 9 2 3 │ 4 5 6 │ 7 8 9 │
└───────┴───────┴───────┘
true ;
false.

The problem is it doesn't JUST return with true, I have to press ;, and then it returns false. This in turn means that my prettier_print/1 rule doesn't work properly.

I think I know enough to figure out that this means:

Prolog is backtracking and trying another interpretation of my rules (seeing if there is anything else it can unify with, if I'm understanding my terms correctly). This finds one other thing to unify with that, but that fails immediately. Is that right?

I want there to be only one possible interpretation. How can I fix my function to mean that?

Thank you for any help, this has me feeling like such a fool!

Body:
The reason why it is returning true and then false upon backtracking is that you are leaving choicepoints in your clauses. Your applications flow will only execute one clause of prettier_print/2, but the prolog interpreter does not know that in advance, so it leaves a choicepoint and then, upon backtracking, will try to see if any of the remaining clauses of prettier_print/2 will succeed.

You can "cut" backtracking, commiting to one choice by using the cut (!):

prettier_print([]).
prettier_print([Puzzle]) :- prettier_print(0, [Puzzle]).

prettier_print(0, Puzzle) :-
    writeln('┌───────┬───────┬───────┐'),
    !,
    prettier_print(1, Puzzle).
prettier_print(4, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    !,
    prettier_print(5, Puzzle).
prettier_print(8, Puzzle) :-
    writeln('│───────┼───────┼───────│'),
    !,
    prettier_print(9, Puzzle).
prettier_print(12, []) :-
    writeln('└───────┴───────┴───────┘'),
    !.
prettier_print(N, [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | Puzzle]) :-
    member(N, [1,2,3,5,6,7,9,10,11]),  % tried this when the line below did not work

    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]),
    succ(N, N1),
    prettier_print(N1, Puzzle),
    !.

You may, as well, rewrite your solution so that you leave no choicepoints by using some other predicates instead of different clauses for prettier_print. This way you would not need to use the cut:

prettier_print(Puzzle) :-
  Puzzle \= [] ->
  (
    print_head,
    print_rows(Puzzle, NRows1),
    print_line,
    print_rows(Puzzle, NRows1),
    print_line,
    print_rows(Puzzle, NRows1),
    print_end
  ).

print_rows(Rows, NRows):-
  print_row(Rows, Rows1),
  print_row(Rows1, Rows2),
  print_row(Rows2, NRows).

print_head:-
    writeln('┌───────┬───────┬───────┐').

print_line:-
    writeln('│───────┼───────┼───────│').

print_end:-
    writeln('└───────┴───────┴───────┘').

print_row([Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9 | NRows], NRows) :-
    format('│ ~d ~d ~d │ ~d ~d ~d │ ~d ~d ~d │~n', [Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9]).


问:
ClassNotFound exception while using the Maven Shade Plugin
I am trying to follow this link:
http://maven.apache.org/plugins/maven-shade-plugin/examples.html

I am new to Maven. I feel a bit out of depth trying to follow the example.

I am able to get Quartz Scheduler to get working with Spring. I want to be able to run it from commandline using jar file.

Here are the list of classes and pom file I used.

EDIT:

I am able to get a shade jar file. I used mvn clean install

but when I try to run it from the command line, I get the following errors.

C:\Users\SpringExample\target>java -jar SpringExample-1.0-SNA
PSHOT-shaded.jar
Exception in thread "main" java.lang.NoClassDefFoundError: org/sonatype/haven/Ex
odusCli
Caused by: java.lang.ClassNotFoundException: org.sonatype.haven.ExodusCli
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: org.sonatype.haven.ExodusCli. Program will exit.

EDIT2:

I used the following in the pom above using this link:

http://seanfreitag.wordpress.com/2011/07/25/create-an-executable-jar-with-dependencies-using-maven/

```<code> <project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>1.4</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <manifestEntries>
                    <Main-Class>org.sonatype.haven.ExodusCli</Main-Class>
                    <Build-Number>123</Build-Number>
                  </manifestEntries>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.handlers</resource>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.schemas</resource>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>
</code>```

答:
Add following snippet to your plugin. This should help.</p>

```<code> <artifactSet>
    <includes>
        <include>org.sonatype.haven.ExodusCli:*</include>
    </includes>
 </artifactSet>
</code>```

Body:
I am trying to follow this link:
http://maven.apache.org/plugins/maven-shade-plugin/examples.html

I am new to Maven. I feel a bit out of depth trying to follow the example.

I am able to get Quartz Scheduler to get working with Spring. I want to be able to run it from commandline using jar file.

Here are the list of classes and pom file I used.

EDIT:

I am able to get a shade jar file. I used mvn clean install

but when I try to run it from the command line, I get the following errors.

C:\Users\SpringExample\target>java -jar SpringExample-1.0-SNA
PSHOT-shaded.jar
Exception in thread "main" java.lang.NoClassDefFoundError: org/sonatype/haven/Ex
odusCli
Caused by: java.lang.ClassNotFoundException: org.sonatype.haven.ExodusCli
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: org.sonatype.haven.ExodusCli. Program will exit.

EDIT2:

I used the following in the pom above using this link:

http://seanfreitag.wordpress.com/2011/07/25/create-an-executable-jar-with-dependencies-using-maven/

 <project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>1.4</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <manifestEntries>
                    org.sonatype.haven.ExodusCli
                    <Build-Number>123</Build-Number>
                  </manifestEntries>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.handlers</resource>
                </transformer>
                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                  <resource>META-INF/spring.schemas</resource>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  ...
</project>

Body:
Add following snippet to your plugin. This should help.

 <artifactSet>
    <includes>
        <include>org.sonatype.haven.ExodusCli:*</include>
    </includes>
 </artifactSet>


问:
Spring boot Mongo DB .yml configuration
When I use MySQL and hibernate for spring boot, I use below configuration in  .yml file

```<code>spring:
  datasource:
    url: jdbc:mysql://localhost/userName?zeroDateTimeBehavior=convertToNull
    username: userName
    password: password
    driverClassName: com.mysql.jdbc.Driver

  jpa:
    show-sql: false
    hibernate:
      dialect: org.hibernate.dialect.MySQLDialect
      format_sql: false
      ddl-auto: update
</code>```

If it is mongoDB instead of MySQL and hibernate how does it change?

答:
You can do as below:</p>

```<code>spring:
  data:
    mongodb:
      uri: mongodb://yourusername:yourpassword@localhost:27017/yourDB
</code>```

Title: Spring boot Mongo DB .yml configuration

Body:
When I use MySQL and hibernate for spring boot, I use below configuration in  .yml file

spring:
  datasource:
    url: jdbc:mysql://localhost/userName?zeroDateTimeBehavior=convertToNull
    username: userName
    password: password
    driverClassName: com.mysql.jdbc.Driver

  jpa:
    show-sql: false
    hibernate:
      dialect: org.hibernate.dialect.MySQLDialect
      format_sql: false
      ddl-auto: update

If it is mongoDB instead of MySQL and hibernate how does it change?

Body:
You can do as below:

spring:
  data:
    mongodb:
      uri: mongodb://yourusername:yourpassword@localhost:27017/yourDB


问:
How to add value to array element withing collection using mongoose?
I have written the following mongoose function to create new document in mongodb

```<code>createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
       //,
       //notes.message: body.message
    }));
    return sEntry.save();
}
</code>```

Here sData schema includes notes array schema within it.

I am not able to add value to message within notes [] using notes.message: body.message

My schema definition is as follows:

```<code>var nSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    message: String
});

var sSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    dataId: { type:String, unique: true },
    notes: [nSchema]
}
</code>```

I also want to mention that for every dataId there can be multiple notes [] entries. However, SData can have only unique row entry for every dataId.

I want notes to be an array within SData collection. How it can be achieved without creating separate notes collection? How should i modify createdata to accommodate all the given requirements.

答:
Use references for other collection mapping and use populate when fetching

Schema Design

```<code>var sSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    dataId: { type:String, unique: true },
    notes: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'nSchema',
    }]
}
</code>```

Adding Data

```<code>createdata: (body) => {
    let sEntry = new SData({
        dataId: body.DataId,
        notes: [nSchemaIds]
    });
    return sEntry.save();
}
</code>```

Body:
I have written the following mongoose function to create new document in mongodb

createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
       //,
       //notes.message: body.message
    }));
    return sEntry.save();
}

Here sData schema includes notes array schema within it.

I am not able to add value to message within notes [] using notes.message: body.message

My schema definition is as follows:

var nSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    message: String
});

var sSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    dataId: { type:String, unique: true },
    notes: [nSchema]
}

I also want to mention that for every dataId there can be multiple notes [] entries. However, SData can have only unique row entry for every dataId.

I want notes to be an array within SData collection. How it can be achieved without creating separate notes collection? How should i modify createdata to accommodate all the given requirements.

Body:
Use references for other collection mapping and use populate when fetching

Schema Design

var sSchema = new Schema({
    _id: {type:ObjectId, auto: true },
    dataId: { type:String, unique: true },
    notes: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'nSchema',
    }]
}

Adding Data

createdata: (body) => {
    let sEntry = new SData({
        dataId: body.DataId,
        notes: [nSchemaIds]
    });
    return sEntry.save();
}


问:
SQL Insert Additional Field in Distinct Filter
I would like to insert an additional field to be used in conjunction with an existing one when retrieving records from SQL database.

Current query:

```<code>SELECT CONVERT(date, [DateTime]) 'Date of Download',
       ActionBy AS 'User Full Name',
       COUNT(DISTINCT Identifier) 'Number of Downloads'
FROM [dbo].[AuditLog]
WHERE ActionTaken = 'Clicked'
    AND Type = 'Attachment Link'
    AND CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
    AND CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
GROUP BY CONVERT(date, [DateTime]), ActionBy
HAVING COUNT(DISTINCT Identifier) > " + limit + "
ORDER BY COUNT(DISTINCT Identifier) DESC";
</code>```

I would like to insert an additional filter Remarks with the existing Identifier in the DISTINCT filter.

Example:
COUNT(DISTINCT Identifier + Remarks) 'Number of Downloads'

May I know how can I modify my current statement?

Thank you

Sample Data:

Other columns were minimised to maximise visibility.

答:
Try :</p>

```<code>SELECT CONVERT(date, [DateTime]) 'Date of Download',
       ActionBy AS 'User Full Name',
       COUNT(DISTINCT Identifier) + ' ' + COUNT(DISTINCT Remarks) 'Number of Downloads'
FROM [dbo].[AuditLog]
WHERE ActionTaken = 'Clicked'
    AND Type = 'Attachment Link'
    AND CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
    AND CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
GROUP BY CONVERT(date, [DateTime]), ActionBy
HAVING COUNT(DISTINCT Identifier) > " + limit + "
ORDER BY COUNT(DISTINCT Identifier) DESC";
</code>```

Body:
I would like to insert an additional field to be used in conjunction with an existing one when retrieving records from SQL database.

Current query:

SELECT CONVERT(date, [DateTime]) 'Date of Download',
       ActionBy AS 'User Full Name',
       COUNT(DISTINCT Identifier) 'Number of Downloads'
FROM [dbo].[AuditLog]
WHERE ActionTaken = 'Clicked'
    AND Type = 'Attachment Link'
    AND CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
    AND CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
GROUP BY CONVERT(date, [DateTime]), ActionBy
HAVING COUNT(DISTINCT Identifier) > " + limit + "
ORDER BY COUNT(DISTINCT Identifier) DESC";

I would like to insert an additional filter Remarks with the existing Identifier in the DISTINCT filter.

Example:
COUNT(DISTINCT Identifier + Remarks) 'Number of Downloads'

May I know how can I modify my current statement?

Thank you

Sample Data:

Other columns were minimised to maximise visibility.

Body:
Try :

SELECT CONVERT(date, [DateTime]) 'Date of Download',
       ActionBy AS 'User Full Name',
       COUNT(DISTINCT Identifier) + ' ' + COUNT(DISTINCT Remarks) 'Number of Downloads'
FROM [dbo].[AuditLog]
WHERE ActionTaken = 'Clicked'
    AND Type = 'Attachment Link'
    AND CONVERT(date, [DateTime]) BETWEEN CONVERT(date,'" + scanStartDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
    AND CONVERT(date,'" + scanEndDate.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')
GROUP BY CONVERT(date, [DateTime]), ActionBy
HAVING COUNT(DISTINCT Identifier) > " + limit + "
ORDER BY COUNT(DISTINCT Identifier) DESC";


问:
Azure App Service Restrictions - allow app service A for app service B
Azure app service A needs to call Azure app service B using System.Net.WebClient class.

Access to app service B is restricted to company's IP range only, through

Azure > app service > Networking > Access Restrictions

Tried adding <public ip of app service A>/32 to B's allow list but that did not work - System.Net.WebClient.DownloadData threw a 403 Forbidden exception.

What else can I try?

答:
It looks like it's impossible to restrict the Public IP address in Access Restrictions of the app service B since both app services in the same app service plan.

Azure App Service is a multi-tenant service, except for App Service Environments. Apps that are not in an App Service environment (not in the Isolated tier) share network infrastructure with other apps. If you restrict the inbound or possible outbound Public IP address of web app service, it looks like restrict the access from itself. Even this, per my understanding, it should be limit the private IP address of the instance in the web app service over the Azure backbone network. However, We could not know the private IP address of each app service.

You can use Azure service plan with isolated price tier but its high cost. So I suggest recreating the web app service A in a different service plan with a different region. Then restrict the possible outbound IP addresses in web app service A.

Additionally, you can get a further understanding of the Azure app service plan in this blog.