问:
Highcharts : remove custom legend tooltip from export
Here is the code

```<code>legend: {
    width: 500,
    itemWidth: 250,
    layout: 'horizontal',
    backgroundColor: '#FFFFFF',
    align: 'left',
    alignColumns:false,
    verticalAlign: 'top',
    margin:10,
    itemMarginLeft :2,
    x: 0,
    y:0,
    itemDistance: 2,
    symbolHeight : 10,
    symbolWidth : 10,
    itemStyle : {
        "fontFamily": "'Raleway', sans-serif !important",
        "fontSize"  : "12px !important",
    },
    title : {
        text : null
    },
    useHTML: true,
    labelFormatter: function() {
        var total = 0;
        for(var i=this.yData.length; i--;) { total += this.yData[i]; };
        if ((this.options.custom == "undefined") || (this.options.custom == undefined)) {
            return  '<span class="legend-tooltip">'+total.toLocaleString('en') + " " + this.name.toLowerCase();
        }
        else{
            var color= this.options.custom.type == '+' ? '#8ed64b' : '#ff0112';
            //return  '<span class="legend-tooltip">'+total.toLocaleString('en') + " " + this.name.toLowerCase()  + ' ' + '<span style="color: '+color+'" title="Change from previous period" >'+this.options.custom.change+"</span>";
            return '<span class="legend-tooltip">'+total.toLocaleString('en') + ' ' + this.name.toLowerCase()  + ' ' + '<span class="tooltip-item" style="color: '+color+'">'+this.options.custom.change+'<span class="tooltip-expand-box">Change from previous period</span></span></span>';
        }
    },
    itemMarginBottom :10

},

</code>```

And this is the chart

Exported chart

Issue is tooltip style is broken. no need of tooltip in the image [hover]

how to exclude tooltip in export.Tried a lot .Didn't get any solution.

This is not applicable ti labelFormatter ref

It's working for default export button with below code

```<code>    legend: {
    title : {
        text : "",
    },
    layout: 'horizontal',
    align: 'left',
    verticalAlign: 'top',
    y : 10,
    x:0,
    useHTML: true,
    labelFormatter: function() {
        var total = 0;
        for(var i=this.yData.length; i--;) { total += this.yData[i]; };
        if ((this.options.custom == "undefined") || (this.options.custom == undefined)) {
            return  '<span class="legend-tooltip">'+total.toLocaleString('en') + " " + this.name.toLowerCase();
        }
        else{
            var color= this.options.custom.type == '+' ? '#8ed64b' : '#ff0112';
            return '<span class="legend-tooltip">'+total.toLocaleString('en') + ' ' + this.name.toLowerCase()  + ' ' + '<span class="tooltip-item" style="color: '+color+'">'+this.options.custom.change+'</span></span>';
        }

    },

},
</code>```

but not for customised export button

```<code>    openMediaShareModal(option,index){
    var self = this;
    var ref = this.$refs[index];
    var chart = ref[0].chart;
    var obj = {};
    var itemURL;
    var exportUrl = 'https://export.highcharts.com/';
    obj.svg = chart.getSVG(option);
    obj.options = JSON.stringify(option);
    obj.type = 'image/png';
    obj.async = true;
    $.ajax({
        type: 'post',
        url: exportUrl,
        data: obj,
        success: function(data) {
            var itemURL = 'https://export.highcharts.com/'+data;
            self.popup_item.image_url = itemURL;
        }
    });

},
</code>```

答:
You can define a separate labelFormatter function for the exported chart:

```<code>    exporting: {
        chartOptions: {
            legend: {
                labelFormatter: function() {
                    ...
                }
            }
        }
    }
</code>```

Live demo: http://jsfiddle.net/BlackLabel/p1wovduy/1/

API Reference: https://api.highcharts.com/highcharts/exporting.chartOptions

Body:
Here is the code

legend: {
    width: 500,
    itemWidth: 250,
    layout: 'horizontal',
    backgroundColor: '#FFFFFF',
    align: 'left',
    alignColumns:false,
    verticalAlign: 'top',
    margin:10,
    itemMarginLeft :2,
    x: 0,
    y:0,
    itemDistance: 2,
    symbolHeight : 10,
    symbolWidth : 10,
    itemStyle : {
        "fontFamily": "'Raleway', sans-serif !important",
        "fontSize"  : "12px !important",
    },
    title : {
        text : null
    },
    useHTML: true,
    labelFormatter: function() {
        var total = 0;
        for(var i=this.yData.length; i--;) { total += this.yData[i]; };
        if ((this.options.custom == "undefined") || (this.options.custom == undefined)) {
            return  ''+total.toLocaleString('en') + " " + this.name.toLowerCase();
        }
        else{
            var color= this.options.custom.type == '+' ? '#8ed64b' : '#ff0112';
            //return  ''+total.toLocaleString('en') + " " + this.name.toLowerCase()  + ' ' + ''+this.options.custom.change+"";
            return ''+total.toLocaleString('en') + ' ' + this.name.toLowerCase()  + ' ' + ''+this.options.custom.change+'Change from previous period';
        }
    },
    itemMarginBottom :10

},

And this is the chart

Exported chart

Issue is tooltip style is broken. no need of tooltip in the image [hover]

how to exclude tooltip in export.Tried a lot .Didn't get any solution.

This is not applicable ti labelFormatter ref

It's working for default export button with below code

    legend: {
    title : {
        text : "",
    },
    layout: 'horizontal',
    align: 'left',
    verticalAlign: 'top',
    y : 10,
    x:0,
    useHTML: true,
    labelFormatter: function() {
        var total = 0;
        for(var i=this.yData.length; i--;) { total += this.yData[i]; };
        if ((this.options.custom == "undefined") || (this.options.custom == undefined)) {
            return  ''+total.toLocaleString('en') + " " + this.name.toLowerCase();
        }
        else{
            var color= this.options.custom.type == '+' ? '#8ed64b' : '#ff0112';
            return ''+total.toLocaleString('en') + ' ' + this.name.toLowerCase()  + ' ' + ''+this.options.custom.change+'';
        }

    },

},

but not for customised export button

    openMediaShareModal(option,index){
    var self = this;
    var ref = this.$refs[index];
    var chart = ref[0].chart;
    var obj = {};
    var itemURL;
    var exportUrl = 'https://export.highcharts.com/';
    obj.svg = chart.getSVG(option);
    obj.options = JSON.stringify(option);
    obj.type = 'image/png';
    obj.async = true;
    $.ajax({
        type: 'post',
        url: exportUrl,
        data: obj,
        success: function(data) {
            var itemURL = 'https://export.highcharts.com/'+data;
            self.popup_item.image_url = itemURL;
        }
    });

},

Body:
You can define a separate labelFormatter function for the exported chart:

    exporting: {
        chartOptions: {
            legend: {
                labelFormatter: function() {
                    ...
                }
            }
        }
    }

Live demo: http://jsfiddle.net/BlackLabel/p1wovduy/1/

API Reference: https://api.highcharts.com/highcharts/exporting.chartOptions


来源: stackexchange

问:
react js pass url boolean to component to detect, is undefined when checked
I am trying to pass a boolean thru the url for the react js component to use however it keeps coming up undefined. I tried multiple url combination and it has been a guessing game.

my route for the boolean url attribute is

```<code><Route path={"http://myurl.com/:showUserInfo"} component={myComponent}>
</code>```

in the myComponent in the render scope

```<code>const test = this.props.match.showUserInfo
</code>```

test is always undefined.

I tried the following url

```<code>http://myurl.com/:showUserInfo=false
http://myurl.com/showUserInfo=false
http://myurl.com/showUserInfo={false}
</code>```

I would like to detect the boolean flag and can I get the value?

I tried a few more but no success. any help is greatly appreciated. Thanks

答: Please use const test = this.props.match.params.showUserInfo to read from route.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to pass a boolean thru the url for the react js component to use however it keeps coming up undefined. I tried multiple url combination and it has been a guessing game.

my route for the boolean url attribute is

<Route path={"http://myurl.com/:showUserInfo"} component={myComponent}>

in the myComponent in the render scope

const test = this.props.match.showUserInfo

test is always undefined.

I tried the following url

http://myurl.com/:showUserInfo=false
http://myurl.com/showUserInfo=false
http://myurl.com/showUserInfo={false}

I would like to detect the boolean flag and can I get the value?

I tried a few more but no success. any help is greatly appreciated. Thanks


问:
Items in carousel not clickab/selectable on smart-display
I am using Dialogflow and actions on Google to talk to my smart display (Google Nest Hub). In one of my intents I show a carousel. I can browse the carousel and call the next intent correctly via voice command, however I cannot touch or click on any of the items shown in my carousel. Yet, when I test my app in Dialogflow or the Actions Console test-area, it works (I can click on items and thereby trigger the next intent). Is there something special in the payload I need to look at to make the carousel responsive to touch?

Thanks for your help

答: We have the same behaviour in our AoG. In addition the carousel works with voice and touch on a smartphone. Only on a 'real' smart display device it does not work. So far, however, we have not yet found a workaround.</p>


问:
Get html from  and attach it to img
I have HTML:

```<code><table id='ansichttable' class='table appels'>
    <thead>
        <tr>
            <th class='bold'>Afbeelding</th>
            <th class="bold">Locatie</th>
            <th class='bold'>Groep</th>
            <th class='bold'>Soort</th>
            <th class='bold'>Bijzonderheden</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a class="img" href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Dubbele Bellefleur</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
        <tr>
            <td><a class="img" href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Dubbele Zoete Aagt</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
        <tr>
            <td><a href="images/imagesfruit/boomgaard4.jpg"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
            <td valign="top">Tuin</td>
            <td valign="top">Appels</td>
            <td valign="top" class="titel">Ellisons Orange</td>
            <td valign="top">Zoete stevige appel</td>
        </tr>
    </tbody>
</table>
</code>```

What I am trying to create is that jQuery gets the title from the: td class="titel"
and create at the a href="......" a title tag like this:

```<code><td><a href="images/imagesfruit/boomgaard4.jpg" titel="Ellisons Orange"><img src="images/imagesfruit/thumbs/t-boomgaard4.jpg"/></a></td>
<td valign="top">Tuin</td>
<td valign="top">Appels</td>
<td valign="top" class="titel">Ellisons Orange</td>
<td valign="top">Zoete stevige appel</td>
</code>```

