问:
Bind a Button Flyout Command to a ViewModel's Command in DataTemplate
I'm new to UWP I am attempting to bind to an event in my ViewModel from a button flyout inside a listview that is shown on every item. I've looked at many solutions online and came up with the following code, it compiles fine but when I click the said Edit button nothing happens.

My ViewModel is available from the Page's context and not the Item's context

XAML

```<code><ListView x:Name="MainListView"
                  ItemsSource="{x:Bind ViewModel.Devices, Mode=OneWay}"
                  SelectionMode="Multiple"
                  SelectionChanged="MainListView_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid Width="Auto">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="0*"></ColumnDefinition>
                            <ColumnDefinition Width=".4*"></ColumnDefinition>
                            <ColumnDefinition Width="3*"></ColumnDefinition>
                            <ColumnDefinition Width="3*"></ColumnDefinition>
                            <ColumnDefinition Width="3*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="2" Text="{Binding AssetNumber}"/>
                        <TextBlock Grid.Column="3" Text="{Binding SerialNumber}"/>
                        <TextBlock Grid.Column="4" Text="{Binding Model}"/>
                        <Button Grid.Column="1" Height="30" Width="30">
                            <Button.Flyout>
                                <MenuFlyout>
                                    <MenuFlyoutItem Text="Edit" Icon="Edit"
                                                    Command="{Binding ElementName=MainListView,Path=DataContext.ViewModel.EditCommand}"
                                                    CommandParameter="{Binding}"/>
                                </MenuFlyout>
                            </Button.Flyout>
                        </Button>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</code>```

View Model Class

```<code>public class MainPageViewModel
{
    // Elements contained in the main listview
    public ObservableCollection<Device> Devices = new ObservableCollection<Device>();

    public MainPageViewModel()
    {
        DeviceProvider.Fill(ref Devices, 100);
        EditCommand = new RelayCommand<Device>(EditDevice);
    }

    public RelayCommand<Device> EditCommand { get; set; }
    private async void EditDevice(Device device)
    {
        // Code here that creates a dialog
    }
}
</code>```

The Device class

```<code>public class Device : INotifyPropertyChanged
{
    private string assetNumber;
    private string serialNumber;
    private string model;
    public string AssetNumber
    {
        get
        {
            return assetNumber;
        }
        set
        {
            assetNumber = value;
            OnPropertyChanged();
        }
    }
    public string SerialNumber
    {
        get
        {
            return serialNumber;
        }
        set
        {
            serialNumber = value;
            OnPropertyChanged();
        }
    }
    public string Model
    {
        get
        {
            return model;
        }

        set
        {
            model = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

</code>```

The RelayCommand class

```<code>public class RelayCommand<T> : ICommand
{
    private readonly Action<T> _execute;
    private readonly Func<bool> _canExecute;

    public event EventHandler CanExecuteChanged;

    public RelayCommand(Action<T> execute) : this(execute, null)
    {
    }

    public RelayCommand(Action<T> execute, Func<bool> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute();
    }

    public void Execute(object parameter)
    {
        _execute((T)parameter);
    }

    public void RaiseCanExecuteChanged()
    {
        var handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

</code>```

答:
Your code doesn't seem to have any problems. So it should work perfectly. But if not, I'd suspect MainPage.ViewModel member might not be defined properly. The property to be used in {Binding} must be "public" and must have "get" accessor. </p>

```<code>public sealed partial class MainPage : Page
{
    public MainPageViewModel ViewModel { get; set; } = new MainPageViewModel();

    public MainPage()
    {
        this.InitializeComponent();
        DataContext = this;
    }
}
</code>```

Body:
I'm new to UWP I am attempting to bind to an event in my ViewModel from a button flyout inside a listview that is shown on every item. I've looked at many solutions online and came up with the following code, it compiles fine but when I click the said Edit button nothing happens.

My ViewModel is available from the Page's context and not the Item's context

XAML

<ListView x:Name="MainListView"
                  ItemsSource="{x:Bind ViewModel.Devices, Mode=OneWay}"
                  SelectionMode="Multiple"
                  SelectionChanged="MainListView_SelectionChanged">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid Width="Auto">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="0*"></ColumnDefinition>
                            <ColumnDefinition Width=".4*"></ColumnDefinition>
                            <ColumnDefinition Width="3*"></ColumnDefinition>
                            <ColumnDefinition Width="3*"></ColumnDefinition>
                            <ColumnDefinition Width="3*"></ColumnDefinition>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="2" Text="{Binding AssetNumber}"/>
                        <TextBlock Grid.Column="3" Text="{Binding SerialNumber}"/>
                        <TextBlock Grid.Column="4" Text="{Binding Model}"/>
                        <Button Grid.Column="1" Height="30" Width="30">
                            <Button.Flyout>
                                <MenuFlyout>
                                    <MenuFlyoutItem Text="Edit" Icon="Edit"
                                                    Command="{Binding ElementName=MainListView,Path=DataContext.ViewModel.EditCommand}"
                                                    CommandParameter="{Binding}"/>
                                </MenuFlyout>
                            </Button.Flyout>
                        </Button>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

View Model Class

public class MainPageViewModel
{
    // Elements contained in the main listview
    public ObservableCollection<Device> Devices = new ObservableCollection<Device>();

    public MainPageViewModel()
    {
        DeviceProvider.Fill(ref Devices, 100);
        EditCommand = new RelayCommand<Device>(EditDevice);
    }

    public RelayCommand<Device> EditCommand { get; set; }
    private async void EditDevice(Device device)
    {
        // Code here that creates a dialog
    }
}

The Device class

