问:
Question about combo box and labels
I have a combo box that contains 5 items. I have one label on the window. What i would like to do is whenever a user clicks on one of the items in the combobox, text will populate that label. I would like to show information about whichever item is selected (IP address, etc.). Any help is appreciated. Thanks.

Code:

```<code>private void cmbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Combo box selection changed. Re-bind data
    string selectedGroup = (string)cmbGroups.SelectedItem;
    BindGrid(selectedGroup);
}
</code>```

Code:

```<code>    private void BindGrid(string selectedGroup)
    {
        //Re-bind the grid
        dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;

        InitializeColumns();
    }
</code>```

Code:

```<code>private void _UpdatePortStatus()
    {
        string[] files = Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["portStatusDir"], "PortStatus.*");

        foreach (string file in files)
        {

            PortStatus ps = new PortStatus();
            ps.ReadXml(new StreamReader(file));
            //ps.ReadXml(new FileStream(file, FileMode.Open, FileAccess.Read));

            if (!_dicPortStatus.ContainsKey(ps.General[0].Group))
            {
                _dicPortStatus.Add(ps.General[0].Group, ps);
            }

            PortStatus psOrig = _dicPortStatus[ps.General[0].Group];

            foreach (PortStatus.PortstatusRow psr in ps.Portstatus.Rows)
            {
                DataRow[] drs = psOrig.Portstatus.Select("PortNumber = '" + psr.PortNumber + "'");

                if (drs.Length == 1)
                {
                    DateTime curDt = DateTime.Parse(drs[0]["LastUpdateDateTimeUTC"].ToString());
                    DateTime newDt = psr.LastUpdateDateTimeUTC;

                    if (newDt > curDt)
                    {
                        drs[0]["LastUpdateDateTimeUTC"] = newDt;
                    }
                }
                else if (drs.Length == 0)
                {
                    psOrig.Portstatus.ImportRow(psr);
                }
                else
                {
                    throw new Exception("More than one of the same portnumber on PortStatus file: " + file);
                }
            }
        }

        foreach (string groupName in _dicPortStatus.Keys)
        {
            if (!cmbGroups.Items.Contains(groupName))
            {
                cmbGroups.Items.Add(groupName);
                cmbGroups.SelectedItem = groupName;
            }
        }
</code>```

Code:

```<code>private Dictionary<string, PortStatus> _dicPortStatus = new Dictionary<string, PortStatus>()
</code>```

答:
```<code><ComboBox Name="ComboBox1">
...
<ComboBox />

<Label Text="{Binding ElementName=ComboBox1, Path=SelectedItem}" />
</code>```

--EDIT--

Extended Example:

```<code>    <StackPanel>
        <ComboBox Name="ComboBox1"
                  DisplayMemberPath="FirstName"></ComboBox>
        <StackPanel DataContext="{Binding ElementName=ComboBox1, Path=SelectedValue}">
            <Label Content="{Binding FirstName}" />
            <Label Content="{Binding LastName}" />
            <Label Content="{Binding Age}" />
        </StackPanel>
    </StackPanel>
</code>```

Code:

```<code>        InitializeComponent();

        ObservableCollection<Person> persons = new ObservableCollection<Person>() {
            new Person(){ FirstName = "John", LastName = "Doe", Age = 25 },
            new Person(){ FirstName = "John", LastName = "Smith", Age = 35 },
            new Person(){ FirstName = "Susan", LastName = "Smith", Age = 31 },
            new Person(){ FirstName = "Anthony", LastName = "Jones", Age = 31 },
        };

        ComboBox1.ItemsSource = persons;
</code>```

Class:

```<code>public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public Int32 Age { get; set; }
}
</code>```

--EDIT:2--

Create a new class:

```<code>class GroupInfo
{
    public String GroupName { get; set; }
    public String IP { get; set; }
}
</code>```

And change your code to following:

```<code>    foreach (string groupName in _dicPortStatus.Keys)
    {
        if (!cmbGroups.Items.Contains(groupName))
        {
            cmbGroups.Items.Add(new GroupInfo(){ GroupName = groupName, IP = <Write Code to get IP>);
            cmbGroups.SelectedItem = groupName;
        }
    }
</code>```

Change XAML to following:

```<code><ComboBox Name="ComboBox1" DisplayMemberPath="GroupName">
    ...
<ComboBox />

<Label Text="{Binding ElementName=ComboBox1, Path=SelectedItem.IP}" />
</code>```

Title: Question about combo box and labels

Body:
I have a combo box that contains 5 items. I have one label on the window. What i would like to do is whenever a user clicks on one of the items in the combobox, text will populate that label. I would like to show information about whichever item is selected (IP address, etc.). Any help is appreciated. Thanks.

Code:

private void cmbGroups_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Combo box selection changed. Re-bind data
    string selectedGroup = (string)cmbGroups.SelectedItem;
    BindGrid(selectedGroup);
}

Code:

    private void BindGrid(string selectedGroup)
    {
        //Re-bind the grid
        dgPortStatus.DataContext = _dicPortStatus[selectedGroup].Portstatus.DefaultView;

        InitializeColumns();
    }

Code:

private void _UpdatePortStatus()
    {
        string[] files = Directory.GetFiles(System.Configuration.ConfigurationSettings.AppSettings["portStatusDir"], "PortStatus.*");

        foreach (string file in files)
        {

            PortStatus ps = new PortStatus();
            ps.ReadXml(new StreamReader(file));
            //ps.ReadXml(new FileStream(file, FileMode.Open, FileAccess.Read));

            if (!_dicPortStatus.ContainsKey(ps.General[0].Group))
            {
                _dicPortStatus.Add(ps.General[0].Group, ps);
            }

            PortStatus psOrig = _dicPortStatus[ps.General[0].Group];

            foreach (PortStatus.PortstatusRow psr in ps.Portstatus.Rows)
            {
                DataRow[] drs = psOrig.Portstatus.Select("PortNumber = '" + psr.PortNumber + "'");

                if (drs.Length == 1)
                {
                    DateTime curDt = DateTime.Parse(drs[0]["LastUpdateDateTimeUTC"].ToString());
                    DateTime newDt = psr.LastUpdateDateTimeUTC;

                    if (newDt > curDt)
                    {
                        drs[0]["LastUpdateDateTimeUTC"] = newDt;
                    }
                }
                else if (drs.Length == 0)
                {
                    psOrig.Portstatus.ImportRow(psr);
                }
                else
                {
                    throw new Exception("More than one of the same portnumber on PortStatus file: " + file);
                }
            }
        }

        foreach (string groupName in _dicPortStatus.Keys)
        {
            if (!cmbGroups.Items.Contains(groupName))
            {
                cmbGroups.Items.Add(groupName);
                cmbGroups.SelectedItem = groupName;
            }
        }

Code:

private Dictionary<string, PortStatus> _dicPortStatus = new Dictionary<string, PortStatus>()

Body:
<ComboBox Name="ComboBox1">
...
<ComboBox />

<Label Text="{Binding ElementName=ComboBox1, Path=SelectedItem}" />

--EDIT--

Extended Example:

    <StackPanel>
        <ComboBox Name="ComboBox1"
                  DisplayMemberPath="FirstName"></ComboBox>
        <StackPanel DataContext="{Binding ElementName=ComboBox1, Path=SelectedValue}">
            <Label Content="{Binding FirstName}" />
            <Label Content="{Binding LastName}" />
            <Label Content="{Binding Age}" />
        </StackPanel>
    </StackPanel>

Code:

        InitializeComponent();

        ObservableCollection<Person> persons = new ObservableCollection<Person>() {
            new Person(){ FirstName = "John", LastName = "Doe", Age = 25 },
            new Person(){ FirstName = "John", LastName = "Smith", Age = 35 },
            new Person(){ FirstName = "Susan", LastName = "Smith", Age = 31 },
            new Person(){ FirstName = "Anthony", LastName = "Jones", Age = 31 },
        };

        ComboBox1.ItemsSource = persons;

Class:

public class Person
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public Int32 Age { get; set; }
}

--EDIT:2--

Create a new class:

class GroupInfo
{
    public String GroupName { get; set; }
    public String IP { get; set; }
}