I have tried the following :

```<code>$(document).ready(function(){
 var gettitle = $("td:eq(3)").html();
                 $("td a").attr("title", $('td.titel').text());
</code>```

And:

```<code>$("td a.img").attr("title", $('.titel').html());
</code>```

And:

```<code>$('table').each(function() {
  var title = $(this).find('td.titel').text();
  $(this).find('td a').attr('title', title);
 });
</code>```

All of them are working, but collecting all the titles from the table and attach them to all the images.

What I need is that jQuery collects the title and attach it to the image above the td where it gets the title. What am I doing wrong?

答:
Is this what you are looking for?

```<code>$("td.titel").each(function(){
    $(this).html('<a href="" title="'+$(this).text()+'">'+$(this).text()+'</a>');
});
</code>```

This gets each td with the class titel and wraps a link around it with the title attribute being the text within the td.

```<code>$("td.titel").each(function(){
    $(this).parent().find('a.img').attr('title',$(this).text());
});
</code>```

EDIT: haha, give the answer to the druttka.  I was writing this when he posted.

ContentLicense: CC BY-SA 3.0

Title: Get html from <td class"title"> and attach it to img

Body:
I have HTML:

            Afbeelding
            Locatie
            Groep
            Soort
            Bijzonderheden

            Tuin
            Appels
            Dubbele Bellefleur
            Zoete stevige appel

            Tuin
            Appels
            Dubbele Zoete Aagt
            Zoete stevige appel

            Tuin
            Appels
            Ellisons Orange
            Zoete stevige appel

What I am trying to create is that jQuery gets the title from the: td class="titel"
and create at the a href="......" a title tag like this:

Tuin
Appels
Ellisons Orange
Zoete stevige appel

I have tried the following :