public class Device : INotifyPropertyChanged
{
    private string assetNumber;
    private string serialNumber;
    private string model;
    public string AssetNumber
    {
        get
        {
            return assetNumber;
        }
        set
        {
            assetNumber = value;
            OnPropertyChanged();
        }
    }
    public string SerialNumber
    {
        get
        {
            return serialNumber;
        }
        set
        {
            serialNumber = value;
            OnPropertyChanged();
        }
    }
    public string Model
    {
        get
        {
            return model;
        }

        set
        {
            model = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
}

The RelayCommand class

public class RelayCommand<T> : ICommand
{
    private readonly Action<T> _execute;
    private readonly Func<bool> _canExecute;

    public event EventHandler CanExecuteChanged;

    public RelayCommand(Action<T> execute) : this(execute, null)
    {
    }

    public RelayCommand(Action<T> execute, Func<bool> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute();
    }

    public void Execute(object parameter)
    {
        _execute((T)parameter);
    }

    public void RaiseCanExecuteChanged()
    {
        var handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }
}

Body:
Your code doesn't seem to have any problems. So it should work perfectly. But if not, I'd suspect MainPage.ViewModel member might not be defined properly. The property to be used in {Binding} must be "public" and must have "get" accessor.

public sealed partial class MainPage : Page
{
    public MainPageViewModel ViewModel { get; set; } = new MainPageViewModel();

    public MainPage()
    {
        this.InitializeComponent();
        DataContext = this;
    }
}


来源: stackexchange

问:
Can I configure Watin to leave the browser window open when the test completes?
I've just begun trying out WatiN as part of my testing platform for web projects.  For ease of setting up tests and also for allowing some "manual" intervention I'd like to set an option so that the browser window remains open when the test completes.  I'm using the simple quick start with the following code...

```<code>    public void Should_start_google()
    {
        using (var browser = new IE("google.com"))
        {
            browser.TextField(Find.ByName("q")).TypeText("Hello WatiN");
            browser.Button(Find.ByName("btnG")).Click();
        }
    }
</code>```

It runs perfectly fine however when its complete the browser shuts down with the test.  Is there any way to have the browser window remain open?  I think it will be useful for developing my tests.

Thanks,
Justin

答:
You should set the AutoClose property to false.

In your case, you would just need to add the following line:

```<code>browser.AutoClose = false;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've just begun trying out WatiN as part of my testing platform for web projects.  For ease of setting up tests and also for allowing some "manual" intervention I'd like to set an option so that the browser window remains open when the test completes.  I'm using the simple quick start with the following code...

    public void Should_start_google()
    {
        using (var browser = new IE("google.com"))
        {
            browser.TextField(Find.ByName("q")).TypeText("Hello WatiN");
            browser.Button(Find.ByName("btnG")).Click();
        }
    }

It runs perfectly fine however when its complete the browser shuts down with the test.  Is there any way to have the browser window remain open?  I think it will be useful for developing my tests.

Thanks,
Justin

Body:
You should set the AutoClose property to false.

In your case, you would just need to add the following line:

browser.AutoClose = false;


问:
How to create and train own model with own dataset?
I want create and train own model. If not possible to create own, any way to train other models? (Yolo, MobileNet, Coco?)

There some requirements:
- I know only JS (tried Python, no, i don't continue, i can't, Python best language, but i can't, sorry)
- Performance, at least 24 FPS, like real-time detection
- Own dataset freedom (like file /dogs/pitbull/01.png)

I tried Python, but i don't/can't work in Python due of 10 years experience with JS doesn't lets me use Python

Thanks for everyone for help

答:
This answer is written by an IBMer.

If you want to build a model like the one described (image classification/object detection) without having to deal with python - and you want to use it with javascript in a browser, you can try the tooling available at https://cloud.annotations.ai/. It works with a IBM Cloud account but you can stay go on with the free tier - so you just need to register, at least to do your first experiments.

You'll find here https://github.com/cloud-annotations code and boilerplate to use your model on different platform.

It is not an advanced tool but it enables you to put your hands on the topic.

ContentLicense: CC BY-SA 4.0


问:
Escape characters for XML tags allowed? In what cases?
Is following the valid UPnP Control response? Do they have to escape these characters in the value of <OutProfile>? UPnP device architecture1.1(sec 3.2.4) says that argument value should be escaped if it contains characters like <, & etc. But I think it should not, if its xml. Can anyone refer some standard document that can clear this confusion? My point is that using escaped characters in following case is unnecessary and makes debugging difficult. But I need to explain this point with solid references to my peers.

```<code><?xml version="1.0"?><s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetABCResponse
xmlns:u="urn:schemas-upnp-org:service:Client:1"><OutProfile><cProfile>
 <cID>0</cID>
 <iconPreference>
  <mimetype>image/bmp</mimetype>
  <width>32</width>
  <height>32</height>
  <depth>24</depth>
 </iconPreference>
</cProfile>
</OutProfile></u:SetABCResponse></s:Body></s:Envelope>
</code>```

答:
No need to manually escape characters. <![CDATA[ ]]> tags allow you to escape anything you want within the tags

```<code><Node>
<![CDATA[<SubNode>Content</SubNode> ]]>
</Node>
</code>```

http://www.w3schools.com/xml/xml_cdata.asp

Body:
Is following the valid UPnP Control response? Do they have to escape these characters in the value of <OutProfile>? UPnP device architecture1.1(sec 3.2.4) says that argument value should be escaped if it contains characters like <, & etc. But I think it should not, if its xml. Can anyone refer some standard document that can clear this confusion? My point is that using escaped characters in following case is unnecessary and makes debugging difficult. But I need to explain this point with solid references to my peers.

<?xml version="1.0"?><s:Envelope
xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><OutProfile><cProfile>
 <cID>0</cID>
 <iconPreference>
  <mimetype>image/bmp</mimetype>
  <width>32</width>
  <height>32</height>
  <depth>24</depth>
 </iconPreference>
</cProfile>
</OutProfile></s:Body></s:Envelope>

Body:
No need to manually escape characters. <![CDATA[ ]]> tags allow you to escape anything you want within the tags

<Node>
<![CDATA[<SubNode>Content</SubNode> ]]>
</Node>

http://www.w3schools.com/xml/xml_cdata.asp


问:
How to add new training phrases to Rasa NLU dynamically?
I have trained a Rasa bot. I want to add new training phrases to an intent via code and trigger intent so that this new training phrases is available for next utterance. How do I do that?

Could not find any relevant reference in the Rasa documentation. In case of Rasa interactive learning, it seams it is a manual process where a human has to sit an train the model.

答: I think you can use an Interactive session with bot. By doing this you can train bot with some new utterance and new answers </p>


问:
ValidationException: Before you can proceed, you must enable a service-linked role to give Amazon ES permissions to access your VPC
I am trying to create a VPC controlled Elastic Search Service on AWS.  The problem is I keep getting the error when I run the following code: 'ValidationException: Before you can proceed, you must enable a service-linked role to give Amazon ES permissions to access your VPC'.

```<code>const AWS = require('aws-sdk');
AWS.config.update({region:'<aws-datacenter>'});
const accessPolicies = {
  Statement: [{
    Effect: "Allow",
    Principal: {
      AWS: "*"
    },
    Action: "es:*",
    Resource: "arn:aws:es:<dc>:<accountid>:domain/<domain-name/*"
  }]
};
const params = {
  DomainName: '<domain>',
  /* required */
  AccessPolicies: JSON.stringify(accessPolicies),
  AdvancedOptions: {
    EBSEnabled: "true",
    VolumeType: "io1",
    VolumeSize: "100",
    Iops: "1000"
  },
  EBSOptions: {
    EBSEnabled: true,
    Iops: 1000,
    VolumeSize: 100,
    VolumeType: "io1"
  },
  ElasticsearchClusterConfig: {
    DedicatedMasterCount: 3,
    DedicatedMasterEnabled: true,
    DedicatedMasterType: "m4.large.elasticsearch",
    InstanceCount: 2,
    InstanceType: 'm4.xlarge.elasticsearch',
    ZoneAwarenessEnabled: true
  },
  ElasticsearchVersion: '5.5',
  SnapshotOptions: {
    AutomatedSnapshotStartHour: 3
  },
  VPCOptions: {
    SubnetIds: [
      '<redacted>',
      '<redacted>'
    ],
    SecurityGroupIds: [
      '<redacted>'
    ]
  }
};

const es = new AWS.ES();
es.createElasticsearchDomain(params, function (err, data) {
  if (err) {
    console.log(err, err.stack); // an error occurred
  } else {
    console.log(JSON.stringify(data, null, 4)); // successful response
  }
});
</code>```

The problem is I get this error:  ValidationException: Before you can proceed, you must enable a service-linked role to give Amazon ES permissions to access your VPC.  I cannot seem to figure out how to create this service linked role for the elastic search service.  In the aws.amazon.com IAM console I cannot select that service for a role. I believe it is supposed to be created automatically.

Has anybody ran into this or know the way to fix it?

答:
Do it yourself in CDK:</p>

```<code>const serviceLinkedRole = new cdk.CfnResource(this, "es-service-linked-role", {
  type: "AWS::IAM::ServiceLinkedRole",
  properties: {
    AWSServiceName: "es.amazonaws.com",
    Description: "Role for ES to access resources in my VPC"
  }
});

const esDomain = new es.CfnDomain(this, "es", { ... });

esDomain.node.addDependency(serviceLinkedRole);
</code>```

Body:
I am trying to create a VPC controlled Elastic Search Service on AWS.  The problem is I keep getting the error when I run the following code: 'ValidationException: Before you can proceed, you must enable a service-linked role to give Amazon ES permissions to access your VPC'.

const AWS = require('aws-sdk');
AWS.config.update({region:'<aws-datacenter>'});
const accessPolicies = {
  Statement: [{
    Effect: "Allow",
    Principal: {
      AWS: "*"
    },
    Action: "es:*",
    Resource: "arn:aws:es:<dc>:<accountid>:domain/<domain-name/*"
  }]
};
const params = {
  DomainName: '<domain>',
  /* required */
  AccessPolicies: JSON.stringify(accessPolicies),
  AdvancedOptions: {
    EBSEnabled: "true",
    VolumeType: "io1",
    VolumeSize: "100",
    Iops: "1000"
  },
  EBSOptions: {
    EBSEnabled: true,
    Iops: 1000,
    VolumeSize: 100,
    VolumeType: "io1"
  },
  ElasticsearchClusterConfig: {
    DedicatedMasterCount: 3,
    DedicatedMasterEnabled: true,
    DedicatedMasterType: "m4.large.elasticsearch",
    InstanceCount: 2,
    InstanceType: 'm4.xlarge.elasticsearch',
    ZoneAwarenessEnabled: true
  },
  ElasticsearchVersion: '5.5',
  SnapshotOptions: {
    AutomatedSnapshotStartHour: 3
  },
  VPCOptions: {
    SubnetIds: [
      '<redacted>',
      '<redacted>'
    ],
    SecurityGroupIds: [
      '<redacted>'
    ]
  }
};

const es = new AWS.ES();
es.createElasticsearchDomain(params, function (err, data) {
  if (err) {
    console.log(err, err.stack); // an error occurred
  } else {
    console.log(JSON.stringify(data, null, 4)); // successful response
  }
});

The problem is I get this error:  ValidationException: Before you can proceed, you must enable a service-linked role to give Amazon ES permissions to access your VPC.  I cannot seem to figure out how to create this service linked role for the elastic search service.  In the aws.amazon.com IAM console I cannot select that service for a role. I believe it is supposed to be created automatically.

Has anybody ran into this or know the way to fix it?

Body:
Do it yourself in CDK:

const serviceLinkedRole = new cdk.CfnResource(this, "es-service-linked-role", {
  type: "AWS::IAM::ServiceLinkedRole",
  properties: {
    AWSServiceName: "es.amazonaws.com",
    Description: "Role for ES to access resources in my VPC"
  }
});

const esDomain = new es.CfnDomain(this, "es", { ... });

esDomain.node.addDependency(serviceLinkedRole);


问:
Trying to get the duplicate serial numbers repeating more than three times from this list using perl or awk command
For example: From the below example I was trying to get the duplicated serial numbers which only repeats more than three times.

```<code>Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4
</code>```

So if I return the output it should be something like this:

Only duplicated serial no's

output should be:

```<code>G1A114080901301|D4A928|FiOS-Gen4
G1A114071803436|D4A928|FiOS-Gen4
</code>```

(as this serial no's are only repeating more than two times)

Commands I used:

```<code>sort  sed2file.csv | uniq -id > sortedfile.csv
perl -ne 'print if $a{$_}++' filename
</code>```

答:
Sample code how it can be achieved in perl. See if it fits your purpose.

```<code>use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $debug = 0;                      # debug flag

my %data;                           # data storage
my $num_duplicates = 3;             # treshold for duplicates

for (<DATA>) {                      # walk through data
    next if /Time/;                 # skip header
    chomp;                          # snip \n
    my($time,$serial) = split ' ';  # get time and serial
    $data{$serial}++;               # count duplicates
}

say Dumper(\%data) if $debug;       # look into what we collected

for my $k ( sort keys %data ) {     # look for treshold
    say $k if $data{$k} >= $num_duplicates;
}

__DATA__
Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4
</code>```

Output

```<code>G1A114071803436|D4A928|FiOS-Gen4
G1A114080901301|D4A928|FiOS-Gen4
</code>```

Body:
For example: From the below example I was trying to get the duplicated serial numbers which only repeats more than three times.

Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4

So if I return the output it should be something like this:

Only duplicated serial no's

output should be:

G1A114080901301|D4A928|FiOS-Gen4
G1A114071803436|D4A928|FiOS-Gen4

(as this serial no's are only repeating more than two times)

Commands I used:

sort  sed2file.csv | uniq -id > sortedfile.csv
perl -ne 'print if $a{$_}++' filename

Body:
Sample code how it can be achieved in perl. See if it fits your purpose.

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $debug = 0;                      # debug flag

my %data;                           # data storage
my $num_duplicates = 3;             # treshold for duplicates

for (<DATA>) {                      # walk through data
    next if /Time/;                 # skip header
    chomp;                          # snip \n
    my($time,$serial) = split ' ';  # get time and serial
    $data{$serial}++;               # count duplicates
}

say Dumper(\%data) if $debug;       # look into what we collected

for my $k ( sort keys %data ) {     # look for treshold
    say $k if $data{$k} >= $num_duplicates;
}

__DATA__
Time     serial no's     oui   product class
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
22:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:17 G1A114071803436|D4A928|FiOS-Gen4
23:38:18 G1A117072200565|D4A928|FiOS-Gen4
23:07:51 G1A114080901301|D4A928|FiOS-Gen4
23:10:36 G1A114080901301|D4A928|FiOS-Gen4
20:11:51 G1A114080901301|D4A928|FiOS-Gen4

Output

G1A114071803436|D4A928|FiOS-Gen4
G1A114080901301|D4A928|FiOS-Gen4


问:
Checking a CSV for the existence of a similar value in Python
Consider the following CSV:

```<code>date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00
</code>```

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

```<code>16/02/2020,march contract,51.00
17/02/2020,april contract,240.00
</code>```

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])
```

答:
working with dictionary makes it easy to access values

```<code>import csv
from datetime import datetime

_dict = {}
with open("test.csv", "r") as f:
    reader = csv.reader(f, delimiter=",")

    for i, line in enumerate(reader):
        if i==0:
            headings = [line]
        else:
            if _dict.get(line[1],None) is None:
                _dict[line[1]] = {
                                    'date':line[0],
                                    'amount':float(line[2])
                                 }
            else:
                if datetime.strptime(_dict.get(line[1]).get('date'),'%d/%m/%Y') < datetime.strptime(line[0],'%d/%m/%Y'):
                    _dict[line[1]]['date'] = line[0]

                _dict[line[1]]['amount'] = _dict[line[1]]['amount'] + float(line[2])

</code>```

Here your _dict will contain unique description and values

```<code>>>> print(_dict)
{'march contract': {'date': '16/02/2020', 'amount': 51.0},
'april contract': {'date': '17/02/2020', 'amount': 240.0}}
</code>```

convert to list and add headings

```<code>headings.extend([[value['date'],key,value['amount']] for key,value in _dict.items()])

>>>print(headings)
[['date', 'description', 'amount'],['16/02/2020', 'march contract', 51.0], ['17/02/2020', 'april contract', 240.0]]
</code>```

save list to csv

```<code>with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(headings)
</code>```

Body:
Consider the following CSV:

date,description,amount
14/02/2020,march contract,-99.00
15/02/2020,april contract,340.00
16/02/2020,march contract,150.00
17/02/2020,april contract,-100.00

What I'd like to do is:

Iterate through all of the rows

Total the amounts of lines which have the same description

Return the last line which has that newly-calculated amount

Applied to the above example, the CSV would look like this:

16/02/2020,march contract,51.00
17/02/2020,april contract,240.00

So far, I've tried nesting csv.reader()s inside of each other and I'm not getting the result I am wanting.

I'd like to achieve this without any libraries and/or modules.

Here is the code I have so far, where first_row is each row in the CSV and second_row is the iteration of looking for matching descriptions:

csv_reader = csv.reader(report_file)
        for first_row in csv_reader:
            description_index = 5
            amount_index = 13
            print(first_row)
            for second_row in csv_reader:
                if second_row is not first_row:
                    print(first_row[description_index] == second_row[description_index])
                        if first_row[description_index] == second_row[description_index]:
                            first_row[amount_index] = float(first_row[amount_index]) + float(second_row[amount_index])

Body:
working with dictionary makes it easy to access values

import csv
from datetime import datetime

_dict = {}
with open("test.csv", "r") as f:
    reader = csv.reader(f, delimiter=",")

    for i, line in enumerate(reader):
        if i==0:
            headings = [line]
        else:
            if _dict.get(line[1],None) is None:
                _dict[line[1]] = {
                                    'date':line[0],
                                    'amount':float(line[2])
                                 }
            else:
                if datetime.strptime(_dict.get(line[1]).get('date'),'%d/%m/%Y') < datetime.strptime(line[0],'%d/%m/%Y'):
                    _dict[line[1]]['date'] = line[0]

                _dict[line[1]]['amount'] = _dict[line[1]]['amount'] + float(line[2])

Here your _dict will contain unique description and values

>>> print(_dict)
{'march contract': {'date': '16/02/2020', 'amount': 51.0},
'april contract': {'date': '17/02/2020', 'amount': 240.0}}

convert to list and add headings

headings.extend([[value['date'],key,value['amount']] for key,value in _dict.items()])

>>>print(headings)
[['date', 'description', 'amount'],['16/02/2020', 'march contract', 51.0], ['17/02/2020', 'april contract', 240.0]]

save list to csv

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(headings)


问:
Deprovision device using Azure Device Provisioning Service
I'm trying to understand Azure Device Provisioning Service. I provision my virtual device using X.509 certificate and send messages in IoThub.

Now,I tried to temporary disable my device as mention in docs but I don't see any impact in IoThub side. I can see device status is disabled in DPS but enabled in IoThub.

Last I removed my device from DPS but still I can see device in IoThub.

答: The behaviour you're seeing is correct. The Device Provisioning Service will assign your device to an IoT Hub, but will not remove it once you delete the enrollment. The process of deprovisioning a device is described here.</p>


问:
PHP form not writing to mySQL database
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

```<code><form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>

<p>Metric1<br />
<input name="metric1" type="text" /></p>

<p>Metric2<br />
<input name="metric2" type="text" /></p>

<input type="submit" name="submit" value="Submit" />
</form>
</code>```

* Processor File *

```<code><?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>
</code>```

答:
Depending on what the table looks like, your code may or may not work,

```<code>"INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')"
</code>```

assumes that the fields are in that order, and that there are no fields before this one.

```<code>"INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')"
</code>```

would be more future proof, and may also solve your problem as they are going to insert into the correct fields.

It is also possible that you are getting some bad data for the field definitions, try doing the insert in phpmyadmin or at the command line instead of in php, then work backwards from there.

Title: PHP form not writing to mySQL database

Body:
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

<form method="post" action="post_metrics_stack.php" >

Date

<input name="date" type="text" />

Metric1

<input name="metric1" type="text" />

Metric2

<input name="metric2" type="text" />

<input type="submit" name="submit" value="Submit" />
</form>

* Processor File *

<?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>

Body:
Depending on what the table looks like, your code may or may not work,

"INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')"

assumes that the fields are in that order, and that there are no fields before this one.

"INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')"

would be more future proof, and may also solve your problem as they are going to insert into the correct fields.

It is also possible that you are getting some bad data for the field definitions, try doing the insert in phpmyadmin or at the command line instead of in php, then work backwards from there.


问:
Error: [: status_code: integer expression expected in bash
I am a beginner at programming in Unix enviroment and I am facing some difficulties at start. can you help me out in this. </p>

```<code>echo "ES Service getting ready, it may take few mins."
status_code=-1
while [ "status_code" -ne 200 ]
do
    status_code=$(curl -k --write-out %{http_code} --connect-timeout 10---max-time 20 --silent --output /dev/null $ES_HOST)
    printf '.'
    sleep 5
done
```strong text
</code>```

答:
Well, -ne expects an integer expression, and "status_code" isn't an integer, is it? It's a string.

$status_code would be the integer you're looking for.

Body:
I am a beginner at programming in Unix enviroment and I am facing some difficulties at start. can you help me out in this.

echo "ES Service getting ready, it may take few mins."
status_code=-1
while [ "status_code" -ne 200 ]
do
    status_code=$(curl -k --write-out %{http_code} --connect-timeout 10---max-time 20 --silent --output /dev/null $ES_HOST)
    printf '.'
    sleep 5
done
```strong text


问:
NodeJs is sending empty response
I am using NodeJS and MongoDb as a backend service.I am trying to retrieve distinct data based on condition like I want to get names where order status is pending:

```<code>const coll = client.db("My_db").collection("Orders");
            coll.distinct("name",{order_status:"pending"},(function(err,docs){

                  let output = docs.map(r => ({'name':r.name}));
                  res.send(output);

            }));
</code>```

But it is sending empty array like this:

```<code>[
 {},
 {},
 {},
 {},
 {},
 {}
]
</code>```

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

答:
As per documentation Distinct Mongo DB

Thay result will be array .But you are matching r.name its a object key .

So do with argument only

```<code>let output = docs.map(r => ({'name':r}));
</code>```

Title: NodeJs is sending empty response

Body:
I am using NodeJS and MongoDb as a backend service.I am trying to retrieve distinct data based on condition like I want to get names where order status is pending:

const coll = client.db("My_db").collection("Orders");
            coll.distinct("name",{order_status:"pending"},(function(err,docs){

                  let output = docs.map(r => ({'name':r.name}));
                  res.send(output);

            }));

But it is sending empty array like this:

[
 {},
 {},
 {},
 {},
 {},
 {}
]

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

Body:
As per documentation Distinct Mongo DB

Thay result will be array .But you are matching r.name its a object key .

So do with argument only

let output = docs.map(r => ({'name':r}));


问:
Error configuring application listener of class: ClassNotFoundException
in my java maven project, I am getting an exception:

```<code>SEVERE: Error configuring application listener of class [org.springframework.web.context.ContextLoaderListener]
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
</code>```

However, the maven pom eclipse, the build path libraries tab has spring-web-4.3.4.RELEASE.jar which contains that class, and is there because of the pom contains

```<code> <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
</code>```

where

```<code><spring.version>4.3.4.RELEASE</spring.version>
</code>```

And that so the question is, why is that exception being thrown rather than that class being loaded?

答:
If you are working on a web application based on spring which requires use of org.springframework.web.context.ContextLoaderListener in web.xml file and you are getting this exception when you start the server. This exception is more likely when you are working on eclipse or possibly on other such IDE.

Exception log trace will look like this:

```<code>org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
</code>```

Solution:

Reason 1:

Possibly you have not added the spring web dependencies in your project. Just add them if you have not.

Reason 2:

If you are still getting this exception then you must add these dependencies to project deployment assembly as well.

To add dependencies in deployment assembly follow below instructions.

1) Open project properties and select Choose Deployment Assembly. Then select option “Java Build Path Entries”.

2) Click Next and select all jar files. Click Finish.

3) Deployment assembly will look like this. Click Apply.