And change your code to following:

    foreach (string groupName in _dicPortStatus.Keys)
    {
        if (!cmbGroups.Items.Contains(groupName))
        {
            cmbGroups.Items.Add(new GroupInfo(){ GroupName = groupName, IP = <Write Code to get IP>);
            cmbGroups.SelectedItem = groupName;
        }
    }

Change XAML to following:

<ComboBox Name="ComboBox1" DisplayMemberPath="GroupName">
    ...
<ComboBox />

<Label Text="{Binding ElementName=ComboBox1, Path=SelectedItem.IP}" />


来源: stackexchange

问:
Compiler warnings are not showing in basic4andriod ide
my log in the IDE is not working well. i cant see synthax errors, warnings etc.

here is a screenshot

The first circled area is a sample synthax error that is supposed to produce warnings in the log window circled to the right.

答: Try changing from Release to Debug mode</p>

ContentLicense: CC BY-SA 3.0

Body: Try changing from Release to Debug mode


问:
How can I connect to CockroachDB from outside the Kubernetes cluster?
I've set up and deployed a Kubernetes stateful set containing three CockroachDB pods, as per docs. My ultimate objective is to query the database without requiring use of kubectl. My intermediate objective is to query the database without actually shelling into the database pod.

I forwarded a port from a pod to my local machine, and attempted to connect:

```<code>$ kubectl port-forward cockroachdb-0 26257
Forwarding from 127.0.0.1:26257 -> 26257
Forwarding from [::1]:26257 -> 26257

# later, after attempting to connect:
Handling connection for 26257
E0607 16:32:20.047098   80112 portforward.go:329] an error occurred forwarding 26257 -> 26257: error forwarding port 26257 to pod cockroachdb-0_mc-red, uid : exit status 1: 2017/06/07 04:32:19 socat[40115] E connect(5, AF=2 127.0.0.1:26257, 16): Connection refused

$ cockroach node ls --insecure --host localhost --port 26257
Error: unable to connect or connection lost.

Please check the address and credentials such as certificates (if attempting to
communicate with a secure cluster).

rpc error: code = Internal desc = transport is closing
Failed running "node"
</code>```

Anyone manage to accomplish this?

答:
From inside the Kubernetes cluster, you can talk to the database by connecting the cockroachdb-public DNS name. In the docs, that corresponds to the example command:

```<code>kubectl run cockroachdb -it --image=cockroachdb/cockroach --rm --restart=Never -- sql --insecure --host=cockroachdb-public
</code>```

While that command is using the CockroachDB image, any Postgres client driver you use should be able to connect to cockroachdb-public when running with the Kubernetes cluster.

Connecting to the database from outside of the Kubernetes cluster will require exposing the cockroachdb-public service. The details will depend somewhat on how your Kubernetes cluster was deployed, so I'd recommend checking out their docs on that:
https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#exposing-the-service

And in case you're curious, the reason forwarding port 26257 isn't working for you is because port forwarding from a pod only works if the process in the pod is listening on localhost, but the CockroachDB process in the statefulset configuration is set up to listen on the pod's hostname (as configured via the --host flag).

Body:
I've set up and deployed a Kubernetes stateful set containing three CockroachDB pods, as per docs. My ultimate objective is to query the database without requiring use of kubectl. My intermediate objective is to query the database without actually shelling into the database pod.

I forwarded a port from a pod to my local machine, and attempted to connect:

$ kubectl port-forward cockroachdb-0 26257
Forwarding from 127.0.0.1:26257 -> 26257
Forwarding from [::1]:26257 -> 26257

# later, after attempting to connect:
Handling connection for 26257
E0607 16:32:20.047098   80112 portforward.go:329] an error occurred forwarding 26257 -> 26257: error forwarding port 26257 to pod cockroachdb-0_mc-red, uid : exit status 1: 2017/06/07 04:32:19 socat[40115] E connect(5, AF=2 127.0.0.1:26257, 16): Connection refused

$ cockroach node ls --insecure --host localhost --port 26257
Error: unable to connect or connection lost.

Please check the address and credentials such as certificates (if attempting to
communicate with a secure cluster).

rpc error: code = Internal desc = transport is closing
Failed running "node"

Anyone manage to accomplish this?

Body:
From inside the Kubernetes cluster, you can talk to the database by connecting the cockroachdb-public DNS name. In the docs, that corresponds to the example command:

kubectl run cockroachdb -it --image=cockroachdb/cockroach --rm --restart=Never -- sql --insecure --host=cockroachdb-public

While that command is using the CockroachDB image, any Postgres client driver you use should be able to connect to cockroachdb-public when running with the Kubernetes cluster.

Connecting to the database from outside of the Kubernetes cluster will require exposing the cockroachdb-public service. The details will depend somewhat on how your Kubernetes cluster was deployed, so I'd recommend checking out their docs on that:
https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#exposing-the-service

And in case you're curious, the reason forwarding port 26257 isn't working for you is because port forwarding from a pod only works if the process in the pod is listening on localhost, but the CockroachDB process in the statefulset configuration is set up to listen on the pod's hostname (as configured via the --host flag).


问:
How to stop the black screens when navigating from one activity to another in xamarin android mono
I am working in a project where many black screens are appearing while I am navigating from one activity to another activity in. our application is completely based on net so for every activity there is some API calling in background hope this is the problem of all and also implemented page loading but that did not solve the problem. I had not got the reason of the black screens during the navigation between the activities. Can help me with the reason of that and solution for solving the problem.</p>

答:
When you navigating from one Activity to another, if your layout file is too large or your Activity load too much data when your Activity is Created, your Activity will first show the default black background. You can solve the problem by modifying the style of the Activity :

```<code>    <style name="MyTheme" parent="@android:style/Theme">
        <item name="android:windowIsTranslucent">true</item>
    </style>
</code>```

Use it in Activity you want navigate to :

```<code> [Activity(Label = "Activity1", Theme = "@style/MyTheme")]
</code>```

Body:
When you navigating from one Activity to another, if your layout file is too large or your Activity load too much data when your Activity is Created, your Activity will first show the default black background. You can solve the problem by modifying the style of the Activity :

    <style name="MyTheme" parent="@android:style/Theme">
        <item name="android:windowIsTranslucent">true</item>
    </style>

Use it in Activity you want navigate to :

 [Activity(Label = "Activity1", Theme = "@style/MyTheme")]


问:
Pip Install Twisted Error 1
When using pip install Twisted in virtualenv on Mac osx 10.9.4, I get this result:

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/9r/3b500gbs3093ms87mqqbckr80000gn/T/pip-build-doynftp7/twisted/

I am not sure how to resolve. I used easy_install, but I get a SSL verification issue. Anyone have similar issue? The rest of error message is below.

```<code> Collecting twisted
 Using cached Twisted-16.6.0.tar.bz2
 Complete output from command python setup.py egg_info:
Download error on https://pypi.python.org/simple/incremental/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
Couldn't find index page for 'incremental' (maybe misspelled?)
Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
No local packages or working download links found for incremental>=16.10.1
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/var/folders/9r/3b500gbs3093ms87mqqbckr80000gn/T/pip-build-lqvxc68n/twisted/setup.py", line 21, in <module>
    setuptools.setup(**_setup["getSetupArgs"]())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/core.py", line 108, in setup
    _setup_distribution = dist = klass(attrs)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/dist.py", line 317, in __init__
    self.fetch_build_eggs(attrs['setup_requires'])
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/dist.py", line 372, in fetch_build_eggs
    replace_conflicting=True,
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/pkg_resources/__init__.py", line 851, in resolve
    dist = best[req.key] = env.best_match(req, ws, installer)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1123, in best_match
    return self.obtain(req, installer)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1135, in obtain
    return installer(requirement)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/dist.py", line 440, in fetch_build_egg
    return cmd.easy_install(req)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 668, in easy_install
    raise DistutilsError(msg)
distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('incremental>=16.10.1')
 ----------------------------------------
</code>```

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/9r/3b500gbs3093ms87mqqbckr80000gn/T/pip-build-lqvxc68n/twisted/

Running openssl s_client -showcerts -connect pypi.python.org:443
 returns the following:

```<code> CONNECTED(00000003)
 depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended     Validation Server CA
 verify error:num=20:unable to get local issuer certificate
 verify return:0
 ---
 Certificate chain
  0 s:/businessCategory=Private Organization/1.3.6.1.4.1.311.60.2.1.3=US/1.3.6.1.4.1.311.60.2.1.2=Delaware/serialNumber=3359300/street=16 Allen    Rd/postalCode=03894-4801/C=US/ST=NH/L=Wolfeboro/O=Python Software Foundation/CN=www.python.org
  i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
  -----BEGIN CERTIFICATE-----
  MIIIWjCCB0KgAwIBAgIQCXCW7BLw16II/CMOsOFe/jANBgkqhkiG9w0BAQsFADB1
  ..
 -----END CERTIFICATE-----
 1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
 i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA
 -----BEGIN CERTIFICATE-----
MIIEtjCCA56gAwIBAgIQDHmpRLCMEZUgkmFf4msdgzANBgkqhkiG9w0BAQsFADBs
....
-----END CERTIFICATE-----
 Server certificate
 subject=/businessCategory=Private Organization/1.3.6.1.4.1.311.60.2.1.3=US/1.3.6.1.4.1.311.60.2.1.2=Delaware/serialNumber=3359300/street=16 Allen Rd/postalCode=03894-4801/C=US/ST=NH/L=Wolfeboro/O=Python Software Foundation/CN=www.python.org
issuer=/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended  Validation Server CA
---
No client certificate CA names sent
---
SSL handshake has read 3524 bytes and written 456 bytes
---
New, TLSv1/SSLv3, Cipher is AES128-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol  : TLSv1
Cipher    : AES128-SHA
Session-ID: BC7695FF86D2B82B20468A13E3F3E13AE23776B500E64665305EEBAF49BB54D1
Session-ID-ctx:
Master-Key:8D25B34237A3C74E90317D87BA74A2AAF0E8C424FB2ADE3D72E5F234D5E043C4527641290B928B3A22 1BE7D44116CFB1
Key-Arg   : None
Start Time: 1487035770
Timeout   : 300 (sec)
Verify return code: 0 (ok)
</code>```

答:
I had a similar problem when installing Twisted on my MacBook, after trying many different ways, I successfully install Twisted using conda.

You can try it, using either Anaconda or miniconda.

https://conda.io/docs/download.html

https://stackoverflow.com/a/20994790/1294704

Title: Pip Install Twisted Error 1

Body:
When using pip install Twisted in virtualenv on Mac osx 10.9.4, I get this result:

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/9r/3b500gbs3093ms87mqqbckr80000gn/T/pip-build-doynftp7/twisted/

I am not sure how to resolve. I used easy_install, but I get a SSL verification issue. Anyone have similar issue? The rest of error message is below.

 Collecting twisted
 Using cached Twisted-16.6.0.tar.bz2
 Complete output from command python setup.py egg_info:
Download error on https://pypi.python.org/simple/incremental/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
Couldn't find index page for 'incremental' (maybe misspelled?)
Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749) -- Some packages may not be found!
No local packages or working download links found for incremental>=16.10.1
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/private/var/folders/9r/3b500gbs3093ms87mqqbckr80000gn/T/pip-build-lqvxc68n/twisted/setup.py", line 21, in <module>
    setuptools.setup(**_setup["getSetupArgs"]())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/distutils/core.py", line 108, in setup
    _setup_distribution = dist = klass(attrs)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/dist.py", line 317, in __init__
    self.fetch_build_eggs(attrs['setup_requires'])
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/dist.py", line 372, in fetch_build_eggs
    replace_conflicting=True,
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/pkg_resources/__init__.py", line 851, in resolve
    dist = best[req.key] = env.best_match(req, ws, installer)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1123, in best_match
    return self.obtain(req, installer)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1135, in obtain
    return installer(requirement)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/dist.py", line 440, in fetch_build_egg
    return cmd.easy_install(req)
  File "/Users/Complex-Cauchy/1/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 668, in easy_install
    raise DistutilsError(msg)
distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('incremental>=16.10.1')
 ----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/9r/3b500gbs3093ms87mqqbckr80000gn/T/pip-build-lqvxc68n/twisted/

Running openssl s_client -showcerts -connect pypi.python.org:443
 returns the following:

 CONNECTED(00000003)
 depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended     Validation Server CA
 verify error:num=20:unable to get local issuer certificate
 verify return:0
 ---
 Certificate chain
  0 s:/businessCategory=Private Organization/1.3.6.1.4.1.311.60.2.1.3=US/1.3.6.1.4.1.311.60.2.1.2=Delaware/serialNumber=3359300/street=16 Allen    Rd/postalCode=03894-4801/C=US/ST=NH/L=Wolfeboro/O=Python Software Foundation/CN=www.python.org
  i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
  -----BEGIN CERTIFICATE-----
  MIIIWjCCB0KgAwIBAgIQCXCW7BLw16II/CMOsOFe/jANBgkqhkiG9w0BAQsFADB1
  ..
 -----END CERTIFICATE-----
 1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended Validation Server CA
 i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA
 -----BEGIN CERTIFICATE-----
MIIEtjCCA56gAwIBAgIQDHmpRLCMEZUgkmFf4msdgzANBgkqhkiG9w0BAQsFADBs
....
-----END CERTIFICATE-----
 Server certificate
 subject=/businessCategory=Private Organization/1.3.6.1.4.1.311.60.2.1.3=US/1.3.6.1.4.1.311.60.2.1.2=Delaware/serialNumber=3359300/street=16 Allen Rd/postalCode=03894-4801/C=US/ST=NH/L=Wolfeboro/O=Python Software Foundation/CN=www.python.org
issuer=/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert SHA2 Extended  Validation Server CA
---
No client certificate CA names sent
---
SSL handshake has read 3524 bytes and written 456 bytes
---
New, TLSv1/SSLv3, Cipher is AES128-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
Protocol  : TLSv1
Cipher    : AES128-SHA
Session-ID: BC7695FF86D2B82B20468A13E3F3E13AE23776B500E64665305EEBAF49BB54D1
Session-ID-ctx:
Master-Key:8D25B34237A3C74E90317D87BA74A2AAF0E8C424FB2ADE3D72E5F234D5E043C4527641290B928B3A22 1BE7D44116CFB1
Key-Arg   : None
Start Time: 1487035770
Timeout   : 300 (sec)
Verify return code: 0 (ok)


问:
Problem with jQuery .load method and newlines in internet Explorer
I'm trying to load plaintext data using jQuery's load method. This plaintext includes line breaks. I load this data into an HTML ``` tag.</p>

<p>It works fine in all browsers I tried (Firefox/Linux, [Firefox,Chrome,Opera]/Windows) except for Internet Explorer, where the line breaks from the original file are removed. I've tried to save the file with either Windows line-breaks and Linux line-breaks, but this makes no difference with respect to browser behavior (neither IE, which continues to misbehave, nor the others, which keep behaving).</p>

<p>This is the HTML code:</p>

```

    ``````