$(document).ready(function(){
 var gettitle = $("td:eq(3)").html();
                 $("td a").attr("title", $('td.titel').text());

And:

$("td a.img").attr("title", $('.titel').html());

And:

$('table').each(function() {
  var title = $(this).find('td.titel').text();
  $(this).find('td a').attr('title', title);
 });

All of them are working, but collecting all the titles from the table and attach them to all the images.

What I need is that jQuery collects the title and attach it to the image above the td where it gets the title. What am I doing wrong?

Body:
Is this what you are looking for?

$("td.titel").each(function(){
    $(this).html('<a href="" title="'+$(this).text()+'">'+$(this).text()+'</a>');
});

This gets each td with the class titel and wraps a link around it with the title attribute being the text within the td.

$("td.titel").each(function(){
    $(this).parent().find('a.img').attr('title',$(this).text());
});

EDIT: haha, give the answer to the druttka.  I was writing this when he posted.


问:
NativeScript-ui-autocomplete undefined property
Probably a dumb question but I'm trying to get remote data to use in nativescript-ui-autocomplete but I get the following error ERROR TypeError: Cannot set property 'loadSuggestionsAsync' of undefined

The code is very similar to the example at https://github.com/NativeScript/nativescript-ui-samples-angular/tree/master/autocomplete/app/examples/remote-data-fetch however I can't get mine to work.

TypeScript

```<code>import * as http from "tns-core-modules/http";

import { ObservableArray } from "tns-core-modules/data/observable-array";
import { TokenModel } from "nativescript-ui-autocomplete";
import { RadAutoCompleteTextViewComponent } from "nativescript-ui-autocomplete/angular";

export class MapComponent implements OnInit {

    private _items: ObservableArray<TokenModel>;
    private jsonUrl = "https://raw.githubusercontent.com/NativeScript/nativescript-ui-samples/master/examples-data/airports.json";

    mapbox: MapboxViewApi;

    constructor( private router: Router) {
        // Use the component constructor to inject providers.
    }

    ngOnInit() {
        let that = this;
        this.autocomplete.autoCompleteTextView.loadSuggestionsAsync = function (text) {
            const promise = new Promise(function (resolve, reject) {
                http.getJSON(that.jsonUrl).then(function (r: any) {
                    const airportsCollection = r.airports;
                    const items: Array<TokenModel> = new Array();
                    for (let i = 0; i < airportsCollection.length; i++) {
                        items.push(new TokenModel(airportsCollection[i].FIELD2, null));
                    }

                    resolve(items);
                }).catch((err) => {
                    const message = 'Error fetching remote data from ' + that.jsonUrl + ': ' + err.message;
                    console.log(message);
                    alert(message);
                    reject();
                });
            });

            return promise;
        };

    }

    @ViewChild("autocomplete", { static: true }) autocomplete: RadAutoCompleteTextViewComponent;

    get dataItems(): ObservableArray<TokenModel> {
        return this._items;
    }
}
</code>```

XML

```<code><RadAutoCompleteTextView #autocomplete [items]="dataItems" suggestMode="Suggest" displayMode="Plain">
                <SuggestionView tkAutoCompleteSuggestionView suggestionViewHeight="300">
                    <ng-template tkSuggestionItemTemplate let-item="item">
                        <StackLayout orientation="vertical" padding="10">
                            <Label [text]="item.text"></Label>
                        </StackLayout>
                    </ng-template>
                </SuggestionView>
            </RadAutoCompleteTextView>
</code>```

I also tried it on a blank project but same error

EDIT:
Tried reproducing in playground and it works without problems, I copy the code to my project and get the same error, tried putting everything in a try/catch and got this after the error

```<code>ERROR Error: Uncaught (in promise): Error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
JS: createAlertDialog(file: node_modules\@nativescript\core\ui\dialogs\dialogs.android.js:12:0)
JS:     at (file: node_modules\@nativescript\core\ui\dialogs\dialogs.android.js:96:0)
JS:     at ZoneAwarePromise(file: node_modules\@nativescript\angular\zone-js\dist\zone-nativescript.js:902:0)
JS:     at alert(file: node_modules\@nativescript\core\ui\dialogs\dialogs.android.js:93:0)
JS:     at push../app/map/map.component.ts.MapComponent.ngAfterViewInit(file: src\app\map\map.component.ts:61:12)
JS:     at callProviderLifecycles(file: node_modules\@angular\core\fesm5\core.js:21414:0)
JS:     at callElementProvidersLifecycles(file: node_modules\@angular\core\fesm5\core.js:21388:0)
JS:     at callLifecycleHooksChildrenFirst(file:///data/data/org.nativescript.MapboxEnduco/files/app...
</code>```

答:
Had the same issue, in my case, I had to replace

```<code> this.autocomplete.*autoCompleteTextView*.loadSuggestionsAsync = function (text) {
</code>```

with

```<code>this.autocomplete.**nativeElement**.loadSuggestionsAsync = function (text) { //etc
</code>```

Hope it will help you.

Body:
Probably a dumb question but I'm trying to get remote data to use in nativescript-ui-autocomplete but I get the following error ERROR TypeError: Cannot set property 'loadSuggestionsAsync' of undefined

The code is very similar to the example at https://github.com/NativeScript/nativescript-ui-samples-angular/tree/master/autocomplete/app/examples/remote-data-fetch however I can't get mine to work.

TypeScript

import * as http from "tns-core-modules/http";

import { ObservableArray } from "tns-core-modules/data/observable-array";
import { TokenModel } from "nativescript-ui-autocomplete";
import { RadAutoCompleteTextViewComponent } from "nativescript-ui-autocomplete/angular";

export class MapComponent implements OnInit {

    private _items: ObservableArray<TokenModel>;
    private jsonUrl = "https://raw.githubusercontent.com/NativeScript/nativescript-ui-samples/master/examples-data/airports.json";

    mapbox: MapboxViewApi;

    constructor( private router: Router) {
        // Use the component constructor to inject providers.
    }

    ngOnInit() {
        let that = this;
        this.autocomplete.autoCompleteTextView.loadSuggestionsAsync = function (text) {
            const promise = new Promise(function (resolve, reject) {
                http.getJSON(that.jsonUrl).then(function (r: any) {
                    const airportsCollection = r.airports;
                    const items: Array<TokenModel> = new Array();
                    for (let i = 0; i < airportsCollection.length; i++) {
                        items.push(new TokenModel(airportsCollection[i].FIELD2, null));
                    }

                    resolve(items);
                }).catch((err) => {
                    const message = 'Error fetching remote data from ' + that.jsonUrl + ': ' + err.message;
                    console.log(message);
                    alert(message);
                    reject();
                });
            });

            return promise;
        };

    }

    @ViewChild("autocomplete", { static: true }) autocomplete: RadAutoCompleteTextViewComponent;

    get dataItems(): ObservableArray<TokenModel> {
        return this._items;
    }
}

XML

<RadAutoCompleteTextView #autocomplete [items]="dataItems" suggestMode="Suggest" displayMode="Plain">
                <SuggestionView tkAutoCompleteSuggestionView suggestionViewHeight="300">
                    <ng-template tkSuggestionItemTemplate let-item="item">
                        <StackLayout orientation="vertical" padding="10">

                        </StackLayout>
                    </ng-template>
                </SuggestionView>
            </RadAutoCompleteTextView>

I also tried it on a blank project but same error

EDIT:
Tried reproducing in playground and it works without problems, I copy the code to my project and get the same error, tried putting everything in a try/catch and got this after the error

ERROR Error: Uncaught (in promise): Error: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
JS: createAlertDialog(file: node_modules\@nativescript\core\ui\dialogs\dialogs.android.js:12:0)
JS:     at (file: node_modules\@nativescript\core\ui\dialogs\dialogs.android.js:96:0)
JS:     at ZoneAwarePromise(file: node_modules\@nativescript\angular\zone-js\dist\zone-nativescript.js:902:0)
JS:     at alert(file: node_modules\@nativescript\core\ui\dialogs\dialogs.android.js:93:0)
JS:     at push../app/map/map.component.ts.MapComponent.ngAfterViewInit(file: src\app\map\map.component.ts:61:12)
JS:     at callProviderLifecycles(file: node_modules\@angular\core\fesm5\core.js:21414:0)
JS:     at callElementProvidersLifecycles(file: node_modules\@angular\core\fesm5\core.js:21388:0)
JS:     at callLifecycleHooksChildrenFirst(file:///data/data/org.nativescript.MapboxEnduco/files/app...

Body:
Had the same issue, in my case, I had to replace

 this.autocomplete.*autoCompleteTextView*.loadSuggestionsAsync = function (text) {

with

this.autocomplete.**nativeElement**.loadSuggestionsAsync = function (text) { //etc

Hope it will help you.


问:
If my interface must return Task what is the best way to have a no-operation implementation?
In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to run quickly and synchronously - what is the best way to return a No-Operation task from the method?

I have gone with Task.Delay(0) below, however I would like to know if this has any performance side-effects if the function is called a lot (for argument's sake, say hundreds of times a second):

Does this syntactic sugar un-wind to something big?

Does it start clogging up my application's thread pool?

Is the compiler cleaver enough to deal with Delay(0) differently?

Would return Task.Run(() => { }); be any different?

Is there a better way?

```<code>using System.Threading.Tasks;

namespace MyAsyncTest
{
    internal interface IFooFace
    {
        Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
    }

    /// <summary>
    /// An implementation, that unlike most cases, will not have a long-running
    /// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
    /// </summary>
    internal class LazyBar : IFooFace
    {
        #region IFooFace Members

        public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
        {
            // First, do something really quick
            var x = 1;

            // Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
            // Is it a real no-op, or if I call this a lot, will it adversely affect the
            // underlying thread-pool? Better way?
            return Task.Delay(0);

            // Any different?
            // return Task.Run(() => { });

            // If my task returned something, I would do:
            // return Task.FromResult<int>(12345);
        }

        #endregion
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Test();
        }

        private static async void Test()
        {
            IFooFace foo = FactoryCreate();
            await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
            return;
        }

        private static IFooFace FactoryCreate()
        {
            return new LazyBar();
        }
    }
}
</code>```

答:
```<code>return await Task.FromResult(new MyClass());
</code>```

Body:
In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to run quickly and synchronously - what is the best way to return a No-Operation task from the method?

I have gone with Task.Delay(0) below, however I would like to know if this has any performance side-effects if the function is called a lot (for argument's sake, say hundreds of times a second):

Does this syntactic sugar un-wind to something big?

Does it start clogging up my application's thread pool?

Is the compiler cleaver enough to deal with Delay(0) differently?

Would return Task.Run(() => { }); be any different?

Is there a better way?

using System.Threading.Tasks;

namespace MyAsyncTest
{
    internal interface IFooFace
    {
        Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
    }

    ///
    /// An implementation, that unlike most cases, will not have a long-running
    /// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
    ///
    internal class LazyBar : IFooFace
    {
        #region IFooFace Members

        public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
        {
            // First, do something really quick
            var x = 1;

            // Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
            // Is it a real no-op, or if I call this a lot, will it adversely affect the
            // underlying thread-pool? Better way?
            return Task.Delay(0);

            // Any different?
            // return Task.Run(() => { });

            // If my task returned something, I would do:
            // return Task.FromResult<int>(12345);
        }

        #endregion
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Test();
        }

        private static async void Test()
        {
            IFooFace foo = FactoryCreate();
            await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
            return;
        }

        private static IFooFace FactoryCreate()
        {
            return new LazyBar();
        }
    }
}


问:
Powershell - How to split a string based on characters?
I have a list of pdf filenames that need to be parsed and ultimately sent to a sql table, with the parse out pieces each in their own column.  How would I split based on a dash '-' and ultimately get it into a table.

What cmdlets would you start with to split on a character?  I need to split based on the dash '-'.

Thanks for the help.

Example File Names:

tester-2458-full_contact_snapshot-20200115_1188.pdf

tester-2458-limited_contact_snapshot-20200119_9330.pdf

Desired Results:

答: Use $variable.split('-') which will return a string array with a length equal to however many elements are produced by the split operation.</p>


问:
Use matplotlib.ticker.Locator to put ticks only if location is divisible by a given value
For example I need to set a tick only if dividing by 9 gives a "nice" value (nice here has the same meaning as in https://matplotlib.org/3.2.1/api/ticker_api.html).

Accordingly any set of following ticks should be allowed.

[9, 18, 27] allowed b/c dividing by 9 gives [1, 2, 3]

[27, 54, 81, 108] allowed b/c dividing by 9 gives [3, 6, 9, 12]

[0.45, 0.9, 1.35] allowed b/c dividing by 9 gives [0.05, 0.1, 0.15]

Note that I am not looking to set ticks at every multiple of 9, so MultipleLocator doesn't work here.

I also want the locator to automatically figure out "how many ticks" and "best tick interval" etc. Basically I need the functionality of MaxNLocator with my additional divisibility requirement.

Current best solution is MaxNLocator with the arguments MaxNLocator('auto', steps=[9]). But MaxNLocator explicitly adds 10 to the steps argument (see https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/ticker.py#L2058) so sometimes I get tick values like [1000, 2000, 3000] which aren't acceptable. (1000 is not a multiple of 9, see the example 1,2,3 below)

Any suggestions?

UPDATE: See below for some nice vs. not nice examples.

import matplotlib.pyplot as plt
import numpy as np

def draw(name, xmax, steps, verdict):
    x = np.linspace(0, xmax)
    plt.plot(x, np.sin(x))
    plt.gca().set_xlim([0, xmax])
    plt.gca().xaxis.set_major_locator(plt.MaxNLocator('auto', steps=steps))

    vd = 'NICE!!!\n' if verdict else 'NOT nice!\n'
    print(name, plt.gca().get_xticks()/9, '>>', vd)

draw('example 1', 64, [9], True)
draw('example 2', 7.2, [9], True)
draw('example 3', 90000, [9], False)
draw('example 4', 9, [1, 3, 9], False)
draw('example 5', 90, [1.8, 4.5, 9], False)
```

<p>Output:</p>

```example 1 [0. 1. 2. 3. 4. 5. 6. 7. 8.] >> NICE!!!

example 2 [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8] >> NICE!!!

example 3 [0. 1111.11111111  2222.22222222  3333.33333333
  4444.44444444  5555.55555556  6666.66666667  7777.77777778
  8888.88888889 10000.] >> NOT nice!

example 4 [0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
 0.66666667 0.77777778 0.88888889 1.] >> NOT nice!

example 5 [ 0.  1.11111111  2.22222222  3.33333333  4.44444444  5.55555556
  6.66666667  7.77777778  8.88888889 10.] >> NOT nice!
```

答:
You can provide a steps= argument to MaxNLocator. These steps need to be between 1 and 10. In your case you could put there the values you like to be used as multiplicator. For example [1.8, 4.5, 9].

```<code>from matplotlib.ticker import MaxNLocator
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 999)
y = np.sin(x/100)
plt.plot(x, y)
plt.gca().xaxis.set_major_locator(MaxNLocator(steps=[1.8, 4.5, 9]))
plt.gca().yaxis.set_major_locator(MaxNLocator(steps=[1.8, 4.5, 9]))
plt.show()
</code>```

Body:
For example I need to set a tick only if dividing by 9 gives a "nice" value (nice here has the same meaning as in https://matplotlib.org/3.2.1/api/ticker_api.html).

Accordingly any set of following ticks should be allowed.

[9, 18, 27] allowed b/c dividing by 9 gives [1, 2, 3]

[27, 54, 81, 108] allowed b/c dividing by 9 gives [3, 6, 9, 12]

[0.45, 0.9, 1.35] allowed b/c dividing by 9 gives [0.05, 0.1, 0.15]

Note that I am not looking to set ticks at every multiple of 9, so MultipleLocator doesn't work here.

I also want the locator to automatically figure out "how many ticks" and "best tick interval" etc. Basically I need the functionality of MaxNLocator with my additional divisibility requirement.

Current best solution is MaxNLocator with the arguments MaxNLocator('auto', steps=[9]). But MaxNLocator explicitly adds 10 to the steps argument (see https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/ticker.py#L2058) so sometimes I get tick values like [1000, 2000, 3000] which aren't acceptable. (1000 is not a multiple of 9, see the example 1,2,3 below)

Any suggestions?

UPDATE: See below for some nice vs. not nice examples.

import matplotlib.pyplot as plt
import numpy as np

def draw(name, xmax, steps, verdict):
    x = np.linspace(0, xmax)
    plt.plot(x, np.sin(x))
    plt.gca().set_xlim([0, xmax])
    plt.gca().xaxis.set_major_locator(plt.MaxNLocator('auto', steps=steps))

    vd = 'NICE!!!\n' if verdict else 'NOT nice!\n'
    print(name, plt.gca().get_xticks()/9, '>>', vd)

draw('example 1', 64, [9], True)
draw('example 2', 7.2, [9], True)
draw('example 3', 90000, [9], False)
draw('example 4', 9, [1, 3, 9], False)
draw('example 5', 90, [1.8, 4.5, 9], False)

Output:

example 1 [0. 1. 2. 3. 4. 5. 6. 7. 8.] >> NICE!!!

example 2 [0.  0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8] >> NICE!!!

example 3 [0. 1111.11111111  2222.22222222  3333.33333333
  4444.44444444  5555.55555556  6666.66666667  7777.77777778
  8888.88888889 10000.] >> NOT nice!

example 4 [0. 0.11111111 0.22222222 0.33333333 0.44444444 0.55555556
 0.66666667 0.77777778 0.88888889 1.] >> NOT nice!

example 5 [ 0.  1.11111111  2.22222222  3.33333333  4.44444444  5.55555556
  6.66666667  7.77777778  8.88888889 10.] >> NOT nice!

Body:
You can provide a steps= argument to MaxNLocator. These steps need to be between 1 and 10. In your case you could put there the values you like to be used as multiplicator. For example [1.8, 4.5, 9].

from matplotlib.ticker import MaxNLocator
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 999)
y = np.sin(x/100)
plt.plot(x, y)
plt.gca().xaxis.set_major_locator(MaxNLocator(steps=[1.8, 4.5, 9]))
plt.gca().yaxis.set_major_locator(MaxNLocator(steps=[1.8, 4.5, 9]))
plt.show()


问:
Calling the variable property directly vs getter/setters - OOP Design
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

```<code>class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();
</code>```

Suggested Optimization:

```<code>$rover = new dog();
$rover->name = 'rover';
echo $rover->name;
</code>```

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

答:
A boilerplate answer, I'm afraid but I would suggest the following:
If you have no encapsulation problems for your class (enforcing business logic, etc.) by exposing this property to other users, it is perfectly ok to do so.</p>

Body:
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Suggested Optimization:

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?


问:
In python - How can I plot 2D figure (x,y) and add 3rd axis by variation of the colour for each (x,y)-coordinate?
I want to add a 3rd axis data by adding a colour for each point on my 2D-plot.

I have measured the electric potential in an area, the X,Y is the lattitude and the longtitude. so each point on the 2D plot is a coordinate. Now I want to make each point a colour corresponding to the electrical potential measured (the z data). If the values are near each other they should be almost the same colour and a different if they are far apart.

I plotted it as 2D like this:

```<code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl

pl.plot(x,y, '*')
pl.xlabel('Latitude')
pl.ylabel('Longitude')
</code>```

And then I tried to make a contourplot, with the data from the z-axis, but the plot turns out weird. If I try to plot the z-data directly, it gives an error saying "TypeError: Input z must be a 2D array.".

```<code>x = lat
y = lon
z = EP

X, Y = np.meshgrid(x, y)
print (X.shape, Y.shape)
# (2, 7) (2, 7) Both have same shape
#Z = z.reshape(X.shape) # Use either X or Y to define shape
Z=np.tile(z,(211,1))
print(Z.shape)
#print(z)

fig = plt.figure()
ax1 = plt.contour(X,Y,Z)
plt.colorbar(ax1)
plt.show()
</code>```

I would like the plot to look a bit like this, where the dots have different colours depending on their value. Our x,y and z arrays are all arrays of one column and 211 rows, so they have the same size.

答:
You could try using pl.scatter

```<code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl

graph = pl.scatter(x, y, c=z)

pl.xlabel('Latitude')
pl.ylabel('Longitude')
pl.colorbar(graph)
</code>```

Body:
I want to add a 3rd axis data by adding a colour for each point on my 2D-plot.

I have measured the electric potential in an area, the X,Y is the lattitude and the longtitude. so each point on the 2D plot is a coordinate. Now I want to make each point a colour corresponding to the electrical potential measured (the z data). If the values are near each other they should be almost the same colour and a different if they are far apart.

I plotted it as 2D like this:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl

pl.plot(x,y, '*')
pl.xlabel('Latitude')
pl.ylabel('Longitude')

And then I tried to make a contourplot, with the data from the z-axis, but the plot turns out weird. If I try to plot the z-data directly, it gives an error saying "TypeError: Input z must be a 2D array.".

x = lat
y = lon
z = EP

X, Y = np.meshgrid(x, y)
print (X.shape, Y.shape)
# (2, 7) (2, 7) Both have same shape
#Z = z.reshape(X.shape) # Use either X or Y to define shape
Z=np.tile(z,(211,1))
print(Z.shape)
#print(z)

fig = plt.figure()
ax1 = plt.contour(X,Y,Z)
plt.colorbar(ax1)
plt.show()

I would like the plot to look a bit like this, where the dots have different colours depending on their value. Our x,y and z arrays are all arrays of one column and 211 rows, so they have the same size.

Body:
You could try using pl.scatter

%matplotlib inline
import numpy as np
import matplotlib.pyplot as pl

graph = pl.scatter(x, y, c=z)

pl.xlabel('Latitude')
pl.ylabel('Longitude')
pl.colorbar(graph)


问:
How to comprehend that the type of `std::function` depends solely on its call signature?
As per the documentation(http://www.cplusplus.com/reference/functional/function/), which says that:

Class that can wrap any kind of callable element (such as functions
  and function objects) into a copyable object, and whose type depends
  solely on its call signature (and not on the callable element type
  itself).

How to comprehend that the type of std::function depends solely on its call signature(and not on the callable element type itself)? Could somebody make it clear by giving some simple examples?I would be greatful to have some help with this question.

答:
If we forget all gory details, then the important method of std::function is operator().

Consider you write a wrapper for callables with signature double (int,int), then the wrapper will be something similar to:

```<code>struct example_wrapper {
     double operator()(int a,int b) { return 42; }
};
</code>```

The details I left out is what enables you to make std::function wrap any kind of callable. If the callables have the same signature, then the wrapper can have the exact same public interface (ie it is the same type). If the callables have different signature, the wrapper needs a different public interface (ie it is a different type).

Body:
If we forget all gory details, then the important method of std::function is operator().

Consider you write a wrapper for callables with signature double (int,int), then the wrapper will be something similar to:

struct example_wrapper {
     double operator()(int a,int b) { return 42; }
};

The details I left out is what enables you to make std::function wrap any kind of callable. If the callables have the same signature, then the wrapper can have the exact same public interface (ie it is the same type). If the callables have different signature, the wrapper needs a different public interface (ie it is a different type).


答:
fscanf using scansets might work.

```<code>#include <stdio.h>
#include <stdlib.h>

int main ( void) {
    char *filename = "tempm.txt";
    char date[30] = "";
    char humidity[30] = "";
    FILE *fp = NULL;
    if ( NULL == ( fp = fopen ( filename, "r"))) {
        perror ( filename);
        exit ( EXIT_FAILURE);
    }
    fscanf ( fp, "%*[^0123456789]");//scan and discard up to first digit
    while ( 1 == fscanf ( fp, "%29[^\"]", date)) {//scan up to a quote
        fscanf ( fp, "%*[^0123456789]");//scan and discard up to next digit
        if ( 1 == fscanf ( fp, "%29[^\"]", humidity)) {//scan up to a quote
            printf ( "%s\n%s\n", date, humidity);
        }
        fscanf ( fp, "%*[^0123456789]");//scan and discard up to next digit
    }
    fclose ( fp);
    return 0;
}
</code>```

Title: How can i use strtok?

Body:
{"2014-02-13T06:20:00": "3.0", "2014-02-13T13:50:00": "7.0", "2014-02-13T06:00:00": "2", "2014-02-13T03:00:00": "3", "2014-02-13T13:00:00": "6", "2014-02-13T18:50:00": "4.0", "2014-02-13T13:20:00": "6.0", "2014-02-13T15:00:00": "6", "2014-02-13T08:50:00": "4.0", "2014-02-13T21:50:00": "4.0", "2014-02-13T08:00:00": "3", "2014-02-13T07:50:00": "3.0", "2014-02-13T08:20:00": "4.0", "2014-02-13T21:20:00": "3.0", "2014-02-13T11:50:00": "6.0", "2014-02-13T11:20:00": "6.0", "2014-02-13T17:50:00": "5.0", "2014-02-13T11:00:00": "6", "2014-02-13T05:50:00": "2.0", "2014-02-13T20:50:00": "3.0", "2014-02-13T20:20:00": "4.0", "2014-02-13T16:00:00": "6", "2014-02-13T23:50:00": "2.0", "2014-02-13T21:00:00": "3", "2014-02-13T07:20:00": "3.0", "2014-02-13T03:20:00": "3.0", "2014-02-13T07:00:00": "3", "2014-02-13T15:50:00": "6.0", "2014-02-13T03:50:00": "2.0", "2014-02-13T04:00:00": "2", "2014-02-13T12:00:00": "6", "2014-02-13T04:20:00": "2.0", "2014-02-13T12:20:00": "6.0", "2014-02-13T12:50:00": "6.0", "2014-02-13T22:50:00": "3.0", "2014-02-13T09:00:00": "4", "2014-02-13T09:20:00": "4.0", "2014-02-13T09:50:00": "4.0", "2014-02-13T18:00:00": "5", "2014-02-13T05:20:00": "2.0", "2014-02-13T15:20:00": "6.0", "2014-02-13T00:50:00": "4.0", "2014-02-13T14:50:00": "7.0", "2014-02-13T00:00:00": "4", "2014-02-13T00:20:00": "4.0", "2014-02-13T06:50:00": "3.0", "2014-02-13T22:00:00": "4", "2014-02-13T18:20:00": "5.0", "2014-02-13T02:50:00": "3.0", "2014-02-13T02:20:00": "3.0", "2014-02-13T04:50:00": "2.0", "2014-02-13T02:00:00": "3", "2014-02-13T23:00:00": "3", "2014-02-13T16:50:00": "5.0", "2014-02-13T19:50:00": "4.0", "2014-02-13T19:20:00": "4.0", "2014-02-13T05:00:00": "2", "2014-02-13T19:00:00": "4", "2014-02-13T23:20:00": "3.0", "2014-02-13T14:20:00": "7.0", "2014-02-13T10:20:00": "5.0", "2014-02-13T10:00:00": "4", "2014-02-13T10:50:00": "5.0", "2014-02-13T17:00:00": "5", "2014-02-13T01:00:00": "4", "2014-02-13T17:20:00": "5.0", "2014-02-13T01:20:00": "4.0", "2014-02-13T01:50:00": "4.0", "2014-02-13T22:20:00": "3.0", "2014-02-13T16:20:00 :"6.0"}

I have this text, which represent (for example):
date -> 2014-02-13T06:20:00
humid rate -> 4.0

At first, I want to have as an output date \n humid rate \n date \n humid rate etc. etc.. I've tried to use strtok, but i couldn't do much.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINESIZE 128

int main()
{
    FILE *fp = fopen("tempm.txt", "r");
    char line[LINESIZE];
    char *value;

    while(fgets(line, sizeof(line), fp))
    {
        value = strtok(line, "\" \":");
        printf("\n%s", value);
    }

    return 0;
}

This is the code I've written so far.

Body:
fscanf using scansets might work.

#include <stdio.h>
#include <stdlib.h>

int main ( void) {
    char *filename = "tempm.txt";
    char date[30] = "";
    char humidity[30] = "";
    FILE *fp = NULL;
    if ( NULL == ( fp = fopen ( filename, "r"))) {
        perror ( filename);
        exit ( EXIT_FAILURE);
    }
    fscanf ( fp, "%*[^0123456789]");//scan and discard up to first digit
    while ( 1 == fscanf ( fp, "%29[^\"]", date)) {//scan up to a quote
        fscanf ( fp, "%*[^0123456789]");//scan and discard up to next digit
        if ( 1 == fscanf ( fp, "%29[^\"]", humidity)) {//scan up to a quote
            printf ( "%s\n%s\n", date, humidity);
        }
        fscanf ( fp, "%*[^0123456789]");//scan and discard up to next digit
    }
    fclose ( fp);
    return 0;
}


问:
How to run code based on UIPickerview selections?
I'm making a simple iOS application similar to google docs or other text editor. I created a UIPickerview to change the font size but then I realized that when I chose something, nothing happens. So is there any way I can do this here is my code

```<code>import UIKit

class FirstViewController: UIViewController, UIPopoverPresentationControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var fontBTN: UIButton!
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return arrayFruits.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return arrayFruits[row]
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    }
    var arrayFruits = [String]()
    @IBOutlet weak var picker: UIPickerView!
    @IBOutlet weak var aligners: UISegmentedControl!

    @IBOutlet weak var foramtters: UISegmentedControl!
    @IBOutlet weak var textView: UITextView!

    var pickerData = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.picker.delegate = self
        self.picker.dataSource = self
        arrayFruits = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]
    }

    @IBAction func aligning(_ sender: Any) {
        switch aligners.selectedSegmentIndex {
        case 0:
            textView.textAlignment = .left
        case 1:
            textView.textAlignment = .center
        case 2:
            textView.textAlignment = .right
        case 3:
            textView.textAlignment = .justified
        default: break

        }
    }

    @IBAction func formating(_ sender: Any) {
        switch foramtters.selectedSegmentIndex {
        case 0:
            textView.font = UIFont.boldSystemFont(ofSize: 14)
        case 1:
            textView.attributedText = NSAttributedString(string: textView.text, attributes:
                [.underlineStyle: NSUnderlineStyle.single.rawValue])
            textView.font = UIFont(name: "Arial", size: 14)
        case 2:
            textView.font = UIFont.italicSystemFont(ofSize: 14)
        default: break

        }

    }

    @IBAction func fontPicker(_ sender: Any) {
        if picker.isHidden == true {
            picker.isHidden = false
            fontBTN.setTitle("Done", for: .normal)
        } else if picker.isHidden == false {
            fontBTN.setTitle("Aa", for: .normal)
            picker.isHidden = true

        }
    }

}
</code>```

I have tried doing a Switch statement, but I get an error saying "Expression pattern of type 'Int' cannot match values of type 'UIPickerView?'" I tried googling this up but nothing showed up so I asked this question.

```<code>switch picker {
        case 0:
            //funtion here
        default:

        }
</code>```

Can you please help me?

答:
To change font size of your textView based on picker selection you need to do something like this.</p>

```<code>func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      if let doubleValue = Double(arrayFruits[row]) {
          let fontSize = CGFloat(doubleValue)
          textView.font = UIFont.systemFont(ofSize: fontSize)
      }
}
</code>```

Body:
I'm making a simple iOS application similar to google docs or other text editor. I created a UIPickerview to change the font size but then I realized that when I chose something, nothing happens. So is there any way I can do this here is my code

import UIKit

class FirstViewController: UIViewController, UIPopoverPresentationControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var fontBTN: UIButton!
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return arrayFruits.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return arrayFruits[row]
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    }
    var arrayFruits = [String]()
    @IBOutlet weak var picker: UIPickerView!
    @IBOutlet weak var aligners: UISegmentedControl!

    @IBOutlet weak var foramtters: UISegmentedControl!
    @IBOutlet weak var textView: UITextView!

    var pickerData = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.picker.delegate = self
        self.picker.dataSource = self
        arrayFruits = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]
    }

    @IBAction func aligning(_ sender: Any) {
        switch aligners.selectedSegmentIndex {
        case 0:
            textView.textAlignment = .left
        case 1:
            textView.textAlignment = .center
        case 2:
            textView.textAlignment = .right
        case 3:
            textView.textAlignment = .justified
        default: break

        }
    }

    @IBAction func formating(_ sender: Any) {
        switch foramtters.selectedSegmentIndex {
        case 0:
            textView.font = UIFont.boldSystemFont(ofSize: 14)
        case 1:
            textView.attributedText = NSAttributedString(string: textView.text, attributes:
                [.underlineStyle: NSUnderlineStyle.single.rawValue])
            textView.font = UIFont(name: "Arial", size: 14)
        case 2:
            textView.font = UIFont.italicSystemFont(ofSize: 14)
        default: break

        }

    }

    @IBAction func fontPicker(_ sender: Any) {
        if picker.isHidden == true {
            picker.isHidden = false
            fontBTN.setTitle("Done", for: .normal)
        } else if picker.isHidden == false {
            fontBTN.setTitle("Aa", for: .normal)
            picker.isHidden = true

        }
    }

}

I have tried doing a Switch statement, but I get an error saying "Expression pattern of type 'Int' cannot match values of type 'UIPickerView?'" I tried googling this up but nothing showed up so I asked this question.

switch picker {
        case 0:
            //funtion here
        default:

        }

Can you please help me?

Body:
To change font size of your textView based on picker selection you need to do something like this.

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
      if let doubleValue = Double(arrayFruits[row]) {
          let fontSize = CGFloat(doubleValue)
          textView.font = UIFont.systemFont(ofSize: fontSize)
      }
}


问:
Understanding "randomness"
I can't get my head around this, which is more random?

```<code>rand()
</code>```

OR:

```<code>rand() * rand()
</code>```

I´m finding it a real brain teaser, could you help me out?

EDIT:

Intuitively I know that the mathematical answer will be that they are equally random, but I can't help but think that if you "run the random number algorithm" twice when you multiply the two together you'll create something more random than just doing it once.

答:
OK, so I will try to add some value to complement others answers by saying that you are creating and using a random number generator.

Random number generators are devices (in a very general sense) that have multiple characteristics which can be modified to fit a purpose. Some of them (from me) are:

Entropy: as in Shannon Entropy

Distribution: statistical distribution (poisson, normal, etc.)

Type: what is the source of the numbers (algorithm, natural event, combination of, etc.) and algorithm applied.

Efficiency: rapidity or complexity of execution.

Patterns: periodicity, sequences, runs, etc.

and probably more...

In most answers here, distribution is the main point of interest, but by mix and matching functions and parameters, you create new ways of generating random numbers which will have different characteristics for some of which the evaluation may not be obvious at first glance.

Title: Understanding "randomness"

Body:
I can't get my head around this, which is more random?

rand()

OR:

rand() * rand()

I´m finding it a real brain teaser, could you help me out?

EDIT:

Intuitively I know that the mathematical answer will be that they are equally random, but I can't help but think that if you "run the random number algorithm" twice when you multiply the two together you'll create something more random than just doing it once.


答:
This means simply that the type of the callable stored in std::function does not impact the type of std::function itself, only the function signature does.

This can for example be implemented as such non-optimized:

```<code>template<class F, class Ret, class... Args>
Ret invoke_functor(void* func, Args&& ...args)
{
    return (*reinterpret_cast<F*>(f))(std::forward<Args>(args)...);
}

template<class Ret, class... Args>
Ret invoke_function(void* func, Args&& ...args)
{
    return reinterpret_cast<Ret(*)(Args...)>(func)(std::forward<Args>(args...);
}

template<class Ret, class... Args> //wrong but close enough
class function
{
public:
    template<class Functor>
    function(Functor&& f) :
        m_func(new Functor(f)), //leak
        m_invoke(&invoke_functor<Functor, Ret, Args...>)
    { }

    function(Ret(*ptr)(Args...)) :
         m_func(ptr),
         m_invoke(&invoke_function<Ret, Args...>)
    { }

     Ret
     operator()(const Args& ...args)
     {
          return m_invoke(m_func, args);
     }

private:
    void* m_func;
    Ret(*m_invoke)(void*, Args...);
}
</code>```

Here std::function can be created from both functions and callable structures as shown by the other answers.

Title: How to comprehend that the type of `std::function` depends solely on its call signature?

Body:
As per the documentation(http://www.cplusplus.com/reference/functional/function/), which says that:

Class that can wrap any kind of callable element (such as functions
  and function objects) into a copyable object, and whose type depends
  solely on its call signature (and not on the callable element type
  itself).

How to comprehend that the type of std::function depends solely on its call signature(and not on the callable element type itself)? Could somebody make it clear by giving some simple examples?I would be greatful to have some help with this question.

Body:
This means simply that the type of the callable stored in std::function does not impact the type of std::function itself, only the function signature does.

This can for example be implemented as such non-optimized:

template<class F, class Ret, class... Args>
Ret invoke_functor(void* func, Args&& ...args)
{
    return (*reinterpret_cast<F*>(f))(std::forward<Args>(args)...);
}

template<class Ret, class... Args>
Ret invoke_function(void* func, Args&& ...args)
{
    return reinterpret_cast<Ret(*)(Args...)>(func)(std::forward<Args>(args...);
}

template<class Ret, class... Args> //wrong but close enough
class function
{
public:
    template<class Functor>
    function(Functor&& f) :
        m_func(new Functor(f)), //leak
        m_invoke(&invoke_functor<Functor, Ret, Args...>)
    { }

    function(Ret(*ptr)(Args...)) :
         m_func(ptr),
         m_invoke(&invoke_function<Ret, Args...>)
    { }

     Ret
     operator()(const Args& ...args)
     {
          return m_invoke(m_func, args);
     }

private:
    void* m_func;
    Ret(*m_invoke)(void*, Args...);
}

Here std::function can be created from both functions and callable structures as shown by the other answers.


问:
Can I copy data from one table to another in SQLite using a join condition?
I'm trying to copy data from one SQLite table into another using matching data in a different set column across both tables. The second table has spaces and capital letters in the column names.

```<code>INSERT INTO table1(column1)
SELECT "Column 2"
FROM table2
INNER JOIN table2
ON table1.column3 = table2."Column 4";
</code>```

Column 3 from Table 1 and Column 4 from Table 2 should match so that the data that is selected and copied from Table 2 into Table 1 is in the right row. I am getting an error message with the code above that says ambigious column name: Column 2. Any advice on how to move this data over while ensuring that the data from Table 2 goes into the correct rows of Table 1?

Sample data:

table1

column1 (animal): Null, Null

column3 (id): ID 1, ID 3

table2

Column 2 (Animal Type): Cat, Dog, Bird

Column 4 (ID number): ID 1, ID 2, ID 3

Desired results:

table1

column1 (animal): Cat, Bird

column3 (id): ID 1, ID 3

table2

No change

Thank you!

答:
What you want is to UPDATE the table table1:

```<code>UPDATE table1
SET animal = (SELECT t2."Animal Type" FROM table2 t2 WHERE t2."ID number" = table1.ID);
</code>```

See the demo.

Results:

```<code>| animal | ID  |
| ------ | --- |
| Cat    | 1   |
| Bird   | 3   |
</code>```

Body:
I'm trying to copy data from one SQLite table into another using matching data in a different set column across both tables. The second table has spaces and capital letters in the column names.

INSERT INTO table1(column1)
SELECT "Column 2"
FROM table2
INNER JOIN table2
ON table1.column3 = table2."Column 4";

Column 3 from Table 1 and Column 4 from Table 2 should match so that the data that is selected and copied from Table 2 into Table 1 is in the right row. I am getting an error message with the code above that says ambigious column name: Column 2. Any advice on how to move this data over while ensuring that the data from Table 2 goes into the correct rows of Table 1?

Sample data:

table1

column1 (animal): Null, Null

column3 (id): ID 1, ID 3

table2

Column 2 (Animal Type): Cat, Dog, Bird

Column 4 (ID number): ID 1, ID 2, ID 3

Desired results:

table1

column1 (animal): Cat, Bird

column3 (id): ID 1, ID 3

table2

No change

Thank you!

Body:
What you want is to UPDATE the table table1:

UPDATE table1
SET animal = (SELECT t2."Animal Type" FROM table2 t2 WHERE t2."ID number" = table1.ID);

See the demo.

Results:

| animal | ID  |
| ------ | --- |
| Cat    | 1   |
| Bird   | 3   |


问:
I want to know why my 'login logic' always false condition?
I want to know why when I make the syntax for the login logic but the password and ID are always wrong? did I do something wrong to my code?
Here's the code

```<code>public class tester {
    public static void main (String[] args){
        Data baru = new Data();

        baru.id.add("HelloGays");
        baru.password.add("hi");
        System.out.println(baru.id.toString());
        System.out.println(baru.password.toString());
        GetCredentials login = new GetCredentials(baru.id,baru.password);
    }
}
</code>```

I initialized the id and password variables as above, then

```<code>public class Data {
    public ArrayList<String> id = new ArrayList<>();
    public ArrayList<String> password = new ArrayList<>();

}
</code>```

that's class for the data collection that i initialized in class Tester

```<code>public class GetCredentials {

    public GetCredentials(ArrayList id, ArrayList password){
        Scanner input = new Scanner(System.in);

        String akses,akses2;
        boolean buffer2=false,kontol=false;
        id = new ArrayList<>();

        System.out.print("Input your ID         :");
        akses = input.nextLine();
        boolean buffer = id.contains(akses);

        password = new ArrayList<>();

        System.out.print("Enter your password   :");

        akses2 = input.nextLine();
        try{
        buffer2 = (password.get(id.indexOf(akses)).equals(akses2));
        }catch(ArrayIndexOutOfBoundsException e){
            kontol = true;
        }
        if (buffer2==true){
            System.out.println("Succsessful Login");}
        else{
            kontol=true;}

        if (kontol){
            System.err.println("Wrong ID/Password");
        }

        input.close();
    }
}
</code>```

and above is the syntax for checking login credentials

答:
It's because id and password collections are empty.

```<code>id = new ArrayList<>();
password = new ArrayList<>();
</code>```

These instructions will create new empty collections, so when you try to obtain the password for a user, it will always fail, because there is no single user or password in those collections.

Body:
I want to know why when I make the syntax for the login logic but the password and ID are always wrong? did I do something wrong to my code?
Here's the code

public class tester {
    public static void main (String[] args){
        Data baru = new Data();

        baru.id.add("HelloGays");
        baru.password.add("hi");
        System.out.println(baru.id.toString());
        System.out.println(baru.password.toString());
        GetCredentials login = new GetCredentials(baru.id,baru.password);
    }
}

I initialized the id and password variables as above, then

public class Data {
    public ArrayList<String> id = new ArrayList<>();
    public ArrayList<String> password = new ArrayList<>();

}

that's class for the data collection that i initialized in class Tester

public class GetCredentials {

    public GetCredentials(ArrayList id, ArrayList password){
        Scanner input = new Scanner(System.in);

        String akses,akses2;
        boolean buffer2=false,kontol=false;
        id = new ArrayList<>();

        System.out.print("Input your ID         :");
        akses = input.nextLine();
        boolean buffer = id.contains(akses);

        password = new ArrayList<>();

        System.out.print("Enter your password   :");

        akses2 = input.nextLine();
        try{
        buffer2 = (password.get(id.indexOf(akses)).equals(akses2));
        }catch(ArrayIndexOutOfBoundsException e){
            kontol = true;
        }
        if (buffer2==true){
            System.out.println("Succsessful Login");}
        else{
            kontol=true;}

        if (kontol){
            System.err.println("Wrong ID/Password");
        }

        input.close();
    }
}

and above is the syntax for checking login credentials

Body:
It's because id and password collections are empty.

id = new ArrayList<>();
password = new ArrayList<>();

These instructions will create new empty collections, so when you try to obtain the password for a user, it will always fail, because there is no single user or password in those collections.


答:
There is also a -split operator.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_split

basic example:

if you have file names in $FilePaths array.

```<code>foreach($filepath in $FilePaths)
{
  $parts = $filepath -split '-';
  [pscustomobject]@{"User" = $parts[0]; "AppID" = $parts[1]; "FileType" = $parts[2]; "FilePath"=$filepath }
}
</code>```

Title: Powershell - How to split a string based on characters?

Body:
I have a list of pdf filenames that need to be parsed and ultimately sent to a sql table, with the parse out pieces each in their own column.  How would I split based on a dash '-' and ultimately get it into a table.

What cmdlets would you start with to split on a character?  I need to split based on the dash '-'.

Thanks for the help.

Example File Names:

tester-2458-full_contact_snapshot-20200115_1188.pdf

tester-2458-limited_contact_snapshot-20200119_9330.pdf

Desired Results:

Body:
There is also a -split operator.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_split

basic example:

if you have file names in $FilePaths array.

foreach($filepath in $FilePaths)
{
  $parts = $filepath -split '-';
  [pscustomobject]@{"User" = $parts[0]; "AppID" = $parts[1]; "FileType" = $parts[2]; "FilePath"=$filepath }
}


问:
How to change referenced numpy arrays to a slice of itself?
Consider the following operation and slicing applied to two numpy arrays:

```<code>In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])
</code>```

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

```<code>In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]
</code>```

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

```<code>In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])
</code>```

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

答:
You can use map to map the slicing on all the variables

import numpy as np
a = np.array([1,2,3,4])
b = np.array([5,6,7,8])

def func(x):
    x[2:] = 0
    x = x[::2]
    return x
[a,b] = list(map(func,[a,b]))
print(a,b)
```