The ContextLoaderListener is used to integrate Spring with other web application.
Below is an example configuration in web.xml

```<code><!-- file : web.xml -->
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/Spring/applicationContext.xml</param-value>
  </context-param>

  <listener>
    <listener-class>
          org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
</code>```

And the common error message is, your server can not find this Spring ContextLoaderListener class during the server start up.

Try above fixes will help solve the issue.

More details here: https://howtodoinjava.com/spring-core/solved-java-lang-classnotfoundexception-org-springframework-web-context-contextloaderlistener/

Good to refer: java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

Body:
in my java maven project, I am getting an exception:

SEVERE: Error configuring application listener of class [org.springframework.web.context.ContextLoaderListener]
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

However, the maven pom eclipse, the build path libraries tab has spring-web-4.3.4.RELEASE.jar which contains that class, and is there because of the pom contains

 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

where

<spring.version>4.3.4.RELEASE</spring.version>

And that so the question is, why is that exception being thrown rather than that class being loaded?

Body:
If you are working on a web application based on spring which requires use of org.springframework.web.context.ContextLoaderListener in web.xml file and you are getting this exception when you start the server. This exception is more likely when you are working on eclipse or possibly on other such IDE.

Exception log trace will look like this:

org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)

Solution:

Reason 1:

Possibly you have not added the spring web dependencies in your project. Just add them if you have not.