```

<p>This is the jQuery call:</p>

```$(function(){
    $("#data pre").load("lorem.txt");
});
```

答:
... or you can replace the text if the browser is IE:</p>

```<code>$("#data pre").load("lorem.txt", function(response, status, xhr) {
    if (status != "error") {
    if (($.browser.msie)&&(jQuery.browser.version=="8.0"))
        $("#data pre").html(response.replace(/\r\n/g, "<br>"));
    }
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to load plaintext data using jQuery's load method. This plaintext includes line breaks. I load this data into an HTML
 tag.

It works fine in all browsers I tried (Firefox/Linux, [Firefox,Chrome,Opera]/Windows) except for Internet Explorer, where the line breaks from the original file are removed. I've tried to save the file with either Windows line-breaks and Linux line-breaks, but this makes no difference with respect to browser behavior (neither IE, which continues to misbehave, nor the others, which keep behaving).

This is the HTML code:

This is the jQuery call:

$(function(){
    $("#data pre").load("lorem.txt");
});

Body:
... or you can replace the text if the browser is IE:

$("#data pre").load("lorem.txt", function(response, status, xhr) {
    if (status != "error") {
    if (($.browser.msie)&&(jQuery.browser.version=="8.0"))
        $("#data pre").html(response.replace(/\r\n/g, "<br>"));
    }
});


问:
Save SVG as PNG using javascript Unknown DOM exception
I am trying to convert an SVG to PNG through browser using javascript

I've been following the answer on this question Save inline SVG as JPEG/PNG/SVG

It works for the given XML in that answer
Unfortunately, I got Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. when trying to convert my SVG. Here's the snippet to my code. Can anybody tell me why it's not working?

var btn = document.querySelector('button');
var svg = document.querySelector('svg');
var canvas = document.querySelector('canvas');

function triggerDownload (imgURI) {
  var evt = new MouseEvent('click', {
    view: window,
    bubbles: false,
    cancelable: true
  });

  var a = document.createElement('a');
  a.setAttribute('download', 'MY_COOL_IMAGE.png');
  a.setAttribute('href', imgURI);
  a.setAttribute('target', '_blank');

  a.dispatchEvent(evt);
}

btn.addEventListener('click', function () {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var data = (new XMLSerializer()).serializeToString(svg);
  var DOMURL = window.URL || window.webkitURL || window;

  var img = new Image();
  img.crossOrigin = 'anonymous'

  var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  var url = DOMURL.createObjectURL(svgBlob);

  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);

    var imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

    triggerDownload(imgURI);
  };

  img.src = url;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>svg to png</button>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="161px" height="91px" version="1.1" style="background-color: rgb(255, 255, 255);"><defs/><g transform="translate(0.5,0.5)"><rect x="0" y="0" width="160" height="90" fill="#ffffff" stroke="#000000" pointer-events="none"/><path d="M 0 26 L 0 0 L 160 0 L 160 26 Z" fill="#dae8fc" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(48.5,7.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="63" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; white-space: nowrap; font-weight: bold; text-align: center;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">Classname</div></div></foreignObject><text x="32" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica" font-weight="bold">Classname</text></switch></g><g transform="translate(5.5,32.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="62" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 22px; max-width: 148px; width: 63px; white-space: normal; word-wrap: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">+ field: type</div></div></foreignObject><text x="31" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ field: type</text></switch></g><path d="M 0 56 L 160 56" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(5.5,66.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="111" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility"><div xmlns="http://www.w3.org/1999/xhtml" style="display: inline-block; font-size: 12px; font-family: Helvetica; color: rgb(0, 0, 0); line-height: 1.2; vertical-align: top; overflow: hidden; max-height: 22px; max-width: 148px; width: 112px; white-space: normal; word-wrap: normal;"><div xmlns="http://www.w3.org/1999/xhtml" style="display:inline-block;text-align:inherit;text-decoration:inherit;">+ method(type): type</div></div></foreignObject><text x="56" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ method(type): type</text></switch></g></g></svg>

<canvas id="canvas"></canvas></code>```

答:
You have issues in your SVG's foreignObject on removing this will solve your issue,

var btn = document.querySelector('button');
var svg = document.querySelector('svg');
var canvas = document.querySelector('canvas');

function triggerDownload (imgURI) {
  var evt = new MouseEvent('click', {
    view: window,
    bubbles: false,
    cancelable: true
  });

  var a = document.createElement('a');
  a.setAttribute('download', 'MY_COOL_IMAGE.png');
  a.setAttribute('href', imgURI);
  a.setAttribute('target', '_blank');

  a.dispatchEvent(evt);
}

btn.addEventListener('click', function () {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var data = (new XMLSerializer()).serializeToString(svg);
  var DOMURL = window.URL || window.webkitURL || window;

  var img = new Image();
  img.crossOrigin = 'anonymous'

  var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  var url = DOMURL.createObjectURL(svgBlob);

  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);

    var imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

    triggerDownload(imgURI);
  };

  img.src = url;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>svg to png</button>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="161px" height="91px" version="1.1" style="background-color: rgb(255, 255, 255);">
<defs/>
<g transform="translate(0.5,0.5)">
<rect x="0" y="0" width="160" height="90" fill="#ffffff" stroke="#000000" pointer-events="none"/>
<path d="M 0 26 L 0 0 L 160 0 L 160 26 Z" fill="#dae8fc" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/>
<g transform="translate(48.5,7.5)">
<switch>

<text x="32" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica" font-weight="bold">Classname</text>
</switch>
</g>
<g transform="translate(5.5,32.5)">
<switch>

<text x="31" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ field: type</text>
</switch>
</g>
<path d="M 0 56 L 160 56" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(5.5,66.5)">
<switch>

<text x="56" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ method(type): type</text>
</switch>
</g>
</g>
</svg>

<canvas id="canvas"></canvas></code>```

You can also try Canvas2Image plugin

Body:
I am trying to convert an SVG to PNG through browser using javascript

I've been following the answer on this question Save inline SVG as JPEG/PNG/SVG

It works for the given XML in that answer
Unfortunately, I got Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported. when trying to convert my SVG. Here's the snippet to my code. Can anybody tell me why it's not working?

var btn = document.querySelector('button');
var svg = document.querySelector('svg');
var canvas = document.querySelector('canvas');

function triggerDownload (imgURI) {
  var evt = new MouseEvent('click', {
    view: window,
    bubbles: false,
    cancelable: true
  });

  var a = document.createElement('a');
  a.setAttribute('download', 'MY_COOL_IMAGE.png');
  a.setAttribute('href', imgURI);
  a.setAttribute('target', '_blank');

  a.dispatchEvent(evt);
}

btn.addEventListener('click', function () {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var data = (new XMLSerializer()).serializeToString(svg);
  var DOMURL = window.URL || window.webkitURL || window;

  var img = new Image();
  img.crossOrigin = 'anonymous'

  var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  var url = DOMURL.createObjectURL(svgBlob);

  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);

    var imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

    triggerDownload(imgURI);
  };

  img.src = url;
});

<button>svg to png</button>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="161px" height="91px" version="1.1" style="background-color: rgb(255, 255, 255);"><defs/><g transform="translate(0.5,0.5)"><rect x="0" y="0" width="160" height="90" fill="#ffffff" stroke="#000000" pointer-events="none"/><path d="M 0 26 L 0 0 L 160 0 L 160 26 Z" fill="#dae8fc" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(48.5,7.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="63" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">

Classname

</foreignObject><text x="32" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica" font-weight="bold">Classname</text></switch></g><g transform="translate(5.5,32.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="62" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">

+ field: type

</foreignObject><text x="31" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ field: type</text></switch></g><path d="M 0 56 L 160 56" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(5.5,66.5)"><switch><foreignObject style="overflow:visible;" pointer-events="all" width="111" height="12" requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility">

+ method(type): type

</foreignObject><text x="56" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ method(type): type</text></switch></g></g></svg>

<canvas id="canvas"></canvas>

Body:
You have issues in your SVG's foreignObject on removing this will solve your issue,

var btn = document.querySelector('button');
var svg = document.querySelector('svg');
var canvas = document.querySelector('canvas');

function triggerDownload (imgURI) {
  var evt = new MouseEvent('click', {
    view: window,
    bubbles: false,
    cancelable: true
  });

  var a = document.createElement('a');
  a.setAttribute('download', 'MY_COOL_IMAGE.png');
  a.setAttribute('href', imgURI);
  a.setAttribute('target', '_blank');

  a.dispatchEvent(evt);
}

btn.addEventListener('click', function () {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var data = (new XMLSerializer()).serializeToString(svg);
  var DOMURL = window.URL || window.webkitURL || window;

  var img = new Image();
  img.crossOrigin = 'anonymous'

  var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  var url = DOMURL.createObjectURL(svgBlob);

  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);

    var imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

    triggerDownload(imgURI);
  };

  img.src = url;
});

<button>svg to png</button>

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="161px" height="91px" version="1.1" style="background-color: rgb(255, 255, 255);">
<defs/>
<g transform="translate(0.5,0.5)">
<rect x="0" y="0" width="160" height="90" fill="#ffffff" stroke="#000000" pointer-events="none"/>
<path d="M 0 26 L 0 0 L 160 0 L 160 26 Z" fill="#dae8fc" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/>
<g transform="translate(48.5,7.5)">
<switch>

<text x="32" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica" font-weight="bold">Classname</text>
</switch>
</g>
<g transform="translate(5.5,32.5)">
<switch>

<text x="31" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ field: type</text>
</switch>
</g>
<path d="M 0 56 L 160 56" fill="none" stroke="#000000" stroke-miterlimit="10" pointer-events="none"/><g transform="translate(5.5,66.5)">
<switch>

<text x="56" y="12" fill="#000000" text-anchor="middle" font-size="12px" font-family="Helvetica">+ method(type): type</text>
</switch>
</g>
</g>
</svg>

<canvas id="canvas"></canvas>

You can also try Canvas2Image plugin


问:
Why use only static classes to test rest endpoints while using Jersey Test?
I have been using JerseyTest framework to test endpoints in my application. I am fairly new to this.

I studied a few other test cases written by other developers of my company. They do not test the Resource class directly but rather write a static class within the test case and test the static class.

Even in the Jersey Guide, I notice examples of only testing static classes.

I do not understand the purpose of writing test cases like this because my goal was to test my resource class so what will we achieve if we write a static class and test that?

Class to be tested is below

```<code>class SomeController {

@Post
@path("/someResponse")
private SomeResponseObject doSomeWork(@NotNull SomeObjectParameter parameter) {
   //Code for processing request and prepares the response object
   return someResponseObject;
}
}
</code>```

But the class tested within the unit test class

```<code>public class SomeControllerTest extends JerseyTest {

@Path("/path")
public static class ControllerResource {
    @Post
    public SomeResponseObject getSomeWork() {
        //Prepared SomeResponseObject
        return someResponseObject;
    }
}

@Override
protected Application configure() {
    return new ResourceConfig(ControllerResource.class);
}

@Test
public void test() {
    SomeResponseObject response = target("hello").request().post(SomeResponseObject.class);
    //Do assertions
}
}
</code>```

Now if you notice the Configure method, the class that is added is the static class that is created within the test class rather than the class to be tested which is SomeController.class

What is the point of writing the unit test here if we are not testing the SomeController class? What are we trying to achieve?

答:
It's because Jersey can't create it if it's not static. You are passing a class to the ResourceConfig, so you are telling Jersey to create an instance of it. If you just register it as an instance, then it doesn't need to be static, since Jersey will not need to create the instance.

```<code> return new ResourceConfig()
     .register(new ControllerResource());
</code>```

I don't think that not being able to create it is something that is specific to Jersey. It's more related to Java. All the other frameworks that I can think of that I've used inner classes for, it's the same thing, like Spring and Jackson. Inner classes need to be static for the framework to create the instance.

As an aside though, there is never really any reason to have the resource as an inner class of the test. I post many examples using Jersey Test Framework, and the only reason I use inner resource classes in the test is the make the example self-contained and runnable as-is. Normally your resource class would be in a separate file, where there is no need for static.

Body:
I have been using JerseyTest framework to test endpoints in my application. I am fairly new to this.

I studied a few other test cases written by other developers of my company. They do not test the Resource class directly but rather write a static class within the test case and test the static class.

Even in the Jersey Guide, I notice examples of only testing static classes.

I do not understand the purpose of writing test cases like this because my goal was to test my resource class so what will we achieve if we write a static class and test that?

Class to be tested is below

class SomeController {

@Post
@path("/someResponse")
private SomeResponseObject doSomeWork(@NotNull SomeObjectParameter parameter) {
   //Code for processing request and prepares the response object
   return someResponseObject;
}
}

But the class tested within the unit test class

public class SomeControllerTest extends JerseyTest {

@Path("/path")
public static class ControllerResource {
    @Post
    public SomeResponseObject getSomeWork() {
        //Prepared SomeResponseObject
        return someResponseObject;
    }
}

@Override
protected Application configure() {
    return new ResourceConfig(ControllerResource.class);
}

@Test
public void test() {
    SomeResponseObject response = target("hello").request().post(SomeResponseObject.class);
    //Do assertions
}
}

Now if you notice the Configure method, the class that is added is the static class that is created within the test class rather than the class to be tested which is SomeController.class

What is the point of writing the unit test here if we are not testing the SomeController class? What are we trying to achieve?

Body:
It's because Jersey can't create it if it's not static. You are passing a class to the ResourceConfig, so you are telling Jersey to create an instance of it. If you just register it as an instance, then it doesn't need to be static, since Jersey will not need to create the instance.

 return new ResourceConfig()
     .register(new ControllerResource());

I don't think that not being able to create it is something that is specific to Jersey. It's more related to Java. All the other frameworks that I can think of that I've used inner classes for, it's the same thing, like Spring and Jackson. Inner classes need to be static for the framework to create the instance.

As an aside though, there is never really any reason to have the resource as an inner class of the test. I post many examples using Jersey Test Framework, and the only reason I use inner resource classes in the test is the make the example self-contained and runnable as-is. Normally your resource class would be in a separate file, where there is no need for static.


问:
SQL Change Data Capture get all tables
I need to audit data in all tables in database. I use SQL Server 2016. I enabled  Change Data Capture for all tables.

How to get changes from all tables chronologically?

答:
Basically the Change Data Capture creates system tables in [cdc] schema to capture change events for each table. something like cdc.[TableSchemaName]_[TableName]_CT, this table will have all the changes done to your actual table in the chronological order. It is basically the data read from DB's transaction log file.

Another point - you need to query Maximum Lsn for the database at any point of time and also the minimum LSN for the table for which you want to read change data. The records between min and max LSN should give you the total changes for a table.

Reference link below:
https://learn.microsoft.com/en-us/sql/relational-databases/system-functions/cdc-fn-cdc-get-all-changes-capture-instance-transact-sql

Title: SQL Change Data Capture get all tables


问:
MYSQL: ORDER BY table selected on the fly by user
I have a table like this:

Table: Cols

```<code> col1   col2    col3    col4
------ ------  ------  -------
  1       2       5       8
  5       4       2       7
  5       3       7       4
  7       5       4       1
</code>```

its very important what sort column be selected by user, i try something like:

```<code>    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as integer)
</code>```

or

```<code>    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as varchar(20))
</code>```

Both without errors but none correct.

If I'm out of the way, please enlighten me to get back on track.

答:
TRY :::</p>

```<code>DECLARE @OrderBy VARCHAR(10) = '/*Here, pass the column name(if multiple columns, pass column names separated by commas)*/'
DECLARE @SQLquery VARCHAR(MAX) = '
SELECT col1,Col2,Col3
FROM Cols
order by ' + @OrderBy

EXEC (@SQLquery)
</code>```

Body:
I have a table like this:

Table: Cols

 col1   col2    col3    col4
------ ------  ------  -------
  1       2       5       8
  5       4       2       7
  5       3       7       4
  7       5       4       1

its very important what sort column be selected by user, i try something like:

    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as integer)

or

    SELECT col1,Col2,Col3
    FROM Cols
    order by cast(:ORDER_ID_COL as varchar(20))

Both without errors but none correct.

If I'm out of the way, please enlighten me to get back on track.

Body:
TRY :::

DECLARE @OrderBy VARCHAR(10) = '/*Here, pass the column name(if multiple columns, pass column names separated by commas)*/'
DECLARE @SQLquery VARCHAR(MAX) = '
SELECT col1,Col2,Col3
FROM Cols
order by ' + @OrderBy

EXEC (@SQLquery)


问:
How does composition work in C#?
I have a Car Class:

```<code>public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}
</code>```

And an Engine Class:

```<code>public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}
</code>```

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

答:
Well it depends on how you want the control the accessibility/use of the Engine property.

Case 1:
If you want Car to have full control of the Engine property and no one else to access it, make it a private field and instantiate inside the Car constructor.

```<code>public class Car
{
    private readonly Engine _engine;
    public Car()
    {
        _engine = new Engine();
    }
}
</code>```

Case 2:
Engine should be accessible from outside, such that anyone can set it or access it.
It can be done in 2 ways:

1) Constructor Injection - injecting the dependency via constructor, usually abstracted using an interface so that mocking/unit testing can be done easily.