<p>Output:</p>

```[1 0] [5 0]
```

Body:
Consider the following operation and slicing applied to two numpy arrays:

In [1]: import numpy as np

In [2]: a = np.array([1,2,3,4])

In [3]: b = np.array([5,6,7,8])

In [4]: a[2:] = 0

In [5]: a = a[::2]

In [6]: b[2:] = 0

In [7]: b = b[::2]

In [8]: a
Out[8]: array([1, 0])

In [9]: b
Out[9]: array([5, 0])

I do not want to repeat the slicing code, for example, instead of lines [4]-[7] above, I wish to use something like

In [4]: for data in [a,b] :
   ...:     data[2:] = 0
   ...:     data = data[::2]

I understand that it does not work because the effect of data = data[::2] is to make data to point a new object, not to change the original objects. So the values of a and b are not sliced:

In [5]: a
Out[5]: array([1, 2, 0, 0])

In [6]: b
Out[6]: array([5, 6, 0, 0])

My question is:

How to slice a numpy array referenced by a variable?

In my real application, I an doing several operations in each array, and want to have them all in the same block inside the for.

Body:
You can use map to map the slicing on all the variables

import numpy as np
a = np.array([1,2,3,4])
b = np.array([5,6,7,8])

def func(x):
    x[2:] = 0
    x = x[::2]
    return x