Reason 2:

If you are still getting this exception then you must add these dependencies to project deployment assembly as well.

To add dependencies in deployment assembly follow below instructions.

1) Open project properties and select Choose Deployment Assembly. Then select option “Java Build Path Entries”.

2) Click Next and select all jar files. Click Finish.

3) Deployment assembly will look like this. Click Apply.

The ContextLoaderListener is used to integrate Spring with other web application.
Below is an example configuration in web.xml

<!-- file : web.xml -->
 <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/Spring/applicationContext.xml</param-value>
  </context-param>

  <listener>
    <listener-class>
          org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

And the common error message is, your server can not find this Spring ContextLoaderListener class during the server start up.

Try above fixes will help solve the issue.

More details here: https://howtodoinjava.com/spring-core/solved-java-lang-classnotfoundexception-org-springframework-web-context-contextloaderlistener/

Good to refer: java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener


问:
Rabbitmq: Unable to login in rabbitmq
When I am trying to open rabbitmq page to login it shows the error like "The site can't reachable" enter image description here</p>

答:
This is not a problem with RabbitMQ.

Check your firewall.

Or see if the port is open.

Title: Rabbitmq: Unable to login in rabbitmq


问:
Convert Cartesian coordinate system to polar coordinate system with multi-points
I would like to convert many points from the Cartesian coordinate system to polar coordinate system.

This is my code:

```<code>import numpy as np
x = 1
y = 1
def cart_to_pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

print(cart_to_pol(x, y))
</code>```

But I have many points in an array that needed to convert.

Is there any method that I can covert all points at the same time without one by one?

If the center is not at (0,0), but at (50,50) for example. How can I set the center of the circle in coding?

The result from the code above the degree is in radius (0~2pi), but I need the degree in angle (0~360). I try
phi = np.arctan2(y, x)*180/pi
but the result is wrong. How can I fix it?

Thanks!!!

```<code>points = [(10, 43), (10, 44), (10, 45), (10, 46), (10, 47), (10, 48), (10, 49),
(10, 50), (10, 51), (10, 52), (10, 53), (10, 54), (10, 55), (10, 56), (11, 39),
(11, 40), (11, 41), (11, 42), (11, 57), (11, 58), (11, 59), (11, 60), (12, 36),
(12, 37), (12, 38), (12, 61), (12, 62), (12, 63), (13, 33), (13, 34), (13, 35),
(13, 64), (13, 65), (13, 66), (14, 31), (14, 32), (14, 33), (14, 66), (14, 67),
(14, 68), (15, 30), (15, 31), (15, 68), (15, 69), (16, 28), (16, 29), (16, 70),
(16, 71), (17, 27), (17, 72), (18, 25), (18, 26), (18, 73), (18, 74), (19, 24)]
</code>```

Body:
I would like to convert many points from the Cartesian coordinate system to polar coordinate system.

This is my code:

import numpy as np
x = 1
y = 1
def cart_to_pol(x, y):
    rho = np.sqrt(x**2 + y**2)
    phi = np.arctan2(y, x)
    return(rho, phi)

print(cart_to_pol(x, y))

But I have many points in an array that needed to convert.

Is there any method that I can covert all points at the same time without one by one?

If the center is not at (0,0), but at (50,50) for example. How can I set the center of the circle in coding?

The result from the code above the degree is in radius (0~2pi), but I need the degree in angle (0~360). I try
phi = np.arctan2(y, x)*180/pi
but the result is wrong. How can I fix it?

Thanks!!!

points = [(10, 43), (10, 44), (10, 45), (10, 46), (10, 47), (10, 48), (10, 49),
(10, 50), (10, 51), (10, 52), (10, 53), (10, 54), (10, 55), (10, 56), (11, 39),
(11, 40), (11, 41), (11, 42), (11, 57), (11, 58), (11, 59), (11, 60), (12, 36),
(12, 37), (12, 38), (12, 61), (12, 62), (12, 63), (13, 33), (13, 34), (13, 35),
(13, 64), (13, 65), (13, 66), (14, 31), (14, 32), (14, 33), (14, 66), (14, 67),
(14, 68), (15, 30), (15, 31), (15, 68), (15, 69), (16, 28), (16, 29), (16, 70),
(16, 71), (17, 27), (17, 72), (18, 25), (18, 26), (18, 73), (18, 74), (19, 24)]

Body:
Just use complex math

import numpy as np
x = 1
y = 1
def cart_to_pol(x, y, x_c = 0, y_c = 0, deg = True):
    complex_format = x - x_c + 1j * (y - y_c)
    return np.abs(complex_format), np.angle(complex_format, deg = deg)

print(cart_to_pol(x, y))

(1.4142135623730951, 45.0)

Just pass your center coordinates to (x_c, y_c)  Or you could do it with 2d arrays:

def cart_to_pol(coords, center = [0,0], deg = True):
    complex_format = np.array(coords, dtype = float).view(dtype = np.complex) -\
                     np.array(center, dtype = float).view(dtype = np.complex)
    return np.abs(complex_format).squeeze(), np.angle(complex_format, deg = deg).squeeze()

print(cart_to_pol(points))
(array([44.14748011, 45.12205669, 46.09772229, 47.07440918, 48.05205511,
       49.03060269, 50.009999  , 50.99019514, 51.97114584, 52.95280918,
       53.93514624, 54.91812087, 55.90169944, 56.88585061, 40.52159918,
       41.48493703, 42.44997055, 43.41658669, 58.05170109, 59.03388857,
       60.01666435, 61.        , 37.94733192, 38.89730068, 39.84971769,
       62.16912417, 63.15061362, 64.13267498, 35.4682957 , 36.40054945,
       37.33630941, 65.30696747, 66.28725368, 67.26812024, 34.0147027 ,
       34.92849839, 35.84689666, 67.46851117, 68.44705983, 69.42621983,
       33.54101966, 34.43835072, 69.63476143, 70.61161378, 32.24903099,
       33.12099032, 71.80529228, 72.78049189, 31.90611227, 73.97972695,
       30.8058436 , 31.6227766 , 75.18643495, 76.15773106, 30.61045573]), array([76.90810694, 77.19573393, 77.47119229, 77.73522627, 77.98852161,
       78.23171107, 78.46537935, 78.69006753, 78.90627699, 79.11447295,
       79.3150876 , 79.50852299, 79.69515353, 79.87532834, 74.24882634,
       74.62374875, 74.98163937, 75.32360686, 79.07719528, 79.2611029 ,
       79.43898931, 79.61114218, 71.56505118, 72.03086026, 72.47443163,
       78.87081071, 79.04593736, 79.21570213, 68.49856568, 69.07549826,
       69.62356479, 78.51800865, 78.69006753, 78.85711014, 65.69545073,
       66.37062227, 67.0112832 , 78.02386756, 78.19756579, 78.366366  ,
       63.43494882, 64.17900803, 77.56043798, 77.73522627, 60.2551187 ,
       61.11341823, 77.12499844, 77.30041551, 57.80426607, 76.71513352,
       54.24611275, 55.30484647, 76.14858099, 76.32869287, 51.63251462]))


问:
Is there a way to get outer scope variables with the same name?
If I defined some variable in outer closure, and in the inner closure has defined another variable with the same name. Can I somehow get the outer variable?

I know it's still somewhere in the memory and not been overwritten since it can be printed after the function. Is there a way to access it?