```<code>public class Car
{
    public Car(IEngine engine)
    {
        Engine = engine;
    }
    public IEngine Engine { get; set; }
}
var car = new Car(new Engine());
</code>```

2) Setting Engine property manually

```<code>public class Car
 {
    public Engine Engine { get; set; }
 }
var car = new Car();
car.Engine = new Engine();
</code>```

Title: How does composition work in C#?

Body:
I have a Car Class:

public class Car
{
    private String _Brand;
    private String _Model;
    private Engine _Engine;

    public Car(){

    }

     public String Brand
     {
        get { return _Brand; }
        set { _Brand = value; }
     }

     public String Model
     {
        get { return _Model; }
        set { _Model = value; }
     }

     public Engine Engine
     {
        get { return _Engine; }
        set { _Engine = value; }
     }
}

And an Engine Class:

public class Engine
{
     private int _Code;
     private DateTime _Year;

     public Engine(){

     }

     public int Code
     {
        get { return _Code; }
        set { _Code = value; }
     }

     public DateTime Year
     {
        get { return _Year; }
        set { _Year = value; }
     }
}

From code-behind of Registration.aspx.cs, I wanna create using a button, a Car and an Engine w/ theirs respective relationship (Composition).

However, I have a massive confusion about how a composition for these objects should be behave. I.E., I can't figure it out if I must declare: Engine = new Engine(); in Car's constructor or if in Registration Event (Button, Code-Behind) declare: Car car = new Car() and then car.Engine = new Engine();.

I don't how composition relationship work in a scenario like this. The existence of where to declare "new" is putting me in a mixing of concepts.

Regards

Body:
Well it depends on how you want the control the accessibility/use of the Engine property.

Case 1:
If you want Car to have full control of the Engine property and no one else to access it, make it a private field and instantiate inside the Car constructor.

public class Car
{
    private readonly Engine _engine;
    public Car()
    {
        _engine = new Engine();
    }
}

Case 2:
Engine should be accessible from outside, such that anyone can set it or access it.
It can be done in 2 ways:

1) Constructor Injection - injecting the dependency via constructor, usually abstracted using an interface so that mocking/unit testing can be done easily.

public class Car
{
    public Car(IEngine engine)
    {
        Engine = engine;
    }
    public IEngine Engine { get; set; }
}
var car = new Car(new Engine());

2) Setting Engine property manually

public class Car
 {
    public Engine Engine { get; set; }
 }
var car = new Car();
car.Engine = new Engine();


问:
wondering if there is an efficient way to shorten this code
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

```<code>private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}
</code>```

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

答:
Make objects and use databindings.  </p>

```<code>public class Book
{
    public BookType BookType { get; set; }
    public string Name { get; set; }
    public string Image { get; set; }
}

public enum BookType
{
    Programming,
    Networking,
    Web,
}

public partial class Form1 : Form
{
    private readonly List<Book> _books = new List<Book>
    {
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "VB" },
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "Java" },
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "C#" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "LAN Networks" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "Windows Networking" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "More About Networking" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "Web Programming" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "Javascript" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "ASP" },
    };

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var bookTypes = _books.GroupBy(b => b.BookType).Select(g => g.Key).ToList();

        this.cboBookTypes.DataSource = bookTypes;
    }

    private void cboBookTypes_SelectedIndexChanged(object sender, EventArgs e)
    {
        var bookType = (BookType)this.cboBookTypes.SelectedItem;
        var books = _books.Where(b => b.BookType == bookType).ToList();
        var img = books.First().Image;

        this.imgBook.Image = Image.FromFile(img);
        this.lstBooks.DataSource = books;
        this.lstBooks.DisplayMember = "Name";

    }
}
</code>```

Body:
So my program is going to end up being fairly large and I don't want a whole lot of code that could just be shortened. Here is one instance I am looking for some tips on:

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string books = null;
    // sets books to the clicked item
    books = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;
    // Loads string to list box and image to selectedPictureBox when programming is selected
    if (books == "Programming")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("programming.png");
        bookListBox.Items.Add("Visual Basic");
        bookListBox.Items.Add("Java");
        bookListBox.Items.Add("C#");
    }
    // Loads string to list box and image to selectedPictureBox when Networking is selected
    else if (books == "Networking")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("networking.png");
        bookListBox.Items.Add("LAN Networks");
        bookListBox.Items.Add("Windows Networking");
        bookListBox.Items.Add("More About Networking");
    }
    // Loads string to list box and image to selectedPictureBox when Web is selected
    else if (books == "Web")
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile("html.png");
        bookListBox.Items.Add("Web Programming");
        bookListBox.Items.Add("JavaScript");
        bookListBox.Items.Add("ASP");
    }
}

The code works fine but I was just hoping to get some tips on shortening this code if necessary, any input is appreciated.

Body:
Make objects and use databindings.

public class Book
{
    public BookType BookType { get; set; }
    public string Name { get; set; }
    public string Image { get; set; }
}

public enum BookType
{
    Programming,
    Networking,
    Web,
}

public partial class Form1 : Form
{
    private readonly List<Book> _books = new List<Book>
    {
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "VB" },
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "Java" },
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "C#" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "LAN Networks" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "Windows Networking" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "More About Networking" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "Web Programming" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "Javascript" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "ASP" },
    };

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var bookTypes = _books.GroupBy(b => b.BookType).Select(g => g.Key).ToList();

        this.cboBookTypes.DataSource = bookTypes;
    }

    private void cboBookTypes_SelectedIndexChanged(object sender, EventArgs e)
    {
        var bookType = (BookType)this.cboBookTypes.SelectedItem;
        var books = _books.Where(b => b.BookType == bookType).ToList();
        var img = books.First().Image;

        this.imgBook.Image = Image.FromFile(img);
        this.lstBooks.DataSource = books;
        this.lstBooks.DisplayMember = "Name";

    }
}


问:
Reading a line and assigning a default value to the variables in BASH
How do I read a row of data and assign them to variables while also giving them default values?

I wanted to achieve something like this, but can't get the syntax right.

```<code>{
read variable1=${variable1:=default1} variable2=${variable2:=default2}
read variable3=${variable3:=default3} variable4=${variable4:=default4}
} <fileList
</code>```

答:
Script (file_reader.sh)

```<code># Read in the 2 fields from the first (odd) line
while read var1 var2
do
  # Read in the 2 fields from the next (even) line
  read var3 var4

  # Set defaults
  : ${var1:=var1_default}
  : ${var2:=var2_default}
  : ${var3:=var3_default}
  : ${var4:=var4_default}

  echo "$var1 $var2 $var3 $var4"
done < foo.txt
</code>```

Input (foo.txt)

```<code>eins zwei         < line 1 (odd)
drei vier         < line 2 (even)
    < blank line
fünf
    < blank line
sechs sieben
acht
</code>```

Output

I piped the output of file_reader.sh into the column command to make the values more readable $ ./file_reader.sh | columnt -t…

```<code>eins         zwei         drei         vier
var1_default var2_default fünf         var4_default
var1_default var2_default sechs        sieben
acht         var2_default var3_default var4_default
</code>```

Body:
How do I read a row of data and assign them to variables while also giving them default values?

I wanted to achieve something like this, but can't get the syntax right.

{
read variable1=${variable1:=default1} variable2=${variable2:=default2}
read variable3=${variable3:=default3} variable4=${variable4:=default4}
} <fileList

Body:
Script (file_reader.sh)

# Read in the 2 fields from the first (odd) line
while read var1 var2
do
  # Read in the 2 fields from the next (even) line
  read var3 var4

  # Set defaults
  : ${var1:=var1_default}
  : ${var2:=var2_default}
  : ${var3:=var3_default}
  : ${var4:=var4_default}

  echo "$var1 $var2 $var3 $var4"
done < foo.txt

Input (foo.txt)

eins zwei         < line 1 (odd)
drei vier         < line 2 (even)
    < blank line
fünf
    < blank line
sechs sieben
acht

Output

I piped the output of file_reader.sh into the column command to make the values more readable $ ./file_reader.sh | columnt -t…

eins         zwei         drei         vier
var1_default var2_default fünf         var4_default
var1_default var2_default sechs        sieben
acht         var2_default var3_default var4_default


问:
PHP Echo users from login table into a select menu and then
I'm trying to echo all full names from my login table to a select menu. Once a user selects a name, i want it to pull the email address for that user from the login table and place it into an input field. When i try this, its telling me the variable is undefined.

```<code><div class="form-group">
            <label for="rep" class="col-sm-3 control-label">Change Rep</label>
            <div class="col-sm-9">
                <select class="form-control" id="rep" name="rep">
                    <option value=""></option>

    <?php include_once( "connection.php"); $result=mysqli_query($mysqli, "SELECT * FROM login  ");
                    while($res=mysqli_fetch_array($result)) { ?>
                    <option value="<?php echo $res['name']; ?>">
                        <?php echo $res[ 'name']; ?>
                    </option>
                    <?php } ?>
                </select>
            </div>
        </div>

<div class="form-group">
            <label for="reassignmentemail" class="col-sm-3 control-label">reassignmentemail</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="reassignmentemail" name="reassignmentemail">
            </div>
        </div>
</code>```