[a,b] = list(map(func,[a,b]))
print(a,b)

Output:

[1 0] [5 0]


问:
how to set document title of new open window?
I am doing as below code to set document title for new open window

var downloadWindow = window.open("https://www.google.com/", "_blank");
downloadWindow.document.title = "my title";```

If we try to execute above snippet in console in google chrome, we can see while loading, We can see "my title", but same behaviour I want to be in internet explore?

How we can achieve same behaviour in internet explore?

答:
Try this</p>

```<code>var downloadWindow = window.open("https://www.google.com/", "_blank");
downloadWindow.document.write('<title>my title</title>');
</code>```

Body:
I am doing as below code to set document title for new open window

var downloadWindow = window.open("https://www.google.com/", "_blank");
downloadWindow.document.title = "my title";

If we try to execute above snippet in console in google chrome, we can see while loading, We can see "my title", but same behaviour I want to be in internet explore?

How we can achieve same behaviour in internet explore?

Body:
Try this

var downloadWindow = window.open("https://www.google.com/", "_blank");
downloadWindow.document.write('<title>my title</title>');


答:
See it on jsfiddle. This will put the text from each td with class titel on the title attribute of the a on the same row.

```<code>$('td.titel').each(function() {
    $(this).parent().find('a').attr('title', $(this).text());
});
</code>```

Explanation of what this does:

For each of the selected td.titel elements

Walk up the tree to the parent (in this case it's the tr), then down to the a inside that tr

Put the text of the td.titel element in the title attribute of the a

Body:
I have HTML:

            Afbeelding
            Locatie
            Groep
            Soort
            Bijzonderheden

            Tuin
            Appels
            Dubbele Bellefleur
            Zoete stevige appel

            Tuin
            Appels
            Dubbele Zoete Aagt
            Zoete stevige appel

            Tuin
            Appels
            Ellisons Orange
            Zoete stevige appel

What I am trying to create is that jQuery gets the title from the: td class="titel"
and create at the a href="......" a title tag like this:

Tuin
Appels
Ellisons Orange
Zoete stevige appel

I have tried the following :

$(document).ready(function(){
 var gettitle = $("td:eq(3)").html();
                 $("td a").attr("title", $('td.titel').text());

And:

$("td a.img").attr("title", $('.titel').html());

And:

$('table').each(function() {
  var title = $(this).find('td.titel').text();
  $(this).find('td a').attr('title', title);
 });

All of them are working, but collecting all the titles from the table and attach them to all the images.

What I need is that jQuery collects the title and attach it to the image above the td where it gets the title. What am I doing wrong?

Body:
See it on jsfiddle. This will put the text from each td with class titel on the title attribute of the a on the same row.

$('td.titel').each(function() {
    $(this).parent().find('a').attr('title', $(this).text());
});

Explanation of what this does:

For each of the selected td.titel elements

Walk up the tree to the parent (in this case it's the tr), then down to the a inside that tr

Put the text of the td.titel element in the title attribute of the a


问:
Updating a Bound Property does not update the View in WPF
I am playing around with the MVVM pattern.

I have built a simple application that includes just

-a ListView that displays a simple collection of a UserControl,

-a Button that adds new items to the ListView and

-a ContextMenu that should allow the user to edit the SelectedItem.

The problem:

I have two ICommands bound to my View. ItemBeginEdit and ItemEndEdit.

They are both called properly throughout the app and the parameters are passed through correctly. Tested.

The CommandParameter for each Command is the Bound source of the ListView.SelectedItem (UserControl).

To make it clear:

-ListView.ItemSource = Collection of Models.Item

-ListView.DataTemplate = UserControls.Item

-UserControls.Item.Source = DependencyProperty of type Models.Item.

When changing the whole Collection, the ListView displays correctly all of my items.

When I am getting a reference of Models.Item from the ListView.SelectedItem and change one of its properties in the ICommand execution, it is not updated on the UI.

I have noticed that if I edit the Collection in the Constructor of my ViewModel, the UI updates just for that time only.

If I try to changed it back through the ICommand, nothing happens.

INotifyPropertyChanged is implemented to the relevant classes.

I am still learning WPF and XAML. What do I miss?

The code:

-MainWindow.xaml (View)

```<code><Window x:Class="Demo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Demo"
    xmlns:uc="clr-namespace:Demo.Views.UserControls"
    xmlns:vm="clr-namespace:Demo.ViewModels"
    xmlns:b="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    mc:Ignorable="d"
    x:Name="windowMain"
    Title="Demo"
    Height="300"
    Width="300"
    WindowStartupLocation="CenterScreen">