const foo = 'outer';

function bar() {
  const foo = 'inner';

  // Is there a way to get the outside foo from here?
  console.log(foo);   // "inner", but I want it to be "outer"
}

bar();

console.log(foo); // "outer"```

答:
If foo is on the top level and declared with const, one of the only ways to access it with new Function, whose scope when run is on the top level. (Please don't actually do this):

const foo = 'outer';

function bar() {
  const foo = 'inner';
  const fn = new Function('return foo');
  console.log(fn('foo'));
}

bar();

console.log(foo); // "outer"```
</div>
</div>
</p>

<p>See comment by Hao below. <code>eval</code> can work too, but it's a bit more complicated. As MDN says:</p>

<blockquote>
  <p>If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.</p>
</blockquote>

<p>So if you reference <code>eval</code> by <em>any method other than</em> calling the standalone variable name <code>eval(arg)</code>, the code will run on the top level, and it will be able to see the variable on the top level:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const foo = 'outer';

function bar() {
  const foo = 'inner';
  console.log(window.eval('foo'));
  // Another method:
  console.log((0, eval)('foo'))
  // Another method:
  const anotherEvalReference = eval;
  console.log(anotherEvalReference('foo'));
}

bar();

console.log(foo); // "outer"</code>```

If foo is declared with var instead of const, you can just access that property of the global object:

var foo = 'outer';

function bar() {
  const foo = 'inner';
  console.log(window.foo);
}

bar();

console.log(foo); // "outer"```
</div>
</div>
</p>

<p>If the shadowed variable is <em>not</em> on the top level, eg</p>

```(() => {
  const foo = 'intermediate';
  (() => {
    const foo = 'inner';
    // more code here
  })();
})();
```

Then there's no way to access the intermediate variable from the more code here section.

Body:
If foo is on the top level and declared with const, one of the only ways to access it with new Function, whose scope when run is on the top level. (Please don't actually do this):

const foo = 'outer';

function bar() {
  const foo = 'inner';
  const fn = new Function('return foo');
  console.log(fn('foo'));
}

bar();

console.log(foo); // "outer"

See comment by Hao below. eval can work too, but it's a bit more complicated. As MDN says:

If you use the eval function indirectly, by invoking it via a reference other than eval, as of ECMAScript 5 it works in the global scope rather than the local scope. This means, for instance, that function declarations create global functions, and that the code being evaluated doesn't have access to local variables within the scope where it's being called.

So if you reference eval by any method other than calling the standalone variable name eval(arg), the code will run on the top level, and it will be able to see the variable on the top level:

const foo = 'outer';

function bar() {
  const foo = 'inner';
  console.log(window.eval('foo'));
  // Another method:
  console.log((0, eval)('foo'))
  // Another method:
  const anotherEvalReference = eval;
  console.log(anotherEvalReference('foo'));
}

bar();

console.log(foo); // "outer"

If foo is declared with var instead of const, you can just access that property of the global object:

var foo = 'outer';

function bar() {
  const foo = 'inner';
  console.log(window.foo);
}

bar();

console.log(foo); // "outer"

If the shadowed variable is not on the top level, eg

(() => {
  const foo = 'intermediate';
  (() => {
    const foo = 'inner';
    // more code here
  })();
})();

Then there's no way to access the intermediate variable from the more code here section.


问:
BHO HtmlEventObject crashes
I have a browser helper object written in C++ but I have a problem when recieving a OnHelp HtmlEvent.

When I try to access a attribute the browser crashes.

```<code>VARIANT_BOOL STDMETHODCALLTYPE OnHelp(IHTMLEventObj2 *pEvtObj)
{
    std::cout << "OnHelp Event" << std::endl;

    if(pEvtObj != NULL) {
        VARIANT var;
        pEvtObj->getAttribute(L"formID", 0, &var);
        std::cout << (char*)var.bstrVal << std::endl;
    }
    else {
        std::cout << "PELEM = NULL" << std::endl;
    }

    return VARIANT_TRUE;
}
</code>```

It crashes on the getAttribute line for some reason? When doing this in C# it works perfectly. I hope somebody can help me fix this.

Edit:

The real problem was with the parameter I needed to use IHTMLEventObj and then query for IHTMLEventObj2.

```<code>VARIANT_BOOL STDMETHODCALLTYPE OnHelp(IHTMLEventObj *pEvtObj)
{
    IHTMLEventObj2 *pEvtObj2;
    pEvtObj->QueryInterface(IID_IHTMLEventObj2, (void**)&pEvtObj2);

    if(pEvtObj2 != NULL) {
        VARIANT var;
        pEvtObj2->getAttribute(CComBSTR(L"url"), 0, &var);
        std::cout << _bstr_t(var.bstrVal) << std::endl;
    }
    else {
        std::cout << "PELEM = NULL" << std::endl;
    }

    return VARIANT_TRUE;
}
</code>```

答:
The first arg for getAttribute is a BSTR, but your passing a wchar_t*/unsigned int * depending on VC compile settings.

BSTR is a system string which is expected to be deallocated by the receiving method.

Try

```<code>#define DOM_ANON_STRING(x)          (_bstr_t(x))
pEvtObj->getAttribute(DOM_ANON_STRING(L"formID"), 0, &var);
</code>```

Title: BHO HtmlEventObject crashes

Body:
I have a browser helper object written in C++ but I have a problem when recieving a OnHelp HtmlEvent.

When I try to access a attribute the browser crashes.

VARIANT_BOOL STDMETHODCALLTYPE OnHelp(IHTMLEventObj2 *pEvtObj)
{
    std::cout << "OnHelp Event" << std::endl;

    if(pEvtObj != NULL) {
        VARIANT var;
        pEvtObj->getAttribute(L"formID", 0, &var);
        std::cout << (char*)var.bstrVal << std::endl;
    }
    else {
        std::cout << "PELEM = NULL" << std::endl;
    }

    return VARIANT_TRUE;
}

It crashes on the getAttribute line for some reason? When doing this in C# it works perfectly. I hope somebody can help me fix this.

Edit:

The real problem was with the parameter I needed to use IHTMLEventObj and then query for IHTMLEventObj2.

VARIANT_BOOL STDMETHODCALLTYPE OnHelp(IHTMLEventObj *pEvtObj)
{
    IHTMLEventObj2 *pEvtObj2;
    pEvtObj->QueryInterface(IID_IHTMLEventObj2, (void**)&pEvtObj2);

    if(pEvtObj2 != NULL) {
        VARIANT var;
        pEvtObj2->getAttribute(CComBSTR(L"url"), 0, &var);
        std::cout << _bstr_t(var.bstrVal) << std::endl;
    }
    else {
        std::cout << "PELEM = NULL" << std::endl;
    }

    return VARIANT_TRUE;
}

Body:
The first arg for getAttribute is a BSTR, but your passing a wchar_t*/unsigned int * depending on VC compile settings.

BSTR is a system string which is expected to be deallocated by the receiving method.

Try

#define DOM_ANON_STRING(x)          (_bstr_t(x))
pEvtObj->getAttribute(DOM_ANON_STRING(L"formID"), 0, &var);


答: You don't need to run map over that response. The distinct function returns the array of distinct values. Try console.log(docs) and check it </p>

Title: NodeJs is sending empty response


问:
Vue.js component not working
I can't seem to figure out how to make components work. Without the component it works fine (the commented code).

Here's my HTML:

```<code><strong>Total Price:</strong> <span v-text="total"></span><br>
<strong>CPC:</strong> <span v-text="cpc"></span>
</code>```

Here's my Vue.js code:

```<code>Vue.component('my-component', {
    // data: function() {
    //     return { interval: 0, exposure: 0, clicks: 0, total: 0, cpc: 0 }
    // },
    computed: {
        total: function () {
            return(this.clicks * (this.exposure * 0.001 / 10) / 700).toFixed(8)
        },
        cpc: function () {
            return((this.total) / (this.clicks > 0 ? this.clicks : 1)).toFixed(8)
        }
    }
});

const app = new Vue({
    el: '#app',
    data: {
        interval: 0, exposure: 0, clicks: 0, total: 0, cpc: 0
    },
    // computed: {
    //     total: function () {
    //         return(this.clicks * (this.exposure * 0.001 / 10) / 700).toFixed(8)
    //     },
    //     cpc: function () {
    //         return((this.total) / (this.clicks > 0 ? this.clicks : 1)).toFixed(8)
    //     }
    // }
});
</code>```

1) This doesn't work unless I uncomment the commented code.

2) JSFiddle: http://jsfiddle.net/tjkbf71h/3/

答: its a syntax error in object remove comma from last item of object and your code will run normally

Title: Vue.js component not working

Body:
I can't seem to figure out how to make components work. Without the component it works fine (the commented code).

Here's my HTML:

Total Price:

CPC:

Here's my Vue.js code:

Vue.component('my-component', {
    // data: function() {
    //     return { interval: 0, exposure: 0, clicks: 0, total: 0, cpc: 0 }
    // },
    computed: {
        total: function () {
            return(this.clicks * (this.exposure * 0.001 / 10) / 700).toFixed(8)
        },
        cpc: function () {
            return((this.total) / (this.clicks > 0 ? this.clicks : 1)).toFixed(8)
        }
    }
});

const app = new Vue({
    el: '#app',
    data: {
        interval: 0, exposure: 0, clicks: 0, total: 0, cpc: 0
    },
    // computed: {
    //     total: function () {
    //         return(this.clicks * (this.exposure * 0.001 / 10) / 700).toFixed(8)
    //     },
    //     cpc: function () {
    //         return((this.total) / (this.clicks > 0 ? this.clicks : 1)).toFixed(8)
    //     }
    // }
});

1) This doesn't work unless I uncomment the commented code.