Now the ajax

```<code><script type="text/javascript">
              $(document).ready(function(){ /* PREPARE THE SCRIPT */
                $("#rep").change(function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
                  var rep = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
                  var dataString = "rep="+rep; /* STORE THAT TO A DATA STRING */

                  $.ajax({ /* THEN THE AJAX CALL */
                    type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
                    url: "get-data.php", /* PAGE WHERE WE WILL PASS THE DATA */
                    data: dataString, /* THE DATA WE WILL BE PASSING */
                    success: function(result){ /* GET THE TO BE RETURNED DATA */
                      $("#reassignmentemail").val(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
                    }
                  });

                });
              });
            </script>
</code>```

the get-data.php file

```<code>   <?php

            if(!empty($_POST["rep"])){
            $con = mysqli_connect('localhost', 'root', '', 'blog');

            $result = mysqli_query($con, "SELECT* FROM login WHERE name='$rep' ");
            if($result){
              $data = mysqli_fetch_array($result);
              echo $data[4];
            }

            }
            ?>
</code>```

its telling me that the $rep variable is not defined, any ideas?

Thanks,

答:
```<code>$result=m ysqli_query($mysqli, "SELECT * FROM login  ");
</code>```

change to this

```<code>$result=mysqli_query($mysqli, "SELECT * FROM login");
</code>```

AND in get.php

```<code>if(isset($_POST["rep"]) && !empty($_POST["rep"])){
      $rep  = $_POST["rep"];
        $con = mysqli_connect('localhost', 'root', '', 'blog');

        $result = mysqli_query($con, "SELECT* FROM login WHERE name='$rep' ");
        if($result){
          $data = mysqli_fetch_array($result);
          echo $data[4];
        }

        }
</code>```

Body:
I'm trying to echo all full names from my login table to a select menu. Once a user selects a name, i want it to pull the email address for that user from the login table and place it into an input field. When i try this, its telling me the variable is undefined.

            Change Rep

                <select class="form-control" id="rep" name="rep">
                    <option value=""></option>

    <?php include_once( "connection.php"); $result=mysqli_query($mysqli, "SELECT * FROM login  ");
                    while($res=mysqli_fetch_array($result)) { ?>
                    <option value="<?php echo $res['name']; ?>">
                        <?php echo $res[ 'name']; ?>
                    </option>
                    <?php } ?>
                </select>

            reassignmentemail

                <input type="text" class="form-control" id="reassignmentemail" name="reassignmentemail">

Now the ajax

the get-data.php file

   <?php

            if(!empty($_POST["rep"])){
            $con = mysqli_connect('localhost', 'root', '', 'blog');

            $result = mysqli_query($con, "SELECT* FROM login WHERE name='$rep' ");
            if($result){
              $data = mysqli_fetch_array($result);
              echo $data[4];
            }

            }
            ?>

its telling me that the $rep variable is not defined, any ideas?

Thanks,

Body:
$result=m ysqli_query($mysqli, "SELECT * FROM login  ");

change to this

$result=mysqli_query($mysqli, "SELECT * FROM login");

AND in get.php

if(isset($_POST["rep"]) && !empty($_POST["rep"])){
      $rep  = $_POST["rep"];
        $con = mysqli_connect('localhost', 'root', '', 'blog');

        $result = mysqli_query($con, "SELECT* FROM login WHERE name='$rep' ");
        if($result){
          $data = mysqli_fetch_array($result);
          echo $data[4];
        }

        }


问:
How can I split router.js in SailsJS
My project is getting larger and router.js is growing too. Is it possible to split it into several different route files? Each route file applies to a different controller.</p>

答:
I come from a dot net background and there Attribute routing allows users to specify explicit routes in the controller itself. This is very useful feature as When you work with a team, you cannot have one large file which keeps on growing as it increases the conflicts when code is maintained on GIT.

So i wanted a similar solution in my sails app

I did it as follows

```<code>var _ = require('lodash');
var routes = {
    'get /test':'SiteController.testme'
};
_.assignIn(sails.config.routes,routes);

module.exports = {
    testme : function(req,res){
        res.json("I have been tested");
    },
    findOne: function(req,res){
        res.json("I have got one site");
    }
};
</code>```

Here the controller name is SiteController

Title: How can I split router.js in SailsJS

Body:
I come from a dot net background and there Attribute routing allows users to specify explicit routes in the controller itself. This is very useful feature as When you work with a team, you cannot have one large file which keeps on growing as it increases the conflicts when code is maintained on GIT.

So i wanted a similar solution in my sails app

I did it as follows

var _ = require('lodash');
var routes = {
    'get /test':'SiteController.testme'
};
_.assignIn(sails.config.routes,routes);

module.exports = {
    testme : function(req,res){
        res.json("I have been tested");
    },
    findOne: function(req,res){
        res.json("I have got one site");
    }
};

Here the controller name is SiteController


答:
Note: your code is vulnerable please filter variable and do validation before use in query or use prepare statement

define variable before use it  $rep = $_POST["rep"];

Example -

```<code> <?php

    if(!empty($_POST["rep"])){
    $con = mysqli_connect('localhost', 'root', '', 'blog');
    $rep = $_POST["rep"];

    $result = mysqli_query($con, "SELECT* FROM login WHERE name='$rep' ");
    if($result){
      $data = mysqli_fetch_array($result);
      echo $data[4];
    }

    }
?>
</code>```

Title: PHP Echo users from login table into a select menu and then

Body:
Note: your code is vulnerable please filter variable and do validation before use in query or use prepare statement

define variable before use it  $rep = $_POST["rep"];

Example -

 <?php

    if(!empty($_POST["rep"])){
    $con = mysqli_connect('localhost', 'root', '', 'blog');
    $rep = $_POST["rep"];

    $result = mysqli_query($con, "SELECT* FROM login WHERE name='$rep' ");
    if($result){
      $data = mysqli_fetch_array($result);
      echo $data[4];
    }

    }
?>