<Window.DataContext>
    <vm:MainVM />
</Window.DataContext>

<StackPanel>
    <Button x:Name="btnAddItem"
            Content="Add"
            Width="150"
            Command="{Binding ItemNew}" />
    <ListView x:Name="lviewCollection"
              Width="150"
              MinHeight="100"
              HorizontalContentAlignment="Stretch"
              ItemsSource="{Binding Items}"
              SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
        <b:Interaction.Triggers>
            <b:EventTrigger EventName="LostFocus">
                <b:InvokeCommandAction Command="{Binding ItemEndEdit}"
                                       CommandParameter="{Binding SelectedItem}" />
            </b:EventTrigger>
        </b:Interaction.Triggers>
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <uc:Item DataSource="{Binding}"
                             IsEditing="{Binding IsEditing}">
                    </uc:Item>

                    <StackPanel.ContextMenu>
                        <ContextMenu DataContext="{Binding Source={x:Reference Name=windowMain}, Path=DataContext}">
                            <MenuItem Header="Rename"
                                      Command="{Binding ItemBeginEdit}"
                                      CommandParameter="{Binding SelectedItem}" />
                        </ContextMenu>
                    </StackPanel.ContextMenu>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>
</code>```

-MainVM.cs (ViewModel)

```<code>using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Demo.ViewModels
{
    public class MainVM : INotifyPropertyChanged
    {
        //INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string PropertyName = "")
        {
            var args = new PropertyChangedEventArgs(PropertyName);
            PropertyChanged?.Invoke(this, args);
        }

        //Properties
        public ObservableCollection<Models.CustomItem> Items { get; set; }

        private Models.CustomItem selectedItem;
        public Models.CustomItem SelectedItem
        {
            get { return selectedItem; }
            set
            {
                if (value == null)
                    return;
                if (value == selectedItem)
                    return;

                selectedItem = value;
                OnPropertyChanged();
            }
        }

        public Commands.CmdItemNew ItemNew { get; set; }
        public Commands.CmdItemBeginEdit ItemBeginEdit { get; set; }
        public Commands.CmdItemEndEdit ItemEndEdit { get; set; }

        //Constructors
        public MainVM()
        {
            Items = new ObservableCollection<Models.CustomItem>();
            SelectedItem = null;
            ItemNew = new Commands.CmdItemNew(this);
            ItemBeginEdit = new Commands.CmdItemBeginEdit(this);
            ItemEndEdit = new Commands.CmdItemEndEdit(this);

            ReadItems();
        }

        //Methods
        public void SetupItems()
        {
            //Just create demo items. Not used.
            var items = DatabaseHelper.ReadItems();
            int itemsToCreate = 3 - items.Length;
            while (itemsToCreate > 0)
            {
                CreateItem();
                itemsToCreate--;
            }
        }

        public void CreateItem()
        {
            var item = new Models.CustomItem()
            {
                Name = "New Item"
            };
            DatabaseHelper.Insert(item);
        }

        public void ReadItems()
        {
            var items = DatabaseHelper.ReadItems();
            Items.Clear();
            foreach (var item in items)
                Items.Add(item);
        }
    }
}
</code>```

-CustomItem.cs (Model)

```<code>using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using SQLite;