2) JSFiddle: http://jsfiddle.net/tjkbf71h/3/


问:
How to calculate the sum of geometric series
I want to calculate the sum of a geometric series. ie: 1 , 5 , 25 , 125 , etc
I try to use the math formula to calculate it: a(r^n -1)/(r-1)

My code:

```<code>int a = 1;
int r = 5;
int deno = r -1;
int n = 3
int rn = r^n -1 ;

int total = a * rn / deno;
</code>```

Apparently there is wrong with the code and only some values like the example I give works. I do not know why QAQ

I think the problem is the symbol ^
can anyone explain what ^ does in java? Appreciate it

答:
Atleast in Java 7, the symbol ^ does not mean power.

Try this, you would also like to put a condition where r>1 or r<1. Both have different formuals.

```<code>        int a = 1;
        int r = 5;
        int deno = r -1;
        int n = 3;
        double sum=a*(Math.pow(r, n)-1)/deno;
</code>```

Body:
I want to calculate the sum of a geometric series. ie: 1 , 5 , 25 , 125 , etc
I try to use the math formula to calculate it: a(r^n -1)/(r-1)

My code:

int a = 1;
int r = 5;
int deno = r -1;
int n = 3
int rn = r^n -1 ;

int total = a * rn / deno;

Apparently there is wrong with the code and only some values like the example I give works. I do not know why QAQ

I think the problem is the symbol ^
can anyone explain what ^ does in java? Appreciate it

Body:
Atleast in Java 7, the symbol ^ does not mean power.

Try this, you would also like to put a condition where r>1 or r<1. Both have different formuals.

        int a = 1;
        int r = 5;
        int deno = r -1;
        int n = 3;
        double sum=a*(Math.pow(r, n)-1)/deno;


问:
angularjs input text focus is working in desktop not working for iPad
I have a search input box in my application. Whenever i will click button, search input will get open. But it is not autofocusing.

Please lookt at my code,

$scope.goSearch = function () {
   $scope.$broadcast("focusTextInput");
}

 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="assets/images/searchIconDefault.svg"/>

<input type="search" autofocus class="form-control search-field" placeholder="Search Card" ng-model="search"  focus-on="focusTextInput"></code>```

 app.directive("focusOn", function ($timeout) {
    return {
      restrict: "A",
      link: function (scope, element, attrs) {
        scope.$on(attrs.focusOn, function (e) {
          $timeout((function () {
            element[0].focus();
          }), 10);
        });
      }
    };
  });```

This is the code i am using.

) The only problem is, cursor blinking focus is working in Desktop, laptop but it is not working in ipad and ipad pro.

Can you please tell how can i do this?

答:
Please try below example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.goSearch = function() {
    document.getElementById("search").focus();
  };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

🔍

<input type="search" autofocus id="search" class="form-control search-field" placeholder="Search Card" ng-model="search"  focus-on="focusTextInput">

</div></code>```

Body:
I have a search input box in my application. Whenever i will click button, search input will get open. But it is not autofocusing.

Please lookt at my code,

$scope.goSearch = function () {
   $scope.$broadcast("focusTextInput");
}

<input type="search" autofocus class="form-control search-field" placeholder="Search Card" ng-model="search"  focus-on="focusTextInput">

 app.directive("focusOn", function ($timeout) {
    return {
      restrict: "A",
      link: function (scope, element, attrs) {
        scope.$on(attrs.focusOn, function (e) {
          $timeout((function () {
            element[0].focus();
          }), 10);
        });
      }
    };
  });

This is the code i am using.

) The only problem is, cursor blinking focus is working in Desktop, laptop but it is not working in ipad and ipad pro.

Can you please tell how can i do this?

Body:
Please try below example

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.goSearch = function() {
    document.getElementById("search").focus();
  };
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

<a class="nav-link-img search-icon" ui-sref="search" ng-click="goSearch();">&#128269;</a>

<input type="search" autofocus id="search" class="form-control search-field" placeholder="Search Card" ng-model="search"  focus-on="focusTextInput">

</div>


问:
Xero Invoice - API Character limit in Apex Salesforce
I'm new to salesforce and i'm trying to Integrate Xero Invoice.

While calling the API GET https://api.xero.com/api.xro/2.0/Invoices/ i've got one question in my mind that what will be the character limit of URL/API for making the HTTP request?
for example, i want to specific Invoices which matches ContactIds

```<code>GET https://api.xero.com/api.xro/2.0/Invoices/?IDs=220ddca8-3144-4085-9a88-2d72c5133734,88192a99-cbc5-4a66-bf1a-2f9fea2d36d0
</code>```

答: It's 2048 characters, which will be about 50 IDs, depending on your other query parameters.</p>

Body:
I'm new to salesforce and i'm trying to Integrate Xero Invoice.

While calling the API GET https://api.xero.com/api.xro/2.0/Invoices/ i've got one question in my mind that what will be the character limit of URL/API for making the HTTP request?
for example, i want to specific Invoices which matches ContactIds

GET https://api.xero.com/api.xro/2.0/Invoices/?IDs=220ddca8-3144-4085-9a88-2d72c5133734,88192a99-cbc5-4a66-bf1a-2f9fea2d36d0


问:
I want default argument promotion's example
At C standard 6.5.2.2. paragraph 6

If the expression that denotes the called function has a type that does not include a prototype, the
  integer promotions are performed on each argument, and arguments that have type float are
  promoted to double. These are called the default argument promotions.

"the expression that denotes the called function has a type that does not include a prototype" What can this be described as code?

```<code>char a = 1;
printf("%d", a); /*"the expression that denotes the called function" is printf, and `a`
doesn't have prototype(char). but a can't be replaced as `char a` originally.  ...? */
</code>```

This is my thought that can be applicable to above standard. Is this right?

答:
The expression that denotes the called function is printf, right.

And if you don't provide a prototype for this function, for example by not including <stdio.h> and not declaring of printf() yourself, the compiler recognizes the function as prototype-less.

In your case the first argument is a const char *, and the second argument is an int.

So, it is not a that has no prototype, but printf().

The value of a will be promoted to int.

The assumed prototype will be int printf(); and takes any number and any type of parameters.

Body:
At C standard 6.5.2.2. paragraph 6

If the expression that denotes the called function has a type that does not include a prototype, the
  integer promotions are performed on each argument, and arguments that have type float are
  promoted to double. These are called the default argument promotions.

"the expression that denotes the called function has a type that does not include a prototype" What can this be described as code?

char a = 1;
printf("%d", a); /*"the expression that denotes the called function" is printf, and `a`
doesn't have prototype(char). but a can't be replaced as `char a` originally.  ...? */

This is my thought that can be applicable to above standard. Is this right?


问:
Still getting Tensorflow 2.0.0 behavior after installing Tensorflow 1.15.0
I installed Tensorflow 1.15.0 on one of the conda environment named tensorflow1 but still print(tf.__version__) is printing 2.0.0.
Also, tf.InterativeSession() is not present in tensorflow 2.0. FYI, I activated the conda environment and I am working in PyCharm for my project.

Please help.

答:
Check where your pip is pointing to.
In conda environment pip should point on
/userName/.conda/envs/env_name(tensorflow1 )/bin/pip this path is local to your environment.

and inside environment don't use --user while installing packages.


问:
AVSpeechSynthesizer change voice
Is it possible to use another person's voice within the same accent?

For example, when I do AVSpeechSynthesisVoice(language: "en-US"), it automatically uses a woman's voice, but I wanted a man instead, with the same accent.

Is it possible to change the voice within the same accent or the only way is to try another voice of another accent (eg: us-AU)

(note I want to change the whole voice, not properties of it, like pitch, speed, etc)

Thank you

答:
Well, The voice can be set using identifier name directly, like below.</p>

```<code>    func speak(say: String) {
        let utterance = AVSpeechUtterance(string: say)
        utterance.voice = AVSpeechSynthesisVoice(identifier: "Karen")
        utterance.rate = 0.4
        utterance.pitchMultiplier = 0.5
        utterance.preUtteranceDelay = 0
        utterance.volume = 1

        synth.speak(utterance)
    }
</code>```

Title: AVSpeechSynthesizer change voice

Body:
Well, The voice can be set using identifier name directly, like below.

    func speak(say: String) {
        let utterance = AVSpeechUtterance(string: say)
        utterance.voice = AVSpeechSynthesisVoice(identifier: "Karen")
        utterance.rate = 0.4
        utterance.pitchMultiplier = 0.5
        utterance.preUtteranceDelay = 0
        utterance.volume = 1

        synth.speak(utterance)
    }


问:
Parse JSON array in side JSON array with List<Class> Flutter
I have JSON like this

```<code>{
"status": "true",
"data": [
    {
        "idpekerjaan": "1",
        "namapekerjaan": "Apel Pagi / Sore",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "2",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "15"
            },
            {
                "idsubpekerjaan": "3",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "20"
            }
        ]
    },
    {
        "idpekerjaan": "2",
        "namapekerjaan": "Upacara",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "10",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "60"
            },
            {
                "idsubpekerjaan": "11",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "90"
            }
        ]
    },
}
</code>```

Saya mempunyai fungsi-fungsi:

```<code> class Localization {
  final List <DataPekerjaan> pekerjaan;
  final List <SubPekerjaan> subpekerjaan;

  Localization({this.pekerjaan, this.subpekerjaan});

  factory Localization.fromJson(Map<String, dynamic> json) {
    return Localization(
      subpekerjaan: parseStates(json),
      pekerjaan: parseProvinces(json),

    );
  }

  static List<SubPekerjaan> parseStates(statesJson) {

    List<DataPekerjaan> cari = parseProvinces(statesJson);
    var slist = ???????????????????? as List;
    List<SubPekerjaan> statesList =
       slist.map((data) => SubPekerjaan.fromJson(data)).toList();
    return statesList;
  }

  static List<DataPekerjaan> parseProvinces(provincesJson) {
    var plist = provincesJson['data'] as List;
    List<DataPekerjaan> provincesList =
        plist.map((data) => DataPekerjaan.fromJson(data)).toList();
    return provincesList;
  }

}