问:
Tailing a local file using fileevent
I am trying to tail a file using fileevent (Should only Tcl 8.4 version, so I can't use chan command).

```<code>% proc GetData {chan} {
 set data [read $chan]
    puts "[string length $data] $data"
    if {[eof $chan]} {
        fileevent $chan readable {}
    }
}
%
%
%
%  set fp [open "|tail -f /home/dinesh/input" r+]
file7
% fconfigure $fp
-blocking 1 -buffering full -buffersize 4096 -encoding utf-8 -eofchar {{} {}} -translation {auto lf}
% fconfigure $fp -blocking 0  -buffering  line
%
%
%
%
%  fileevent $fp readable [list GetData $fp]
%
</code>```

I have changed the file contents using cat command in another terminal, but still GetData is not getting called.

With gets $fp line, I am able to get the modified contents, but why fileevent is not triggered ?

答:
The callbacks scheduled with fileevent only occur when you are running the event loop, and tclsh doesn't run an event loop for you by default. Try doing this to see if my hypothesis is correct:

```<code>update
</code>```

If it is, you'll need to design your program to work driven by callbacks. The standard way of running the event loop is this:

```<code>vwait forever
# Any global variable name would do, but “forever” has a nice feel
</code>```

But that's a bit less helpful for your interactive testing. (One way round this is to load the Tk package; that turns on running the event loop by default so you don't need to do so explicitly. And gives you windows to manage, so it isn't without consequences…)

Title: Tailing a local file using fileevent

Body:
I am trying to tail a file using fileevent (Should only Tcl 8.4 version, so I can't use chan command).

% proc GetData {chan} {
 set data [read $chan]
    puts "[string length $data] $data"
    if {[eof $chan]} {
        fileevent $chan readable {}
    }
}
%
%
%
%  set fp [open "|tail -f /home/dinesh/input" r+]
file7
% fconfigure $fp
-blocking 1 -buffering full -buffersize 4096 -encoding utf-8 -eofchar {{} {}} -translation {auto lf}
% fconfigure $fp -blocking 0  -buffering  line
%
%
%
%
%  fileevent $fp readable [list GetData $fp]
%

I have changed the file contents using cat command in another terminal, but still GetData is not getting called.

With gets $fp line, I am able to get the modified contents, but why fileevent is not triggered ?

Body:
The callbacks scheduled with fileevent only occur when you are running the event loop, and tclsh doesn't run an event loop for you by default. Try doing this to see if my hypothesis is correct:

update

If it is, you'll need to design your program to work driven by callbacks. The standard way of running the event loop is this:

vwait forever
# Any global variable name would do, but “forever” has a nice feel

But that's a bit less helpful for your interactive testing. (One way round this is to load the Tk package; that turns on running the event loop by default so you don't need to do so explicitly. And gives you windows to manage, so it isn't without consequences…)


问:
How can I replace each newline (\n) with a space using sed?
How can I replace a newline ("\n") with a space ("") using the sed command?

I unsuccessfully tried:

```<code>sed 's#\n# #g' file
sed 's#^$# #g' file
</code>```

How do I fix it?

答:
Try this:</p>

```<code>echo "a,b"|sed 's/,/\r\n/'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I replace a newline ("\n") with a space ("") using the sed command?

I unsuccessfully tried:

sed 's#\n# #g' file
sed 's#^$# #g' file

How do I fix it?

Body:
Try this:

echo "a,b"|sed 's/,/\r\n/'


问:
How to focus on a field?
I updated from Angular 2 to Angular 4 and in the docs it's written to use the Renderer2 instead of Renderer which is deprecated.

Now am looking into the Renderer source, but cannot find a way to invoke the focus() method as I used to.

Old method:

this.renderer.invokeElementMethod(element, 'focus', []);

What is the new aproach?

EDIT

What if the element i am focusing onto is obtained via QuerySelector?

For instance:

```<code>let inputField = document.querySelectorAll('.dialog input');
if ( inputField[0] ) {
   inputField[0].focus();
}
</code>```

Since its obtained via QuerySelector, the focus() method doesn't exist on it.

答:
Also you can use selectRootElement method of Renderer2.

For example:

```<code>constructor(private renderer: Renderer2) {}

this.renderer.selectRootElement('#domElementId').focus()
</code>```

, where domElementId is id='domElementId' in your html

Title: How to focus on a field?

Body:
I updated from Angular 2 to Angular 4 and in the docs it's written to use the Renderer2 instead of Renderer which is deprecated.

Now am looking into the Renderer source, but cannot find a way to invoke the focus() method as I used to.

Old method:

this.renderer.invokeElementMethod(element, 'focus', []);

What is the new aproach?

EDIT

What if the element i am focusing onto is obtained via QuerySelector?

For instance:

let inputField = document.querySelectorAll('.dialog input');
if ( inputField[0] ) {
   inputField[0].focus();
}

Since its obtained via QuerySelector, the focus() method doesn't exist on it.

Body:
Also you can use selectRootElement method of Renderer2.

For example:

constructor(private renderer: Renderer2) {}

this.renderer.selectRootElement('#domElementId').focus()

, where domElementId is id='domElementId' in your html


问:
Sharing of Records with other users in CosmosDB
CosmosDB says you can use a Token broker app to handle authentication for mobile users which makes the need for a server based middle layer app go away.    Since this is new, I haven’t found much documentation on advanced sharing and security.

Example:

I have a mobile Xamarin Forms library app that has both Students, Teachers and Books.

Students can see their own books they have checked out.  And they can share what books they have checked out with select other students.

So, if Student Stan shares his checked-out books with Student Susie, then Susie can see what books Stan has checked out.

How can I handle this CosmosDB?   I know how to do this with a regular sql database by creating master / detail relationships.   Can I do the same with cosmos DB by creating master / detail json documents?

答:
Firstly, if you’d like to build a Token broker app to authenticate users and issue short-lived tokens to signed-in users, please refer to Resource Token Broker on GitHub.

Secondly, for the books sharing functionality. If you model your data to keep student-books-sharingrelations in same document, which would provide an easy way for read almost all relation information in a query/request. Besides, as you mentioned, if you store these info/data in separate documents, which may need to make multiple queries/requests to get relation information.

This thread discussed about ‘’How to create and update a relation between documents in DocumentDB”, which might be helpful.


问:
TeamCity : NUnit fails to find dependency of target assembly
```<code>Windows 10
Visual Studio 2017
TeamCity 2017.1.2
GitHub
</code>```

I'm working with a VS solution that locally behaves as expected. Main-project has some package dependencies. Test-project has project-ref to main project. VS local compile succeeds. Main-project refs + dependencies are copied to MyProject/bin/debug; test-project refs + dependencies are copied to MyProject.Tests/bin/debug; ReSharper local run of tests succeeds.

However my TC project has problems running tests.

My build-config steps are : pull from GitHub , run Visual Studio (sln) build , trigger NUnit.ConsoleRunner to run tests vs built assembly - which throws a file not found error (can't find package dependency assembly ) that perhaps indicate the build steps needs to save as artifact the dependent assembly and copy it to the test output dir.

However looking at the agent work dir I find the dependency assembly present in both the main-project and the test-project :

```<code>C:\TeamCity\buildAgent\work\64f706c42d79250c\{main-project}\bin\Debug\{dependency}.dll
</code>```

and

```<code>C:\TeamCity\buildAgent\work\64f706c42d79250c\{tests-project}\bin\Debug\{dependency}.dll
</code>```

which indicates that VS build step copied {dependency}.dll into bin as expected.

So why can't NUnit find it ?

```<code>[19:27:48][Step 5/5] MyProject.dll
[19:27:48][MyProject.dll] MyProject.UnitTests.MyTest
[19:27:49][MyProject.UnitTests.MyTest] System.IO.FileNotFoundException : Could not load file or assembly 'MyProjectDependency, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
[19:27:49]
[MyProject.UnitTests.MyTest]    at ReferencingCode()
   at MyProject.MyClass.Answer() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\MyClass.cs:line 9
   at MyProject.UnitTests.MyTest() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\UnitTests.cs:line 10
[19:27:51][Step 5/5] Failed tests detected
</code>```

I'm wondering if the output dirs are different for the VS Build and NUnit steps ?  But my agent work dir is identical to my local VS solution dir - so where would TC be locating the NUnit work dir ?

答:
It looks as if you have two completely separate output directories, one under the test project and one under the main project. Your tests, of course, are run in the directory that contains the test assembly.

The output messages seem to say that the main assembly is being copied into the test assembly directory - the reference from the test project must call for a local copy. We can tell that because the test assembly and the main assembly both have entries in your stack trace. The dependent assembly, however, is probably not referenced by your tests, and so does not get copied. At least that's how I read it - verify by looking at the directory contents.

You could solve this by using the same output directory for everything, but that would probably involve changing the directory structure you are using. A simple fix is to add a reference to the dependent assembly to your test project and set local copy true.

Body:
Windows 10
Visual Studio 2017
TeamCity 2017.1.2
GitHub

I'm working with a VS solution that locally behaves as expected. Main-project has some package dependencies. Test-project has project-ref to main project. VS local compile succeeds. Main-project refs + dependencies are copied to MyProject/bin/debug; test-project refs + dependencies are copied to MyProject.Tests/bin/debug; ReSharper local run of tests succeeds.

However my TC project has problems running tests.

My build-config steps are : pull from GitHub , run Visual Studio (sln) build , trigger NUnit.ConsoleRunner to run tests vs built assembly - which throws a file not found error (can't find package dependency assembly ) that perhaps indicate the build steps needs to save as artifact the dependent assembly and copy it to the test output dir.

However looking at the agent work dir I find the dependency assembly present in both the main-project and the test-project :

C:\TeamCity\buildAgent\work\64f706c42d79250c\{main-project}\bin\Debug\{dependency}.dll

and

C:\TeamCity\buildAgent\work\64f706c42d79250c\{tests-project}\bin\Debug\{dependency}.dll

which indicates that VS build step copied {dependency}.dll into bin as expected.

So why can't NUnit find it ?

[19:27:48][Step 5/5] MyProject.dll
[19:27:48][MyProject.dll] MyProject.UnitTests.MyTest
[19:27:49][MyProject.UnitTests.MyTest] System.IO.FileNotFoundException : Could not load file or assembly 'MyProjectDependency, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
[19:27:49]
[MyProject.UnitTests.MyTest]    at ReferencingCode()
   at MyProject.MyClass.Answer() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\MyClass.cs:line 9
   at MyProject.UnitTests.MyTest() in C:\TeamCity\buildAgent\work\64f706c42d79250c\MyProject\UnitTests.cs:line 10
[19:27:51][Step 5/5] Failed tests detected

I'm wondering if the output dirs are different for the VS Build and NUnit steps ?  But my agent work dir is identical to my local VS solution dir - so where would TC be locating the NUnit work dir ?


问:
Roll not defined - Reference Error
I recently installed a node.js package called roll for my text based game that I am making. Here is my code:

```<code>var totalHealth = 100;

var swordAttack = roll.roll(d100);
console.log(swordAttack.result);
if (swordAttack.result >=50 ) {
  totalHealth = totalHealth * 0.15
}

console.log(); {
    return swordAttack
};
</code>```

The idea of this code is to roll a number 1-100 if it is more than or equal to 50 it will deal 15 damage if not it will miss. So the error I'm getting is coming through the console when I run the code: https://i.stack.imgur.com/S4CUB.png

I am using VS code if that helps.

答:
First require your module and then use it

```<code>var roll = require('roll'),
  roll = new roll();
</code>```

Title: Roll not defined - Reference Error

Body:
I recently installed a node.js package called roll for my text based game that I am making. Here is my code:

var totalHealth = 100;

var swordAttack = roll.roll(d100);
console.log(swordAttack.result);
if (swordAttack.result >=50 ) {
  totalHealth = totalHealth * 0.15
}

console.log(); {
    return swordAttack
};

The idea of this code is to roll a number 1-100 if it is more than or equal to 50 it will deal 15 damage if not it will miss. So the error I'm getting is coming through the console when I run the code: https://i.stack.imgur.com/S4CUB.png

I am using VS code if that helps.

Body:
First require your module and then use it

var roll = require('roll'),
  roll = new roll();


问:
How can I sort a table inside a div
Please look at this code

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table_desc

If I try to append the table html to a div using jquery, then the sort does not work. The onclick goes into the sort function, but then nothing happens.

```<code>$(".betaCalc").append("<table border='1' id='myTable'>");
$(".betaCalc").append("<tr>");
$(".betaCalc").append("<th onclick='sortTable(0)'>Name</th>");
$(".betaCalc").append("<th onclick='sortTable(1)'>Country</th>");
$(".betaCalc").append("</tr>");
$(".betaCalc").append("<tr>");
$(".betaCalc").append("<td>Berglunds snabbkop</td>");
$(".betaCalc").append("<td>Sweden</td>");
$(".betaCalc").append("</tr>");
$(".betaCalc").append("<tr>");
$(".betaCalc").append(" <td>North/South</td>");
$(".betaCalc").append(" <td>UK</td>");
$(".betaCalc").append(" </tr>");
$(".betaCalc").append("  <tr>");
$(".betaCalc").append("  <td>Alfreds Futterkiste</td>");
$(".betaCalc").append("  <td>Germany</td>");
$(".betaCalc").append(" </tr>");
$(".betaCalc").append(" <tr>");
$(".betaCalc").append("   <td>Koniglich Essen</td>");
$(".betaCalc").append("   <td>Germany</td>");
$(".betaCalc").append("  </tr>");
$(".betaCalc").append(" <tr>");
$(".betaCalc").append("   <td>Magazzini Alimentari Riuniti</td>");
$(".betaCalc").append("   <td>Italy</td>");
$(".betaCalc").append(" </tr>");
$(".betaCalc").append(" <tr>");
$(".betaCalc").append("   <td>Paris specialites</td>");
$(".betaCalc").append("   <td>France</td>");
$(".betaCalc").append(" </tr>");
$(".betaCalc").append(" <tr>");
$(".betaCalc").append("   <td>Island Trading</td>");
$(".betaCalc").append("   <td>UK</td>");
$(".betaCalc").append(" </tr>");
$(".betaCalc").append("  <tr>");
$(".betaCalc").append("   <td>Laughing Bacchus Winecellars</td>");
$(".betaCalc").append("   <td>Canada</td>");
$(".betaCalc").append(" </tr>");
$(".betaCalc").append("</table>");
</code>```

答:
Yes i got your issue ,this is not working as you are appending the whole table from jquery.

To solve this, first of all add the table on HTML page and then append the dynamic table rows into that table.

Like:-

```<code>$(".betaCalc").append("<tr><td>Berglunds snabbkop</td><td>Sweden</td></tr>");
</code>```

Then the shorting will work fine.
Thanks

Check here:-https://jsfiddle.net/Bibhudatta_sahoo/k7b04mjb/1/

Title: How can I sort a table inside a div

Body:
Please look at this code

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sort_table_desc

If I try to append the table html to a div using jquery, then the sort does not work. The onclick goes into the sort function, but then nothing happens.

$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("Name	");
$(".betaCalc").append("Country	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("Berglunds snabbkop	");
$(".betaCalc").append("Sweden	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append(" North/South	");
$(".betaCalc").append(" UK	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("  Alfreds Futterkiste	");
$(".betaCalc").append("  Germany	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("   Koniglich Essen	");
$(".betaCalc").append("   Germany	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("   Magazzini Alimentari Riuniti	");
$(".betaCalc").append("   Italy	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("   Paris specialites	");
$(".betaCalc").append("   France	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("   Island Trading	");
$(".betaCalc").append("   UK	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");
$(".betaCalc").append("   Laughing Bacchus Winecellars	");
$(".betaCalc").append("   Canada	");
$(".betaCalc").append("
");
$(".betaCalc").append("
");

Body:
Yes i got your issue ,this is not working as you are appending the whole table from jquery.

To solve this, first of all add the table on HTML page and then append the dynamic table rows into that table.

Like:-

$(".betaCalc").append("<tr><td>Berglunds snabbkop</td><td>Sweden</td></tr>");

Then the shorting will work fine.
Thanks

Check here:-https://jsfiddle.net/Bibhudatta_sahoo/k7b04mjb/1/


问:
The term 'Update-Database' is not recognized as the name of a cmdlet
I am using EF5 beta1 and while I was able to run the "Update-Database" before.  Now that I shut down Visual Studio, I cannot get it to run.  I get the following error:

The term 'Update-Database' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
  At line:1 char:16
  + Update-Database <<<<  -verbose
      + CategoryInfo          : ObjectNotFound: (Update-Database:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException

I have tried to re-install EF5b1 and while was successful (already installed), the 'Update-Database' still does not work.

Can anyone help???

答: Just restart Visual Studio, it'll solve the problem. Works for me.</p>


问:
Listening to dynamically created toggle button in android
Hello all I am implementing a control board with dynamically created toggle buttons where the number of toggle buttons is also dynamic, I am having a hard time appending a function to the dynamically created buttons, </p>

```<code> for (int i = 0; i < len; i++) {
 ToggleButton tb[i] = new ToggleButton(this);
            LinearLayout.LayoutParams tbparams = new LinearLayout.LayoutParams
                    (90, LinearLayout.LayoutParams.WRAP_CONTENT);
            tbparams.setMargins(120, 0, 0, 0);
            tb[i].setBackgroundResource(R.drawable.bgtoggle);
            tb[i].setId(i+1);
            tb[i].setText("toggle_btn"+i+1);
            tb[i].setPadding(4, 4, 4, 4);
            tb[i].setLayoutParams(tbparams);
}
</code>```

答:
Sorry for being this late, i hope someone will take it as useful

```<code> tb[i].setOnCheckedChangeListener(handleOnClick(tb[i],tb[i].getId(),
tb[i].getTag(),iv[i],iv[i].getTag()));
/*Function declartion for dynamic Toggle button listening provided a tag is provide to uniquely identify the dyanmic buttons*/
</code>```

//Toggle button function

```<code>    private CompoundButton.OnCheckedChangeListener handleOnClick(final ToggleButton toggleButton, final int id, final Object tag ) {
............................ //Do your wish
}
</code>```

Body:
Hello all I am implementing a control board with dynamically created toggle buttons where the number of toggle buttons is also dynamic, I am having a hard time appending a function to the dynamically created buttons,

 for (int i = 0; i < len; i++) {
 ToggleButton tb[i] = new ToggleButton(this);
            LinearLayout.LayoutParams tbparams = new LinearLayout.LayoutParams
                    (90, LinearLayout.LayoutParams.WRAP_CONTENT);
            tbparams.setMargins(120, 0, 0, 0);
            tb[i].setBackgroundResource(R.drawable.bgtoggle);
            tb[i].setId(i+1);
            tb[i].setText("toggle_btn"+i+1);
            tb[i].setPadding(4, 4, 4, 4);
            tb[i].setLayoutParams(tbparams);
}

Body:
Sorry for being this late, i hope someone will take it as useful

 tb[i].setOnCheckedChangeListener(handleOnClick(tb[i],tb[i].getId(),
tb[i].getTag(),iv[i],iv[i].getTag()));
/*Function declartion for dynamic Toggle button listening provided a tag is provide to uniquely identify the dyanmic buttons*/

//Toggle button function

    private CompoundButton.OnCheckedChangeListener handleOnClick(final ToggleButton toggleButton, final int id, final Object tag ) {
............................ //Do your wish
}


问:
simple authorisation / login capability in php
I'm looking to implement user login onto my site for the first time.  I'm happy to either build my own solution, or implement something open source, however no package has been an obvious choice in my search so far.  Equally, I'm fully aware that as an intermediate php programmer at best, I am highly likely to miss something obvious if I roll my own solution, and leave the doors well and truly open.

Any suggestions?  We're not talking super sensitive or payment data here, but equally, I'm keen not to have people mess up my site!

requirements are
- php based
- simple as possible, not need for fancy bells and whistles
- not Zend framework, since i've now rolled my own very basic frameworkthanks to this post

Thanks for your input.

答:
This is not that hard, and fun to code, as a beginner.

You need a place to store your data (let's say a mysql database).

You should at least have a login field, and a password field. (the password should be stored crypter using sha1() for instance).

Now, you have to display a login form. I assume this is ok for you.

What is to be done, whenever we get the login and the password?

Query the database to see wether there is a match with login_base == login_form and password_base == sha1(password_form).

If yes, you set something, like a session for instance.

So on a page where one should be logged, you only have to check if there is a session set.

This is for the basis; then you can add some levels and so on.

OwnerDisplayName: Rob Y

OwnerDisplayName: Aif


问:
How do you get the most clicked facebook like-buttons on a single domain?
We have a large website with about 200,000 like buttons spread across the pages of our domain.  I can go to our insights page to get overall number of likes on a particular day, but can we get say the top ten pages that were most liked in a particular day/week/month.  I don't see anything in FQL (at least that I can decipher) that allows one to do this.</p>

答:
Go to http://www.facebook.com/insights/
then click "Insights for your domain" and follow the instructions how to link domain for your profile and you will be able to follow likes. I just find out that cos I have needed that also.</p>


问:
Active Directory OAuth 2.0 - Request an Authorization Code through PHP different than browser request
I'm following this documentation: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

Under, REQUEST AN AUTHORIZATION CODE, it gives a sample code involving an endpoint for OAuth 2.0. I've followed this structure to base my own request resembling:

```<code>https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=https://example.com
&response_mode=query
&resource=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
</code>```

During my tests, I've even tried (getting the request as bare as possible):

```<code>https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
</code>```

Here's the interesting thing: If I access these domains through the browser, they return a "successful" call, like so:

```<code>https://example.com/?code=AOA...................................
</code>```

However, I can't seem to get this same result (acquire a code) through a PHP workaround.

I've tried:

```<code>file_get_contents($my_url);
</code>```

But all that returns is an error and a login page for Microsoft.

I've also tried doing so in cURL, but no luck.

Can anyone advise on how to replicate getting such a code (automatically)?

答:
You could redirect user to microsoft login page by using header() function to send HTTP Location header:

```<code>header("Location: https://login.microsoftonline.com/xxxxxx/oauth2/authorize?client_id=xxxxxx&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:8088/testauth.php%2F&response_mode=query&resource=https%3A%2F%2Fgraph.windows.net%2F&state=12345");
</code>```

After user entered username/password , azure ad will redirect to redirect url with code , you could get the code by :

```<code>echo $_GET['code'];
</code>```

Body:
I'm following this documentation: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

Under, REQUEST AN AUTHORIZATION CODE, it gives a sample code involving an endpoint for OAuth 2.0. I've followed this structure to base my own request resembling:

https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=https://example.com
&response_mode=query
&resource=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345

During my tests, I've even tried (getting the request as bare as possible):

https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code

Here's the interesting thing: If I access these domains through the browser, they return a "successful" call, like so:

https://example.com/?code=AOA...................................

However, I can't seem to get this same result (acquire a code) through a PHP workaround.

I've tried:

file_get_contents($my_url);

But all that returns is an error and a login page for Microsoft.

I've also tried doing so in cURL, but no luck.

Can anyone advise on how to replicate getting such a code (automatically)?

Body:
You could redirect user to microsoft login page by using header() function to send HTTP Location header:

header("Location: https://login.microsoftonline.com/xxxxxx/oauth2/authorize?client_id=xxxxxx&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:8088/testauth.php%2F&response_mode=query&resource=https%3A%2F%2Fgraph.windows.net%2F&state=12345");

After user entered username/password , azure ad will redirect to redirect url with code , you could get the code by :

echo $_GET['code'];