namespace Demo.Models
{
    public class CustomItem : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string PropertyName = "")
        {
            if (PropertyChanged != null)
            {
                var args = new PropertyChangedEventArgs(PropertyName);
                PropertyChanged.Invoke(this, args);
            }
        }
        #endregion

        //Properties
        private int id;
        [PrimaryKey, AutoIncrement]
        public int Id
        {
            get { return id; }
            set
            {
                if (value != id)
                {
                    id = value;
                    OnPropertyChanged();
                }
            }
        }

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (value != name)
                {
                    name = value;
                    OnPropertyChanged();
                }
            }
        }

        private bool isEditing;
        [Ignore]
        public bool IsEditing
        {
            get
            {
                return isEditing;
            }
            set
            {
                if (value != isEditing)
                {
                    isEditing = value;
                    OnPropertyChanged();
                }
            }
        }
    }
}
</code>```

-CmdItemBeginEdit.cs (ICommand)

```<code>using System;
using System.Windows.Input;

namespace Demo.ViewModels.Commands
{
    public class CmdItemBeginEdit : ICommand
    {
        #region ICommand implementation
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public void Execute(object parameter)
        {
            var item = parameter as Models.CustomItem;
            if (item == null)
                return;

            item.IsEditing = true;
        }
        #endregion

        //Properties
        public MainVM VM { get; set; }

        //Constructors
        public CmdItemBeginEdit(MainVM VM)
        {
            this.VM = VM;
        }
    }
}
</code>```

-CmdItemEndEdit.cs (ICommand)

```<code>using System;
using System.Windows.Input;

namespace Demo.ViewModels.Commands
{
    public class CmdItemEndEdit : ICommand
    {
        #region ICommand implementation
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public void Execute(object parameter)
        {
            var item = parameter as Models.CustomItem;
            if (item == null)
                return;

            item.IsEditing = false;
        }
        #endregion

        //Properties
        public MainVM VM { get; set; }

        //Constructors
        public CmdItemEndEdit(MainVM VM)
        {
            this.VM = VM;
        }
    }
}
</code>```

-Item.xaml (UserControl)

```<code><UserControl x:Class="Demo.Views.UserControls.Item"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:Demo.Views.UserControls"
         mc:Ignorable="d"
         d:DesignHeight="45"
         d:DesignWidth="90">

    <StackPanel HorizontalAlignment="Left"
                VerticalAlignment="Center">
        <TextBlock x:Name="tblockName"
                   Text="Name"
                   Margin="2"
                   FontSize="15"
                   VerticalAlignment="Center" />
        <TextBox x:Name="tboxInput"
                 Text="Name"
                 Visibility="Collapsed"
                 Margin="2"
                 FontSize="14"
                 FontStyle="Italic"
                 VerticalAlignment="Center">
        </TextBox>
    </StackPanel>
</UserControl>
</code>```

-Item.xaml.cs (UserControl)

```<code>using System;
using System.Windows;
using System.Windows.Controls;

namespace Demo.Views.UserControls
{
    public partial class Item : UserControl
    {
        #region DependencyProperty - DataSource
        public Models.CustomItem DataSource
        {
            get { return (Models.CustomItem)GetValue(DataSourceProperty); }
            set { SetValue(DataSourceProperty, value); }
        }
        public static readonly DependencyProperty DataSourceProperty =
            DependencyProperty.Register("DataSource", typeof(Models.CustomItem), typeof(Item), new PropertyMetadata(null, SetDataSource));
        private static void SetDataSource(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as Item;
            var value = e.NewValue as Models.CustomItem;

            if (value == null)
            {
                control.tblockName.Text = string.Empty;
                control.IsEditing = false;
            }
            else
            {
                control.tblockName.Text = value.Name;
                control.IsEditing = value.IsEditing;
            }
        }
        #endregion

        #region DependencyProperty - IsEditing
        public bool IsEditing
        {
            get { return (bool)GetValue(IsEditingProperty); }
            set { SetValue(IsEditingProperty, value); }
        }
        public static readonly DependencyProperty IsEditingProperty =
            DependencyProperty.Register("IsEditing", typeof(bool), typeof(Item), new PropertyMetadata(false, SetIsEditing));
        private static void SetIsEditing(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as Item;
            var value = (bool)(e.NewValue);

            if (value)
            {
                control.tblockName.Visibility = Visibility.Collapsed;
                control.tboxInput.Visibility = Visibility.Visible;
            }
            else
            {
                control.tboxInput.Visibility = Visibility.Collapsed;
                control.tblockName.Visibility = Visibility.Visible;
            }
        }
        #endregion