class SubPekerjaan {
  final String idSubPekerjaan;
  final String namaSubPekerjaan;
  final String standarWaktu;

  SubPekerjaan({this.idSubPekerjaan, this.namaSubPekerjaan, this.standarWaktu});

  factory SubPekerjaan.fromJson(Map<String, dynamic> parsedJson){
    return SubPekerjaan(idSubPekerjaan: parsedJson['idsubpekerjaan'], namaSubPekerjaan: parsedJson['namasubpekerjaan'], standarWaktu: parsedJson['standarwaktu']);
  }

}

class DataPekerjaan {
  final String idPekerjaan;
  final String namaPekerjaan;
  final List<String> subPekerjaan;

  DataPekerjaan({this.idPekerjaan, this.namaPekerjaan, this.subPekerjaan});

  factory DataPekerjaan.fromJson(Map<String, dynamic> parsedJson) {
    return DataPekerjaan(idPekerjaan: parsedJson['idpekerjaan'], namaPekerjaan: parsedJson['namapekerjaan'],  subPekerjaan: parsedJson["subpekerjaan"]);
  }

}
</code>```

I want to retrieve the contents of an array of data and then I create a List  and then I also want to take the contents of an array of subpekerjaan so that it becomes a separate data. How can I insert each of those arrays into a function that I already have, especially in the ListparseStates (statesJson). What should I fill in the question mark?
Then is it true how I declare the data type List subPekerjaan on the DataPekerjaan class?

答:
First your json is invalid (VAlidate at https://jsonlint.com/) it should be

```<code>{
"status": "true",
"data": [
    {
        "idpekerjaan": "1",
        "namapekerjaan": "Apel Pagi / Sore",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "2",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "15"
            },
            {
                "idsubpekerjaan": "3",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "20"
            }
        ]
    },
    {
        "idpekerjaan": "2",
        "namapekerjaan": "Upacara",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "10",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "60"
            },
            {
                "idsubpekerjaan": "11",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "90"
            }
        ]
    }
    ]
}
</code>```

Now try with class

```<code>// To parse this JSON data, do
//
//     final myModel = myModelFromJson(jsonString);

import 'dart:convert';

MyModel myModelFromJson(String str) => MyModel.fromJson(json.decode(str));

String myModelToJson(MyModel data) => json.encode(data.toJson());

class MyModel {
    String status;
    List<Datum> data;

    MyModel({
        this.status,
        this.data,
    });

    factory MyModel.fromJson(Map<String, dynamic> json) => MyModel(
        status: json["status"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "status": status,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
    };
}

class Datum {
    String idpekerjaan;
    String namapekerjaan;
    List<Subpekerjaan> subpekerjaan;

    Datum({
        this.idpekerjaan,
        this.namapekerjaan,
        this.subpekerjaan,
    });

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        idpekerjaan: json["idpekerjaan"],
        namapekerjaan: json["namapekerjaan"],
        subpekerjaan: List<Subpekerjaan>.from(json["subpekerjaan"].map((x) => Subpekerjaan.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "idpekerjaan": idpekerjaan,
        "namapekerjaan": namapekerjaan,
        "subpekerjaan": List<dynamic>.from(subpekerjaan.map((x) => x.toJson())),
    };
}

class Subpekerjaan {
    String idsubpekerjaan;
    String namasubpekerjaan;
    String standarwaktu;

    Subpekerjaan({
        this.idsubpekerjaan,
        this.namasubpekerjaan,
        this.standarwaktu,
    });

    factory Subpekerjaan.fromJson(Map<String, dynamic> json) => Subpekerjaan(
        idsubpekerjaan: json["idsubpekerjaan"],
        namasubpekerjaan: json["namasubpekerjaan"],
        standarwaktu: json["standarwaktu"],
    );

    Map<String, dynamic> toJson() => {
        "idsubpekerjaan": idsubpekerjaan,
        "namasubpekerjaan": namasubpekerjaan,
        "standarwaktu": standarwaktu,
    };
}
</code>```

Body:
I have JSON like this

{
"status": "true",
"data": [
    {
        "idpekerjaan": "1",
        "namapekerjaan": "Apel Pagi / Sore",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "2",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "15"
            },
            {
                "idsubpekerjaan": "3",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "20"
            }
        ]
    },
    {
        "idpekerjaan": "2",
        "namapekerjaan": "Upacara",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "10",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "60"
            },
            {
                "idsubpekerjaan": "11",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "90"
            }
        ]
    },
}

Saya mempunyai fungsi-fungsi:

 class Localization {
  final List <DataPekerjaan> pekerjaan;
  final List <SubPekerjaan> subpekerjaan;

  Localization({this.pekerjaan, this.subpekerjaan});

  factory Localization.fromJson(Map<String, dynamic> json) {
    return Localization(
      subpekerjaan: parseStates(json),
      pekerjaan: parseProvinces(json),

    );
  }

  static List<SubPekerjaan> parseStates(statesJson) {

    List<DataPekerjaan> cari = parseProvinces(statesJson);
    var slist = ???????????????????? as List;
    List<SubPekerjaan> statesList =
       slist.map((data) => SubPekerjaan.fromJson(data)).toList();
    return statesList;
  }

  static List<DataPekerjaan> parseProvinces(provincesJson) {
    var plist = provincesJson['data'] as List;
    List<DataPekerjaan> provincesList =
        plist.map((data) => DataPekerjaan.fromJson(data)).toList();
    return provincesList;
  }

}

class SubPekerjaan {
  final String idSubPekerjaan;
  final String namaSubPekerjaan;
  final String standarWaktu;

  SubPekerjaan({this.idSubPekerjaan, this.namaSubPekerjaan, this.standarWaktu});

  factory SubPekerjaan.fromJson(Map<String, dynamic> parsedJson){
    return SubPekerjaan(idSubPekerjaan: parsedJson['idsubpekerjaan'], namaSubPekerjaan: parsedJson['namasubpekerjaan'], standarWaktu: parsedJson['standarwaktu']);
  }

}

class DataPekerjaan {
  final String idPekerjaan;
  final String namaPekerjaan;
  final List<String> subPekerjaan;

  DataPekerjaan({this.idPekerjaan, this.namaPekerjaan, this.subPekerjaan});

  factory DataPekerjaan.fromJson(Map<String, dynamic> parsedJson) {
    return DataPekerjaan(idPekerjaan: parsedJson['idpekerjaan'], namaPekerjaan: parsedJson['namapekerjaan'],  subPekerjaan: parsedJson["subpekerjaan"]);
  }

}

I want to retrieve the contents of an array of data and then I create a List  and then I also want to take the contents of an array of subpekerjaan so that it becomes a separate data. How can I insert each of those arrays into a function that I already have, especially in the ListparseStates (statesJson). What should I fill in the question mark?
Then is it true how I declare the data type List subPekerjaan on the DataPekerjaan class?

Body:
First your json is invalid (VAlidate at https://jsonlint.com/) it should be

{
"status": "true",
"data": [
    {
        "idpekerjaan": "1",
        "namapekerjaan": "Apel Pagi / Sore",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "2",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "15"
            },
            {
                "idsubpekerjaan": "3",
                "namasubpekerjaan": "Apel Pagi/Sore",
                "standarwaktu": "20"
            }
        ]
    },
    {
        "idpekerjaan": "2",
        "namapekerjaan": "Upacara",
        "subpekerjaan": [
            {
                "idsubpekerjaan": "10",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "60"
            },
            {
                "idsubpekerjaan": "11",
                "namasubpekerjaan": "Upacara",
                "standarwaktu": "90"
            }
        ]
    }
    ]
}

Now try with class

// To parse this JSON data, do
//
//     final myModel = myModelFromJson(jsonString);

import 'dart:convert';

MyModel myModelFromJson(String str) => MyModel.fromJson(json.decode(str));

String myModelToJson(MyModel data) => json.encode(data.toJson());

class MyModel {
    String status;
    List<Datum> data;

    MyModel({
        this.status,
        this.data,
    });

    factory MyModel.fromJson(Map<String, dynamic> json) => MyModel(
        status: json["status"],
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "status": status,
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
    };
}

class Datum {
    String idpekerjaan;
    String namapekerjaan;
    List<Subpekerjaan> subpekerjaan;

    Datum({
        this.idpekerjaan,
        this.namapekerjaan,
        this.subpekerjaan,
    });

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        idpekerjaan: json["idpekerjaan"],
        namapekerjaan: json["namapekerjaan"],
        subpekerjaan: List<Subpekerjaan>.from(json["subpekerjaan"].map((x) => Subpekerjaan.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "idpekerjaan": idpekerjaan,
        "namapekerjaan": namapekerjaan,
        "subpekerjaan": List<dynamic>.from(subpekerjaan.map((x) => x.toJson())),
    };
}

class Subpekerjaan {
    String idsubpekerjaan;
    String namasubpekerjaan;
    String standarwaktu;

    Subpekerjaan({
        this.idsubpekerjaan,
        this.namasubpekerjaan,
        this.standarwaktu,
    });

    factory Subpekerjaan.fromJson(Map<String, dynamic> json) => Subpekerjaan(
        idsubpekerjaan: json["idsubpekerjaan"],
        namasubpekerjaan: json["namasubpekerjaan"],
        standarwaktu: json["standarwaktu"],
    );

    Map<String, dynamic> toJson() => {
        "idsubpekerjaan": idsubpekerjaan,
        "namasubpekerjaan": namasubpekerjaan,
        "standarwaktu": standarwaktu,
    };
}


问:
ERROR in Cannot find module 'node-sass'
Config: macOS High Sierra, version 10.13.2, node:v8.1.2 npm:5.0.3
When I run npm start in my angularjs project I get this error:

```<code>ERROR in Cannot find module 'node-sass'
</code>```

After this I run:

```<code>npm i node-sass
</code>```

Now I get this error:

```<code>gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
</code>```

Why won't npm install node-sass? How can I install node-sass?

答:
I had the same error when installing dependencies in Angular. I've tried aforementioned techniques but none of them worked until I've deleted package-lock.json which was previously created when running Node v11.

Now I'm using Node v12 so this is how I got resolved.

I repeat if you have package-lock.json delete it, file and then install dependencies.

Title: ERROR in Cannot find module 'node-sass'

Body:
Config: macOS High Sierra, version 10.13.2, node:v8.1.2 npm:5.0.3
When I run npm start in my angularjs project I get this error:

ERROR in Cannot find module 'node-sass'

After this I run:

npm i node-sass

Now I get this error:

gyp: No Xcode or CLT version detected!
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1

Why won't npm install node-sass? How can I install node-sass?


问:
SQL behaviour when executing queries with conjunctions
If I have a SQL query that is performing an existence check against three tables:

```<code>IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
    AND EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    AND EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')
</code>```

Does SQL Server support 'early exit' for conditional statements, such that if the initial exists check against [Table1] returns false, the remaining two exists checks are not executed?

Assuming Microsoft SQL Server as the backend, what locking behaviour would I expect to see on the three referenced tables, again assuming that the initial exists check against Table1 will return false?

Some basic testing using functions instead of actual queries would suggest that 'early exit' is supported, but lock analysis during query execution also suggests that a lock is acquired on all three tables which contradicts the 'early exit' findings.

Does SQL Server acquire a lock on all tables in a query, just in case it needs them later on?

答: SQL Server does not short-curcuit.  All parts of the statement have to be evaluated and all relevant locks taken while executing the query.</p>

Body:
If I have a SQL query that is performing an existence check against three tables:

IF EXISTS(SELECT [KEY] FROM [Table1] WHERE [KEY]='Key1')
    AND EXISTS(SELECT [KEY] FROM [Table2] WHERE [KEY]='Key2')
    AND EXISTS(SELECT [KEY] FROM [Table3] WHERE [KEY]='Key3')

Does SQL Server support 'early exit' for conditional statements, such that if the initial exists check against [Table1] returns false, the remaining two exists checks are not executed?

Assuming Microsoft SQL Server as the backend, what locking behaviour would I expect to see on the three referenced tables, again assuming that the initial exists check against Table1 will return false?

Some basic testing using functions instead of actual queries would suggest that 'early exit' is supported, but lock analysis during query execution also suggests that a lock is acquired on all three tables which contradicts the 'early exit' findings.

Does SQL Server acquire a lock on all tables in a query, just in case it needs them later on?


问:
Is Heroku rewrites Spring Boot's spring.datasource.url, spring.datasource.username and spring.datasource.password properties?
I have spring boot app (https://github.com/trip2gafa/street-art) with JDBC configured in it.

In application.yml file, I have these configurations:

```<code>datasource:
    url: jdbc:postgresql://localhost:5432/street-art-db
    username: street-art
    password: street-art
</code>```

Application.yml file: https://github.com/trip2gafa/street-art/blob/master/src/main/resources/application.yml

But, database credentials in Heroku differs from credentials that I show in my application.yml file.
Does it mean that Heroku  just rewrites spring.datasource.url, spring.datasource.username and spring.datasource.password properties?

答:
In this link it's described how to configure DB in heroku.

Hope this answer will help you homie, don't be scared homie (c) Nick Diaz

Body:
I have spring boot app (https://github.com/trip2gafa/street-art) with JDBC configured in it.

In application.yml file, I have these configurations:

datasource:
    url: jdbc:postgresql://localhost:5432/street-art-db
    username: street-art
    password: street-art

Application.yml file: https://github.com/trip2gafa/street-art/blob/master/src/main/resources/application.yml

But, database credentials in Heroku differs from credentials that I show in my application.yml file.
Does it mean that Heroku  just rewrites spring.datasource.url, spring.datasource.username and spring.datasource.password properties?


问:
pandas dataframe - get a list of column names where cell has a certain value
I am currently trying to get my hands on pandas DataFrames. I have constructed a certain matrix which looks like this:

```<code>    x   y   z
A   1   0   1
B   1   1   0
C   1   0   0
D   0   1   0
</code>```

What I want to have is this (for each cell = 1, append the column name to the result per row):

```<code>A   x,z
B   x,y
C   x
D   y
</code>```

My current best solution iterates over the columns in a for loop, gets all columns with a value > 0, extracts the column names and then passes it on to my next function. However, since I have a lot of columns (>1000) the for loop is very slow and I am sure there is a better way which I cannot figure out. Can you give me a helping hand?

答:
Use if there are only 1 and 0 values use matrix multiplication DataFrame.dot with columns names and last remove separator by Series.str.rstrip:

```<code>df['new'] = df.dot(df.columns + ',').str.rstrip(',')
print (df)
   x  y  z  new
A  1  0  1  x,z
B  1  1  0  x,y
C  1  0  0    x
D  0  1  0    y
</code>```

If possible some another integers and is necessary test for greater like 0 by DataFrame.gt use:

```<code>df['new'] = df.gt(0).dot(df.columns + ',').str.rstrip(',')
</code>```

Body:
I am currently trying to get my hands on pandas DataFrames. I have constructed a certain matrix which looks like this:

    x   y   z
A   1   0   1
B   1   1   0
C   1   0   0
D   0   1   0

What I want to have is this (for each cell = 1, append the column name to the result per row):

A   x,z
B   x,y
C   x
D   y

My current best solution iterates over the columns in a for loop, gets all columns with a value > 0, extracts the column names and then passes it on to my next function. However, since I have a lot of columns (>1000) the for loop is very slow and I am sure there is a better way which I cannot figure out. Can you give me a helping hand?

Body:
Use if there are only 1 and 0 values use matrix multiplication DataFrame.dot with columns names and last remove separator by Series.str.rstrip:

df['new'] = df.dot(df.columns + ',').str.rstrip(',')
print (df)
   x  y  z  new
A  1  0  1  x,z
B  1  1  0  x,y
C  1  0  0    x
D  0  1  0    y

If possible some another integers and is necessary test for greater like 0 by DataFrame.gt use:

df['new'] = df.gt(0).dot(df.columns + ',').str.rstrip(',')


问:
How to show size and colors separately in shoplify?
I want to display colors and sizes separately on frontend to filter the collection in shopify. But when I do, it shows color and size in same variable with slash in it.

Here is the image

Here is the code that i try

```<code>      <div class="size-filter clearfix mt-4">
         <h4>SIZE</h4>
         <hr>
         {% assign available_sizes = '' %}
         {% for product in collections.frontpage.products limit: limit %}
         {% for variant in product.variants %}
         {% if variant.title != 'Default Title' %}
         {% unless available_sizes contains variant.title %}
         {% if  variant.available %}
         {% capture available_sizes %}{{ available_sizes }}, {{ variant.title }}{% endcapture %}
         <div class="form-check">
            <input class="form-check-input coll-filter" type="checkbox" value="{{variant.title}}" id=""
            {% if current_tags contains tag %} checked  {%endif%}>
            <label class="form-check-label" for="">
            {{variant.title}}
            </label>
         </div>
         {% endif %}
         {% endunless %}
         {% endif %}
         {% endfor %}
         {% endfor %}
      </div>
</code>```

Please help me to fix this error, i stuck here from last 3 days.

Error Solved but got this output:

答:
You can do use the options_with_values object:

```<code>{% for product_option in product.options_with_values %}
  <h5>{{ product_option.name }}</h5>
  {% for value in product_option.values %}
    <input id="{{product_option|handle}}-{{value|handle}}" type="checkbox" value="{{ value }}" />
    <label for="{{product_option|handle}}-{{value|handle}}"></label>
  {% endfor %}
{% endfor %}
</code>```

But you will need to write some Javascript in order to tie it to the main select which holds the variants ids.

Body:
I want to display colors and sizes separately on frontend to filter the collection in shopify. But when I do, it shows color and size in same variable with slash in it.

Here is the image

Here is the code that i try

SIZE

         {% assign available_sizes = '' %}
         {% for product in collections.frontpage.products limit: limit %}
         {% for variant in product.variants %}
         {% if variant.title != 'Default Title' %}
         {% unless available_sizes contains variant.title %}
         {% if  variant.available %}
         {% capture available_sizes %}{{ available_sizes }}, {{ variant.title }}{% endcapture %}

            <input class="form-check-input coll-filter" type="checkbox" value="{{variant.title}}" id=""
            {% if current_tags contains tag %} checked  {%endif%}>

            {{variant.title}}

         {% endif %}
         {% endunless %}
         {% endif %}
         {% endfor %}
         {% endfor %}

Please help me to fix this error, i stuck here from last 3 days.

Error Solved but got this output:

Body:
You can do use the options_with_values object:

{% for product_option in product.options_with_values %}
  <h5>{{ product_option.name }}</h5>
  {% for value in product_option.values %}
    <input id="{{product_option|handle}}-{{value|handle}}" type="checkbox" value="{{ value }}" />
    <label for="{{product_option|handle}}-{{value|handle}}"></label>
  {% endfor %}
{% endfor %}

But you will need to write some Javascript in order to tie it to the main select which holds the variants ids.