        //Constructors
        public Item()
        {
            InitializeComponent();
        }
    }
}
</code>```

答:
It seems that you are assuming that the DataSource property of the Item control is set whenever a property of the referenced CustomItem class changes. That is not the case.

You should remove the DataSource property and add properties that are bound to the view model item properties like this:

```<code><ListView.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <uc:Item Text="{Binding Name}" ... />
            ...
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>
</code>```

The elements in the UserControl's XAML will bind to its properties like

```<code><TextBlock Text="{Binding Text,
                  RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</code>```

An alternative to exposing a set of UserControl properties would be that the elements in the UserControl's XAML bind directly to the view model properties, like

```<code><TextBlock Text="{Binding Name}" ... />
</code>```

Then ItemTemplate would then simply contain this:

```<code><uc:Item />
</code>```

This would however make the UserControl dependent on the view model type (or more precisely on any type that exposes an equivalent set of properties).

Body:
I am playing around with the MVVM pattern.

I have built a simple application that includes just

-a ListView that displays a simple collection of a UserControl,

-a Button that adds new items to the ListView and

-a ContextMenu that should allow the user to edit the SelectedItem.

The problem:

I have two ICommands bound to my View. ItemBeginEdit and ItemEndEdit.

They are both called properly throughout the app and the parameters are passed through correctly. Tested.

The CommandParameter for each Command is the Bound source of the ListView.SelectedItem (UserControl).

To make it clear:

-ListView.ItemSource = Collection of Models.Item

-ListView.DataTemplate = UserControls.Item

-UserControls.Item.Source = DependencyProperty of type Models.Item.

When changing the whole Collection, the ListView displays correctly all of my items.

When I am getting a reference of Models.Item from the ListView.SelectedItem and change one of its properties in the ICommand execution, it is not updated on the UI.

I have noticed that if I edit the Collection in the Constructor of my ViewModel, the UI updates just for that time only.

If I try to changed it back through the ICommand, nothing happens.

INotifyPropertyChanged is implemented to the relevant classes.

I am still learning WPF and XAML. What do I miss?

The code:

-MainWindow.xaml (View)

<Window x:Class="Demo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Demo"
    xmlns:uc="clr-namespace:Demo.Views.UserControls"
    xmlns:vm="clr-namespace:Demo.ViewModels"
    xmlns:b="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    mc:Ignorable="d"
    x:Name="windowMain"
    Title="Demo"
    Height="300"
    Width="300"
    WindowStartupLocation="CenterScreen">

<Window.DataContext>
    <vm:MainVM />
</Window.DataContext>

<StackPanel>
    <Button x:Name="btnAddItem"
            Content="Add"
            Width="150"
            Command="{Binding ItemNew}" />
    <ListView x:Name="lviewCollection"
              Width="150"
              MinHeight="100"
              HorizontalContentAlignment="Stretch"
              ItemsSource="{Binding Items}"
              SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">

        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <uc:Item DataSource="{Binding}"
                             IsEditing="{Binding IsEditing}">
                    </uc:Item>

                    <StackPanel.ContextMenu>
                        <ContextMenu DataContext="{Binding Source={x:Reference Name=windowMain}, Path=DataContext}">
                            <MenuItem Header="Rename"
                                      Command="{Binding ItemBeginEdit}"
                                      CommandParameter="{Binding SelectedItem}" />
                        </ContextMenu>
                    </StackPanel.ContextMenu>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackPanel>

-MainVM.cs (ViewModel)

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Demo.ViewModels
{
    public class MainVM : INotifyPropertyChanged
    {
        //INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string PropertyName = "")
        {
            var args = new PropertyChangedEventArgs(PropertyName);
            PropertyChanged?.Invoke(this, args);
        }

        //Properties
        public ObservableCollection<Models.CustomItem> Items { get; set; }

        private Models.CustomItem selectedItem;
        public Models.CustomItem SelectedItem
        {
            get { return selectedItem; }
            set
            {
                if (value == null)
                    return;
                if (value == selectedItem)
                    return;

                selectedItem = value;
                OnPropertyChanged();
            }
        }

        public Commands.CmdItemNew ItemNew { get; set; }
        public Commands.CmdItemBeginEdit ItemBeginEdit { get; set; }
        public Commands.CmdItemEndEdit ItemEndEdit { get; set; }

        //Constructors
        public MainVM()
        {
            Items = new ObservableCollection<Models.CustomItem>();
            SelectedItem = null;
            ItemNew = new Commands.CmdItemNew(this);
            ItemBeginEdit = new Commands.CmdItemBeginEdit(this);
            ItemEndEdit = new Commands.CmdItemEndEdit(this);

            ReadItems();
        }

        //Methods
        public void SetupItems()
        {
            //Just create demo items. Not used.
            var items = DatabaseHelper.ReadItems();
            int itemsToCreate = 3 - items.Length;
            while (itemsToCreate > 0)
            {
                CreateItem();
                itemsToCreate--;
            }
        }

        public void CreateItem()
        {
            var item = new Models.CustomItem()
            {
                Name = "New Item"
            };
            DatabaseHelper.Insert(item);
        }

        public void ReadItems()
        {
            var items = DatabaseHelper.ReadItems();
            Items.Clear();
            foreach (var item in items)
                Items.Add(item);
        }
    }
}

-CustomItem.cs (Model)

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using SQLite;

namespace Demo.Models
{
    public class CustomItem : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged implementation
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string PropertyName = "")
        {
            if (PropertyChanged != null)
            {
                var args = new PropertyChangedEventArgs(PropertyName);
                PropertyChanged.Invoke(this, args);
            }
        }
        #endregion

        //Properties
        private int id;
        [PrimaryKey, AutoIncrement]
        public int Id
        {
            get { return id; }
            set
            {
                if (value != id)
                {
                    id = value;
                    OnPropertyChanged();
                }
            }
        }

        private string name;
        public string Name
        {
            get { return name; }
            set
            {
                if (value != name)
                {
                    name = value;
                    OnPropertyChanged();
                }
            }
        }

        private bool isEditing;
        [Ignore]
        public bool IsEditing
        {
            get
            {
                return isEditing;
            }
            set
            {
                if (value != isEditing)
                {
                    isEditing = value;
                    OnPropertyChanged();
                }
            }
        }
    }
}

-CmdItemBeginEdit.cs (ICommand)

using System;
using System.Windows.Input;

namespace Demo.ViewModels.Commands
{
    public class CmdItemBeginEdit : ICommand
    {
        #region ICommand implementation
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public void Execute(object parameter)
        {
            var item = parameter as Models.CustomItem;
            if (item == null)
                return;

            item.IsEditing = true;
        }
        #endregion

        //Properties
        public MainVM VM { get; set; }

        //Constructors
        public CmdItemBeginEdit(MainVM VM)
        {
            this.VM = VM;
        }
    }
}

-CmdItemEndEdit.cs (ICommand)

using System;
using System.Windows.Input;

namespace Demo.ViewModels.Commands
{
    public class CmdItemEndEdit : ICommand
    {
        #region ICommand implementation
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public void Execute(object parameter)
        {
            var item = parameter as Models.CustomItem;
            if (item == null)
                return;

            item.IsEditing = false;
        }
        #endregion

        //Properties
        public MainVM VM { get; set; }

        //Constructors
        public CmdItemEndEdit(MainVM VM)
        {
            this.VM = VM;
        }
    }
}

-Item.xaml (UserControl)

<UserControl x:Class="Demo.Views.UserControls.Item"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:Demo.Views.UserControls"
         mc:Ignorable="d"
         d:DesignHeight="45"
         d:DesignWidth="90">

    <StackPanel HorizontalAlignment="Left"
                VerticalAlignment="Center">
        <TextBlock x:Name="tblockName"
                   Text="Name"
                   Margin="2"
                   FontSize="15"
                   VerticalAlignment="Center" />
        <TextBox x:Name="tboxInput"
                 Text="Name"
                 Visibility="Collapsed"
                 Margin="2"
                 FontSize="14"
                 FontStyle="Italic"
                 VerticalAlignment="Center">
        </TextBox>
    </StackPanel>
</UserControl>

-Item.xaml.cs (UserControl)

using System;
using System.Windows;
using System.Windows.Controls;

namespace Demo.Views.UserControls
{
    public partial class Item : UserControl
    {
        #region DependencyProperty - DataSource
        public Models.CustomItem DataSource
        {
            get { return (Models.CustomItem)GetValue(DataSourceProperty); }
            set { SetValue(DataSourceProperty, value); }
        }
        public static readonly DependencyProperty DataSourceProperty =
            DependencyProperty.Register("DataSource", typeof(Models.CustomItem), typeof(Item), new PropertyMetadata(null, SetDataSource));
        private static void SetDataSource(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as Item;
            var value = e.NewValue as Models.CustomItem;

            if (value == null)
            {
                control.tblockName.Text = string.Empty;
                control.IsEditing = false;
            }
            else
            {
                control.tblockName.Text = value.Name;
                control.IsEditing = value.IsEditing;
            }
        }
        #endregion

        #region DependencyProperty - IsEditing
        public bool IsEditing
        {
            get { return (bool)GetValue(IsEditingProperty); }
            set { SetValue(IsEditingProperty, value); }
        }
        public static readonly DependencyProperty IsEditingProperty =
            DependencyProperty.Register("IsEditing", typeof(bool), typeof(Item), new PropertyMetadata(false, SetIsEditing));
        private static void SetIsEditing(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = d as Item;
            var value = (bool)(e.NewValue);

            if (value)
            {
                control.tblockName.Visibility = Visibility.Collapsed;
                control.tboxInput.Visibility = Visibility.Visible;
            }
            else
            {
                control.tboxInput.Visibility = Visibility.Collapsed;
                control.tblockName.Visibility = Visibility.Visible;
            }
        }
        #endregion

        //Constructors
        public Item()
        {
            InitializeComponent();
        }
    }
}

Body:
It seems that you are assuming that the DataSource property of the Item control is set whenever a property of the referenced CustomItem class changes. That is not the case.

You should remove the DataSource property and add properties that are bound to the view model item properties like this:

<ListView.ItemTemplate>
    <DataTemplate>
        <StackPanel>
            <uc:Item Text="{Binding Name}" ... />
            ...
        </StackPanel>
    </DataTemplate>
</ListView.ItemTemplate>

The elements in the UserControl's XAML will bind to its properties like

<TextBlock Text="{Binding Text,
                  RelativeSource={RelativeSource AncestorType=UserControl}}"/>

An alternative to exposing a set of UserControl properties would be that the elements in the UserControl's XAML bind directly to the view model properties, like

<TextBlock Text="{Binding Name}" ... />

Then ItemTemplate would then simply contain this:

<uc:Item />

This would however make the UserControl dependent on the view model type (or more precisely on any type that exposes an equivalent set of properties).