问:
I want to change combobox color while clicking on their names in java
```<code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class combodemo implements ActionListener {
    JFrame f;
    JPanel p;
    JTextField tf;
    JButton b1;
    JButton b2;
    JRadioButton rb1;
    JRadioButton rb2;
    JLabel l;
    JComboBox cb;
    JCheckBox c1, c2, c3;
    ButtonGroup bg;

    combodemo() {
        String[] h = {
            "red",
            "yellow",
            "green"
        };
        cb = new JComboBox(h);
        f = new JFrame();
        p = new JPanel();
        tf = new JTextField(30);
        b1 = new JButton("OK");
        b2 = new JButton("Clear");
        rb1 = new JRadioButton("male");
        rb2 = new JRadioButton("Female");
        l = new JLabel("Enter Text");
        c1 = new JCheckBox("java");
        c2 = new JCheckBox("C++");
        c3 = new JCheckBox("Microsoft");
        bg = new ButtonGroup();

        f.add(p);
        p.add(l);
        p.add(tf);
        b1.addActionListener(this);
        b2.addActionListener(this);
        p.add(b1);
        p.add(b2);
        bg.add(rb1);
        bg.add(rb2);
        p.add(rb1);
        p.add(rb2);
        p.add(cb);
        p.add(c1);
        p.add(c2);
        p.add(c3);

        f.setVisible(true);
        f.pack();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent ae)

    {
        String str = (String) cb.getSelectedItem();
        '
        if (str.equals("red"))
            p.setBackground(Color.red);

        if (str.equals("green"))
            p.setBackground(Color.green);

        if (str.equals("yellow"))
            p.setBackground(Color.yellow);

        if (ae.getActionCommand() == "OK") {
            tf.setText("This is example of swing");
        }
        if (ae.getActionCommand() == "Clear") {
            tf.setText("");
        }
    }
    public static void main(String[] args)

    {
        combodemo cd = new combodemo();
    }
}
</code>```

Actually when I run this code and to change the color of panel when I click on "RED", "GREEN" or "YELLOW", it requires me to click on "OK" in order to change the color of panel. I want to change the color while clicking on the name on "RED", "GREEN" or "Yellow" please help me to get rid of this problem.

I learn this code from NIIT in today's lecture and when I coded it then many errors has occurred. But now I have completed the code but the problem I'm facing now I already written above.

Help will be appreciated.

答:
You need to do two things..

first add actionlistner to jcombobox

```<code>cb.addActionListener(this);
</code>```

second, implement logic for handling the event.

```<code>public void actionPerformed(ActionEvent ae)

{
    if(ae.getSource() instanceof JComboBox) {
            String str = (String)cb.getSelectedItem();
            if(str.equals("red"))
            p.setBackground(Color.red);

            if(str.equals("green"))
            p.setBackground(Color.green);

            if(str.equals("yellow"))
            p.setBackground(Color.yellow);
        }
          /////
</code>```

Complete code

```<code>package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class combodemo implements ActionListener
{
JFrame f;
JPanel p;
JTextField tf;
JButton b1;
JButton b2;
JRadioButton rb1;
JRadioButton rb2;
JLabel l;
JComboBox cb;
JCheckBox c1,c2,c3;
ButtonGroup bg;

combodemo()
{
String  []h = {"red","yellow","green"};
cb = new JComboBox(h);
f = new JFrame();
p = new JPanel();
tf = new JTextField(30);
b1 = new JButton("OK");
b2 = new JButton("Clear");
rb1 = new JRadioButton("male");
rb2 = new JRadioButton("Female");
l = new JLabel("Enter Text");
c1 = new JCheckBox("java");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Microsoft");
bg = new ButtonGroup();

f.add(p);
p.add(l);
p.add(tf);
b1.addActionListener(this);
b2.addActionListener(this);
cb.addActionListener(this);
p.add(b1);
p.add(b2);
bg.add(rb1);
bg.add(rb2);
p.add(rb1);
p.add(rb2);
p.add(cb);
p.add(c1);
p.add(c2);
p.add(c3);

f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)

{
    if(ae.getSource() instanceof JComboBox) {
        String str = (String)cb.getSelectedItem();
        if(str.equals("red"))
        p.setBackground(Color.red);

        if(str.equals("green"))
        p.setBackground(Color.green);

        if(str.equals("yellow"))
        p.setBackground(Color.yellow);
    }

if(ae.getActionCommand()=="OK")
{
tf.setText("This is example of swing");
}
if(ae.getActionCommand()=="Clear")
{
tf.setText("");
}
}
public static void main (String [] args)

{
combodemo cd = new combodemo();
}
}
</code>```

Body:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class combodemo implements ActionListener {
    JFrame f;
    JPanel p;
    JTextField tf;
    JButton b1;
    JButton b2;
    JRadioButton rb1;
    JRadioButton rb2;
    JLabel l;
    JComboBox cb;
    JCheckBox c1, c2, c3;
    ButtonGroup bg;

    combodemo() {
        String[] h = {
            "red",
            "yellow",
            "green"
        };
        cb = new JComboBox(h);
        f = new JFrame();
        p = new JPanel();
        tf = new JTextField(30);
        b1 = new JButton("OK");
        b2 = new JButton("Clear");
        rb1 = new JRadioButton("male");
        rb2 = new JRadioButton("Female");
        l = new JLabel("Enter Text");
        c1 = new JCheckBox("java");
        c2 = new JCheckBox("C++");
        c3 = new JCheckBox("Microsoft");
        bg = new ButtonGroup();

        f.add(p);
        p.add(l);
        p.add(tf);
        b1.addActionListener(this);
        b2.addActionListener(this);
        p.add(b1);
        p.add(b2);
        bg.add(rb1);
        bg.add(rb2);
        p.add(rb1);
        p.add(rb2);
        p.add(cb);
        p.add(c1);
        p.add(c2);
        p.add(c3);

        f.setVisible(true);
        f.pack();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent ae)

    {
        String str = (String) cb.getSelectedItem();
        '
        if (str.equals("red"))
            p.setBackground(Color.red);

        if (str.equals("green"))
            p.setBackground(Color.green);

        if (str.equals("yellow"))
            p.setBackground(Color.yellow);

        if (ae.getActionCommand() == "OK") {
            tf.setText("This is example of swing");
        }
        if (ae.getActionCommand() == "Clear") {
            tf.setText("");
        }
    }
    public static void main(String[] args)

    {
        combodemo cd = new combodemo();
    }
}

Actually when I run this code and to change the color of panel when I click on "RED", "GREEN" or "YELLOW", it requires me to click on "OK" in order to change the color of panel. I want to change the color while clicking on the name on "RED", "GREEN" or "Yellow" please help me to get rid of this problem.

I learn this code from NIIT in today's lecture and when I coded it then many errors has occurred. But now I have completed the code but the problem I'm facing now I already written above.

Help will be appreciated.

Body:
You need to do two things..

first add actionlistner to jcombobox

cb.addActionListener(this);

second, implement logic for handling the event.

public void actionPerformed(ActionEvent ae)

{
    if(ae.getSource() instanceof JComboBox) {
            String str = (String)cb.getSelectedItem();
            if(str.equals("red"))
            p.setBackground(Color.red);

            if(str.equals("green"))
            p.setBackground(Color.green);

            if(str.equals("yellow"))
            p.setBackground(Color.yellow);
        }
          /////

Complete code

package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class combodemo implements ActionListener
{
JFrame f;
JPanel p;
JTextField tf;
JButton b1;
JButton b2;
JRadioButton rb1;
JRadioButton rb2;
JLabel l;
JComboBox cb;
JCheckBox c1,c2,c3;
ButtonGroup bg;

combodemo()
{
String  []h = {"red","yellow","green"};
cb = new JComboBox(h);
f = new JFrame();
p = new JPanel();
tf = new JTextField(30);
b1 = new JButton("OK");
b2 = new JButton("Clear");
rb1 = new JRadioButton("male");
rb2 = new JRadioButton("Female");
l = new JLabel("Enter Text");
c1 = new JCheckBox("java");
c2 = new JCheckBox("C++");
c3 = new JCheckBox("Microsoft");
bg = new ButtonGroup();

f.add(p);
p.add(l);
p.add(tf);
b1.addActionListener(this);
b2.addActionListener(this);
cb.addActionListener(this);
p.add(b1);
p.add(b2);
bg.add(rb1);
bg.add(rb2);
p.add(rb1);
p.add(rb2);
p.add(cb);
p.add(c1);
p.add(c2);
p.add(c3);

f.setVisible(true);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)

{
    if(ae.getSource() instanceof JComboBox) {
        String str = (String)cb.getSelectedItem();
        if(str.equals("red"))
        p.setBackground(Color.red);

        if(str.equals("green"))
        p.setBackground(Color.green);

        if(str.equals("yellow"))
        p.setBackground(Color.yellow);
    }

if(ae.getActionCommand()=="OK")
{
tf.setText("This is example of swing");
}
if(ae.getActionCommand()=="Clear")
{
tf.setText("");
}
}
public static void main (String [] args)

{
combodemo cd = new combodemo();
}
}


来源: stackexchange

问:
How to align/set/put/style two div next to each other
I have some problem with my CSS and HTML. I can't style the 2 footer items to be on the same line. Is there something wrong with how I have my divs and styles?

Suggestion to make better code is very welcome. I have tried float, inline-block.

/*footer*/
footer {
  color:white;
  background-color: #c2b180;
}
.button-social {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px 10px 20px;
    text-align: center;
    text-decoration: none;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
a {
  text-decoration: none;
}
.sameline.block {
  float:left;
  width:50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<footer>
  <div class="sameline.block">
  <div class="about-this-page">
      <h3>About this page</h3>
      <p>Made by Duy Ta</p>
  </div>
    <div class="around-the-web">
      <h3>Around the Web</h3>
       <i class="fa fa-linkedin"></i>
       <i class="fa fa-github"></i>
       <i class="fa fa-twitter"></i>
  </div>
  </div>
  <div id="footer-below">qlip ©
    <script>document.write(new Date().getFullYear())</script>. All Rights Reversed
  </div>
</footer></code>```

答:
First of all don't use dots to name the classes. Then in order to set two elements side by side you need to set their float to left, not the container.
So in your example rename sameline.block to samelineblock and replace

```<code>.sameline.block {
  float: left;
  width: 50%;
}
</code>```

with

```<code>.samelineblock > div {
  float: left;
  width: 50%;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have some problem with my CSS and HTML. I can't style the 2 footer items to be on the same line. Is there something wrong with how I have my divs and styles?

Suggestion to make better code is very welcome. I have tried float, inline-block.

/*footer*/
footer {
  color:white;
  background-color: #c2b180;
}
.button-social {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px 10px 20px;
    text-align: center;
    text-decoration: none;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
a {
  text-decoration: none;
}
.sameline.block {
  float:left;
  width:50%;
}

 <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

About this page

Made by Duy Ta

Around the Web

qlip ©
    . All Rights Reversed

Body:
First of all don't use dots to name the classes. Then in order to set two elements side by side you need to set their float to left, not the container.
So in your example rename sameline.block to samelineblock and replace

.sameline.block {
  float: left;
  width: 50%;
}

with

.samelineblock > div {
  float: left;
  width: 50%;
}


问:
"The requested operation requires elevation" message after setup
I created setup program for one application in inno setup , where I'm trying to run application after install, but I get this message under Windows 7 :

The requested operation requires elevation.

I know it's because of admin privileges. Is there a way to overcome this (except of running the setup.exe as an administrator) ?

答:
Upgrade to the latest version

Go to the website ISXKB. It will tell you aboput elevation for Vista. It will IMHO also apply for W7

ContentLicense: CC BY-SA 2.5


问:
Linq Query: Group By
I have 2 tables with the following fields:

Person

ID, LastName, FirstName

Assignment

PersonID, AssignmentDate, OtherField

Let's say the table data looks like this:

Person

1, Smith, John

2, Allen, James

3, Stone, Emma

Assignment

1, 12/1/2016, Blue

1, 1/1/2017, Green

1, 1/1/2018, Red

2, 5/5/2015, Yellow

I'm building a report, and the logic states that...

if the AssignmentDate's YEAR ends in an EVEN number, report the even number (if year is 2014, report 2014).

If the AssignmentDate's year ends in an ODD number, report the year minus 1 (i.e., year is 2015, report 2014).

In addition, group by PersonID followed by that "even" AssignedYear. Include all persons and all assignments. (I wasn't sure if I should be using Group By or Distinct. Confused on this part.)

I need it to output these results based off the example table:

1, 2016

1, 2018

2, 2014

3, null (since personID = 3 exists, but there are no assignments, we still want to incorporate this person)

How would you do that? I've gotten this far, but got stuck. :(

```<code>var t = from p in tblPersons
        join a in tblAssignments
             on p.ID equals a.PersonID into fml
        from x in fml
        select new AssignmentFilters
              {
                  PersonID = x.PersonID,
                  Person= x.tblPersons.LastName + ", " + x.tblPersons.FirstName +
                       (string.IsNullOrEmpty(x.tblPersons.PreferredName) ? "" : " (" + x.tblPersons.PreferredName + ")") +
                       (string.IsNullOrEmpty(x.tblPersons.MiddleName) ? "" : " " + x.tblPersons.MiddleName) +
                       (string.IsNullOrEmpty(x.tblPersons.Suffix) ? "" : " " + x.tblPersons.Suffix),
                  AuditStartYear = x.DateAssigned == null ? 0 : (x.DateAssigned.Year % 2 == 0 ? x.DateAssigned.Year : x.DateAssigned.Year - 1)
               };
</code>```

Any help would be greatly appreciated! Been working on this for the past few hours and am just frustrated/stumped, lol. Thank you!

答:
isolate the audits per person based on the specific rules you mention

```<code>var audits = from assignment in tblAssignments
             select new
             {
                 PersonId = assignment.PersonID,
                 Year = assignment.DateAssigned == null
                     ? 0
                     : assignment.DateAssigned.Year % 2 == 0
                         ? assignment.DateAssigned.Year
                         : assignment.DateAssigned.Year - 1
             };
</code>```

iterate over the persons and left outer join on the distinct of audits

```<code>var results = from person in tblPersons
            from audit in
            (
                from a in audits.Distinct()
                where a.PersonId == person.ID
                select a
            ).DefaultIfEmpty()
            select new
            {
              Person = person,
              Audit = audit,
            };
</code>```

this should give you something like this and then you can project the results even further in whatever shape you need

Title: Linq Query: Group By

Body:
I have 2 tables with the following fields:

Person

ID, LastName, FirstName

Assignment

PersonID, AssignmentDate, OtherField

Let's say the table data looks like this:

Person

1, Smith, John

2, Allen, James

3, Stone, Emma

Assignment

1, 12/1/2016, Blue

1, 1/1/2017, Green

1, 1/1/2018, Red

2, 5/5/2015, Yellow

I'm building a report, and the logic states that...

if the AssignmentDate's YEAR ends in an EVEN number, report the even number (if year is 2014, report 2014).

If the AssignmentDate's year ends in an ODD number, report the year minus 1 (i.e., year is 2015, report 2014).

In addition, group by PersonID followed by that "even" AssignedYear. Include all persons and all assignments. (I wasn't sure if I should be using Group By or Distinct. Confused on this part.)

I need it to output these results based off the example table:

1, 2016

1, 2018

2, 2014

3, null (since personID = 3 exists, but there are no assignments, we still want to incorporate this person)

How would you do that? I've gotten this far, but got stuck. :(

var t = from p in tblPersons
        join a in tblAssignments
             on p.ID equals a.PersonID into fml
        from x in fml
        select new AssignmentFilters
              {
                  PersonID = x.PersonID,
                  Person= x.tblPersons.LastName + ", " + x.tblPersons.FirstName +
                       (string.IsNullOrEmpty(x.tblPersons.PreferredName) ? "" : " (" + x.tblPersons.PreferredName + ")") +
                       (string.IsNullOrEmpty(x.tblPersons.MiddleName) ? "" : " " + x.tblPersons.MiddleName) +
                       (string.IsNullOrEmpty(x.tblPersons.Suffix) ? "" : " " + x.tblPersons.Suffix),
                  AuditStartYear = x.DateAssigned == null ? 0 : (x.DateAssigned.Year % 2 == 0 ? x.DateAssigned.Year : x.DateAssigned.Year - 1)
               };

Any help would be greatly appreciated! Been working on this for the past few hours and am just frustrated/stumped, lol. Thank you!

Body:
isolate the audits per person based on the specific rules you mention

var audits = from assignment in tblAssignments
             select new
             {
                 PersonId = assignment.PersonID,
                 Year = assignment.DateAssigned == null
                     ? 0
                     : assignment.DateAssigned.Year % 2 == 0
                         ? assignment.DateAssigned.Year
                         : assignment.DateAssigned.Year - 1
             };

iterate over the persons and left outer join on the distinct of audits

var results = from person in tblPersons
            from audit in
            (
                from a in audits.Distinct()
                where a.PersonId == person.ID
                select a
            ).DefaultIfEmpty()
            select new
            {
              Person = person,
              Audit = audit,
            };

this should give you something like this and then you can project the results even further in whatever shape you need


问:
WPF -Child datacontext set from the parent ViewModel doesnot contains the modified values in the parent ViewModel
In my WPF application I have a MainWindow.xaml which has many User Controls embedded into it. I have separate viewmodel for both the main window as well as the user controls. In the Main Window ViewModel I create an instance of the child ViewModel and set it as the child's datacontext.

Parent VM
ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);

MainWindow.xaml

But this approach is not working as I am not getting the values set in the parent viewmodel in the child one and vice versa.

On the contrary, if I set the Child model object as the datacontext from the parent that is working both way.

I need some solution so that I can use MVVM in the user controls also ensuring data gets passed from parent to child and vice versa.
In the usercontrol I am going to have some buttons whose action I want to handle in the child Viewmodel through ICommand.
Adding the code snippets for reference
MainWindow.xaml

```<code><Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
    <local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>
</code>```

MainWindowVM.cs

```<code> ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);
</code>```

ProfileIdentitySettings.xaml

```<code>DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">
</code>```

答:
My Understanding is like you need to set the usercontrol Viewmodel from MainViewModel.

MainViewModel:

```<code> public class MainWindowViewModel : INotifyPropertyChanged, IMainViewModel
{

    public MainWindowViewModel()
    {
        this.Collection = new List<string>();
        this.Child = new ChildUserControlViewModel();
        this.Child.mainViewModel = this;
        this.Child.TextValue = "Justin";
    }
    private List<string> _Collection;

    public List<string> Collection
    {
        get { return _Collection; }
        set { _Collection = value; this.OnPropertyChanged("Collection"); }
    }
    private string _MainValue;
    public string MainValue
    {
        get { return _MainValue; }
        set { _MainValue = value; this.OnPropertyChanged("MainValue"); }
    }
    private ChildUserControlViewModel child;
    public ChildUserControlViewModel Child
    {
        get { return child; }
        set { child = value; this.OnPropertyChanged("Child"); }
    }

}
</code>```

Child Usercontrol View model:

```<code>public class ChildUserControlViewModel : INotifyPropertyChanged
{

    public IMainViewModel mainViewModel = null;

    public List<string> Collection
    {
        get { return this.mainViewModel.Collection; }
        set { this.mainViewModel.Collection = value; this.OnPropertyChanged("Collection"); }
    }

    private string _TextValue;
    public string TextValue
    {
        get { return _TextValue; }
        set
        {
            _TextValue = value;
            this.mainViewModel.MainValue = value;
            this.mainViewModel.Collection.Add(value);
            this.OnPropertyChanged("TextValue");
        }
    }
}

 public interface IMainViewModel
    {
        string MainValue { get; set; }

         List<string> Collection { get; set; }
    }
</code>```

View:

```<code><Grid>
   <usr:ChildUserControl DataContext="{Binding Child}"/>
</Grid>
</code>```

Body:
In my WPF application I have a MainWindow.xaml which has many User Controls embedded into it. I have separate viewmodel for both the main window as well as the user controls. In the Main Window ViewModel I create an instance of the child ViewModel and set it as the child's datacontext.

Parent VM
ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);

MainWindow.xaml

But this approach is not working as I am not getting the values set in the parent viewmodel in the child one and vice versa.

On the contrary, if I set the Child model object as the datacontext from the parent that is working both way.

I need some solution so that I can use MVVM in the user controls also ensuring data gets passed from parent to child and vice versa.
In the usercontrol I am going to have some buttons whose action I want to handle in the child Viewmodel through ICommand.
Adding the code snippets for reference
MainWindow.xaml

<Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
    <local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>

MainWindowVM.cs

 ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);

ProfileIdentitySettings.xaml

DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">

Body:
My Understanding is like you need to set the usercontrol Viewmodel from MainViewModel.

MainViewModel:

 public class MainWindowViewModel : INotifyPropertyChanged, IMainViewModel
{

    public MainWindowViewModel()
    {
        this.Collection = new List<string>();
        this.Child = new ChildUserControlViewModel();
        this.Child.mainViewModel = this;
        this.Child.TextValue = "Justin";
    }
    private List<string> _Collection;

    public List<string> Collection
    {
        get { return _Collection; }
        set { _Collection = value; this.OnPropertyChanged("Collection"); }
    }
    private string _MainValue;
    public string MainValue
    {
        get { return _MainValue; }
        set { _MainValue = value; this.OnPropertyChanged("MainValue"); }
    }
    private ChildUserControlViewModel child;
    public ChildUserControlViewModel Child
    {
        get { return child; }
        set { child = value; this.OnPropertyChanged("Child"); }
    }

}

Child Usercontrol View model:

public class ChildUserControlViewModel : INotifyPropertyChanged
{

    public IMainViewModel mainViewModel = null;

    public List<string> Collection
    {
        get { return this.mainViewModel.Collection; }
        set { this.mainViewModel.Collection = value; this.OnPropertyChanged("Collection"); }
    }

    private string _TextValue;
    public string TextValue
    {
        get { return _TextValue; }
        set
        {
            _TextValue = value;
            this.mainViewModel.MainValue = value;
            this.mainViewModel.Collection.Add(value);
            this.OnPropertyChanged("TextValue");
        }
    }
}

 public interface IMainViewModel
    {
        string MainValue { get; set; }

         List<string> Collection { get; set; }
    }

View:

<Grid>
   <usr:ChildUserControl DataContext="{Binding Child}"/>
</Grid>


问:
pass int data via bundle
I am currently working on a quiz application whereby i need to review answered questions after each quiz session. So, am passing the number of questions attempted as an int value with a bundle to the next activity.

So, am looping forward and backwards against my array of questions in which the index limit is the int which was passed from previous activity. However, am having some trouble as it isn't looping correctly. How do i get round this?

Question Class

```<code>class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}
</code>```

MainActivity.java

```<code>Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
                    intent.putExtra("quizNumber", mquizNumber);
startActivity(intent);
</code>```

ResultsActivity.java

```<code>Intent intent = new Intent(ResultsActivity.this, ReviewActivity.class);
                Bundle exBundle= getIntent().getExtras();
                int intValue= 0;
                if (exBundle != null) {
                    intValue = exBundle.getInt("quizNumber");
                }
               intent.putExtra("quizNumber", intValue);
                startActivity(intent);
</code>```

ReviewActivity.java

```<code>public class ReviewActivity extends AppCompatActivity {
    private Question mQuestionLibrary = new Question();
private TextView mQuestionText;
 private int intValue; // int value from quiz activity to be passed here
    private int mQuestionNumber = 1; // current question number
//navigation buttons for looping through array
    private Button mPrevious;
    private Button mNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        }
        setContentView(R.layout.activity_beginner_review);
        mQuestionText = (TextView) findViewById(R.id.txtQuestion);
        //setting buttons
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        // retrieve the number of attempted questions int value from quizActivity in Bundle
        Bundle exBundle= getIntent().getExtras();
       intValue = 0;
        if (exBundle != null) {
            intValue = exBundle.getInt("quizNumber");
        }
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(true);
            }
        });
        mPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(false);
            }
        });
    }
// logic for looping through array.
    private void updateQuestion(boolean forward) {
        animateAnswerButton();
        if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
            mQuestionNumber++;
        else if (mQuestionNumber>0)
            mQuestionNumber--;
        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    }

}
</code>```

答:
Try this code.

```<code>Intent intent = getIntent();
            Bundle extras = intent.getExtras();
            if (extras != null){
                if(extras.containsKey("quizNumber")) {

                           intValue=getIntent().getExtras().getInt("quizNumber")

                    }
                }

    updateQuestion(true,intValue);

or

     updateQuestion(false,intValue);

 private void updateQuestion(boolean forward, int intValue) {
            animateAnswerButton();
// also print toast of int value for checking value
            if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
                mQuestionNumber++;
            else if (mQuestionNumber>0)
                mQuestionNumber--;
            mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
        }
</code>```

Also toast or log your mquizNumber in MainActivity whether you're putting correct value in bundle or not.

Title: pass int data via bundle

Body:
I am currently working on a quiz application whereby i need to review answered questions after each quiz session. So, am passing the number of questions attempted as an int value with a bundle to the next activity.

So, am looping forward and backwards against my array of questions in which the index limit is the int which was passed from previous activity. However, am having some trouble as it isn't looping correctly. How do i get round this?

Question Class

class Question{
    // array of questions
    private String mQuestions [] = {
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
    // method returns number of questions
    int getLength(){
        return mQuestions.length;
    }

    // method returns question from array textQuestions[] based on array index
    String getQuestion(int a) {
        return mQuestions[a];
    }
}

MainActivity.java

Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
                    intent.putExtra("quizNumber", mquizNumber);
startActivity(intent);

ResultsActivity.java

Intent intent = new Intent(ResultsActivity.this, ReviewActivity.class);
                Bundle exBundle= getIntent().getExtras();
                int intValue= 0;
                if (exBundle != null) {
                    intValue = exBundle.getInt("quizNumber");
                }
               intent.putExtra("quizNumber", intValue);
                startActivity(intent);

ReviewActivity.java

public class ReviewActivity extends AppCompatActivity {
    private Question mQuestionLibrary = new Question();
private TextView mQuestionText;
 private int intValue; // int value from quiz activity to be passed here
    private int mQuestionNumber = 1; // current question number
//navigation buttons for looping through array
    private Button mPrevious;
    private Button mNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        }
        setContentView(R.layout.activity_beginner_review);
        mQuestionText = (TextView) findViewById(R.id.txtQuestion);
        //setting buttons
        mPrevious = (Button) findViewById(R.id.previous);
        mNext = (Button) findViewById(R.id.next);
        // retrieve the number of attempted questions int value from quizActivity in Bundle
        Bundle exBundle= getIntent().getExtras();
       intValue = 0;
        if (exBundle != null) {
            intValue = exBundle.getInt("quizNumber");
        }
        mNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(true);
            }
        });
        mPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateQuestion(false);
            }
        });
    }
// logic for looping through array.
    private void updateQuestion(boolean forward) {
        animateAnswerButton();
        if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
            mQuestionNumber++;
        else if (mQuestionNumber>0)
            mQuestionNumber--;
        mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
    }

}

Body:
Try this code.

Intent intent = getIntent();
            Bundle extras = intent.getExtras();
            if (extras != null){
                if(extras.containsKey("quizNumber")) {

                           intValue=getIntent().getExtras().getInt("quizNumber")

                    }
                }

    updateQuestion(true,intValue);

or

     updateQuestion(false,intValue);

 private void updateQuestion(boolean forward, int intValue) {
            animateAnswerButton();
// also print toast of int value for checking value
            if(forward && mQuestionNumber < intValue //using mQuestion.getLength() works for looping full length of array but i want to check against int data)
                mQuestionNumber++;
            else if (mQuestionNumber>0)
                mQuestionNumber--;
            mQuestionText.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
        }

Also toast or log your mquizNumber in MainActivity whether you're putting correct value in bundle or not.


问:
CSS not working in stylesheet
I have a set of Styles that were first created inside the style attribute on a page.

I want to move it from being on the page itself into a stylesheet.

however, when I move it to a .css file, the page breaks, move the code back to the html doc and it works fine again.

This makes absolutely no sense, moving styles from a style to a css file shouldnt break the code should it?

Am I missing something? I am not changing any of the code, its simply a copy and paste.

答:
This is just a shot in the dark as (at the time of this post) you haven't provided source code.

Make sure you're linking to your stylesheet using a link tag in the head of the HTML document.

If you had:

```<code><style type="text/css">
/* <![CDATA[ */
#someid
{
  margin: 0;
  padding: 3px 12px;
}
/* ]]> */
</style>
</code>```

You'll need to have

```<code>#someid
{
  margin: 0;
  padding: 3px 12px;
}
</code>```

in your CSS file with:

```<code><link rel="stylesheet" type="text/css" href="path/to/style.css" />
</code>```

to link to the stylesheet.

Some common newbie mistakes include:

Title: CSS not working in stylesheet

Body:
This is just a shot in the dark as (at the time of this post) you haven't provided source code.

Make sure you're linking to your stylesheet using a link tag in the head of the HTML document.

If you had:

<style type="text/css">
/* <![CDATA[ */
#someid
{
  margin: 0;
  padding: 3px 12px;
}
/* ]]> */
</style>

You'll need to have

#someid
{
  margin: 0;
  padding: 3px 12px;
}

in your CSS file with:

<link rel="stylesheet" type="text/css" href="path/to/style.css" />

to link to the stylesheet.

Some common newbie mistakes include:

<style type="text/css" src="path/to/style.css">: because it's a similar syntax to the <script> tag, which would make sense, but is invalid

<link rel="stylesheet" src="path/to/style.css">: but link elements use href not src

placing link elements within the body: although browsers will tend to manage link elements in the body, there are likely going to be some errors, and it's not a defined behavior

not specifying a doctype declaration: allows the browser to go into quirks mode, which is never a good idea.


答:
Use this

In your sender class

```<code>//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putInt("DATA", value);
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);
</code>```

in your reciver class

```<code>Bundle bundle = getIntent().getExtras();

//Extract the data…

String venName = bundle.getInt("DATA");
</code>```

Title: pass int data via bundle

Body:
Use this

In your sender class

//Create the bundle
Bundle bundle = new Bundle();
//Add your data from getFactualResults method to bundle
bundle.putInt("DATA", value);
//Add the bundle to the intent
i.putExtras(bundle);
startActivity(i);

in your reciver class

Bundle bundle = getIntent().getExtras();

//Extract the data…

String venName = bundle.getInt("DATA");


问:
Visual studio 2015 post build commnad failing with exit code 1. strange thing is it fails only on some projects
I am trying following post build event in some of my projects

```<code>copy /Y "$(TargetDir)*.dll" "$(SolutionDir)MyMainApp\bin\*.dll"
</code>```

But getting error

Error       The command "copy /Y "D:\myslolution\myimplementation\bin\Release*.dll" "D:\myslolution\MyMainApp\bin*.dll"" exited with code 1.

Any idea what's wrong in it?
strange thing is on multiple rebuild it sometimes work

答:
Please check your two project folders in your side.

For example, bases on your description, I have two projects, I set the post-build event command line in the myimplementation property:

If I build the project, I will get this dll file:

strange thing is on multiple rebuild it sometimes work

If so, please clean and build your project, view it again. My understanding is that if your project code was not changed after you build it first time, it would not update the dll file or call the build event again even if you build it. It would show you up-to-date messages in your VS output window. But if you clean it, and then build it again, it would copy the dll again.

Body:
I am trying following post build event in some of my projects

copy /Y "$(TargetDir)*.dll" "$(SolutionDir)MyMainApp\bin\*.dll"

But getting error

Error       The command "copy /Y "D:\myslolution\myimplementation\bin\Release*.dll" "D:\myslolution\MyMainApp\bin*.dll"" exited with code 1.

Any idea what's wrong in it?
strange thing is on multiple rebuild it sometimes work


问:
Understanding jQuery (basic question)
i have a pretty basic jquery question. im trying to add jscrollpane to my site and get it to initialize after an ajax call. however when i run the function i keep getting the message "testFunction is not defined" in the console. the code is very basic:

```<code>$(document).ready(function() {
  var api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
    }).data('jsp');

  function testFunction() {
      api.getContentPane().load('ajax_content.html', function() {
      api.reinitialise();
   });
 }
});
</code>```

why do i keep getting the message? if i take the testfunction out of the document ready function i get the error "api not defined" thanks in advance

答:
This has to do with the scope of the variable api that you are defining. You need to define the api variable outside of the $(document).ready(function() { .... Try this:

```<code>var api;
$(document).ready(function() {
  api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
  }).data('jsp');
});

function testFunction() {
    api.getContentPane().load('ajax_content.html', function() {
        api.reinitialise();
    });
}
</code>```

Hopefully that helps.

Title: Understanding jQuery (basic question)

Body:
i have a pretty basic jquery question. im trying to add jscrollpane to my site and get it to initialize after an ajax call. however when i run the function i keep getting the message "testFunction is not defined" in the console. the code is very basic:

$(document).ready(function() {
  var api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
    }).data('jsp');

  function testFunction() {
      api.getContentPane().load('ajax_content.html', function() {
      api.reinitialise();
   });
 }
});

why do i keep getting the message? if i take the testfunction out of the document ready function i get the error "api not defined" thanks in advance

Body:
This has to do with the scope of the variable api that you are defining. You need to define the api variable outside of the $(document).ready(function() { .... Try this:

var api;
$(document).ready(function() {
  api = $('.scroll-pane').jScrollPane({
      showArrows:true,
      maintainPosition: false
  }).data('jsp');
});

function testFunction() {
    api.getContentPane().load('ajax_content.html', function() {
        api.reinitialise();
    });
}

Hopefully that helps.


问:
Javascript convert objects to array
I have an array of arrays of objects like this:

```<code>var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]
</code>```

And I want to convert it to this:

```<code>[
  ['a', 1, '1st array'],
  ['b', 2, '1st array'],
  ['a', 1, '2nd array'],
  ['b', 2, '2nd array']
]
</code>```

Can this be done using the array.map() method? I'm asking because there can be more than 1000 objects/array that will have to be converted and I think that a simple for inside for might not be efficient...

答:
You need to do this in following way... you could improve it If you don't want to make it static , and you can make it dynamic. but it will be lengthy code ... :)
    var object1,object2;</p>

```<code>array[0].forEach(function(element,index){
   obejct1[index] = Object.values(element);

});

array[1].forEach(function(element,index){
   obejct2[index] = Object.values(element);

});

object1[0].concat(object1[1],object2[0],object1[1]);
</code>```

Title: Javascript convert objects to array

Body:
I have an array of arrays of objects like this:

var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]

And I want to convert it to this:

[
  ['a', 1, '1st array'],
  ['b', 2, '1st array'],
  ['a', 1, '2nd array'],
  ['b', 2, '2nd array']
]

Can this be done using the array.map() method? I'm asking because there can be more than 1000 objects/array that will have to be converted and I think that a simple for inside for might not be efficient...

Body:
You need to do this in following way... you could improve it If you don't want to make it static , and you can make it dynamic. but it will be lengthy code ... :)
    var object1,object2;

array[0].forEach(function(element,index){
   obejct1[index] = Object.values(element);

});

array[1].forEach(function(element,index){
   obejct2[index] = Object.values(element);

});

object1[0].concat(object1[1],object2[0],object1[1]);


问:
Clickable UILabel
I am trying to make a UILabel that if I click I can edit it. I have a hidden textfield.

Per this answer: How to customize UILabel clickable

I tried the following:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    tapInput = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(didTapLabel)];
    [lblInput setUserInteractionEnabled:YES];
    [lblInput addGestureRecognizer:tapInput];
}

-(void)didTapLabel
{
    [txtHidden becomeFirstResponder];
}
</code>```

But my break point inside didTapLabel is not firing. Everything is hooked up correctly on the storyboard.

答:
Try enabling user interaction here for label,Worked for me, and please use UITapGesture instead of UIGesture
And Textfield should be below uilabel because if the textfield is above label then uilabel's user interaction won't be considered

Title: Clickable UILabel

Body:
I am trying to make a UILabel that if I click I can edit it. I have a hidden textfield.

Per this answer: How to customize UILabel clickable

I tried the following:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    tapInput = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(didTapLabel)];
    [lblInput setUserInteractionEnabled:YES];
    [lblInput addGestureRecognizer:tapInput];
}

-(void)didTapLabel
{
    [txtHidden becomeFirstResponder];
}

But my break point inside didTapLabel is not firing. Everything is hooked up correctly on the storyboard.


答:
Use this code, It's worked. Tested.</p>

```<code>UILabel * clickMeLbl=[[UILabel alloc] initWithFrame:CGRectMake(75,30,170,30)];
clickMeLbl.text = @"Click Me";
clickMeLbl.font = [UIFont fontWithName:@"Helvetica-Bold" size: 18.0f ];
clickMeLbl.textAlignment =  NSTextAlignmentCenter;
clickMeLbl.textColor = [UIColor blackColor];
[self.view addSubview:clickMeLbl];

clickMeLbl.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapLabelWithGesture:)];
[clickMeLbl addGestureRecognizer:tapGesture];

- (void)didTapLabelWithGesture:(UITapGestureRecognizer *)tapGesture {
   NSLog(@"Click Me Label Clicked");
}
</code>```

Title: Clickable UILabel

Body:
Use this code, It's worked. Tested.

UILabel * clickMeLbl=[[UILabel alloc] initWithFrame:CGRectMake(75,30,170,30)];
clickMeLbl.text = @"Click Me";
clickMeLbl.font = [UIFont fontWithName:@"Helvetica-Bold" size: 18.0f ];
clickMeLbl.textAlignment =  NSTextAlignmentCenter;
clickMeLbl.textColor = [UIColor blackColor];
[self.view addSubview:clickMeLbl];

clickMeLbl.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapLabelWithGesture:)];
[clickMeLbl addGestureRecognizer:tapGesture];

- (void)didTapLabelWithGesture:(UITapGestureRecognizer *)tapGesture {
   NSLog(@"Click Me Label Clicked");
}


问:
py.test: Show local variables in Jenkins
Up to now we call py.test via Jenkins.

If a test fails, we see the usual stacktrace like this

```<code>Traceback (most recent call last):
  File "/home/u/src/foo/bar/tests/test_x.py", line 36, in test_schema_migrations
    errors, out))
AssertionError: Unknown output: ["Migrations for 'blue':", ...]
</code>```

It would be really great, if I could see local variables like in the django debug page (See https://djangobook.com/wp-content/uploads/figure2_3a.png).

.... But they should only be visible if I want to see them. I guess this means I need a different format than text. Maybe HTML?

Is there a way to enable this?

I never used the tool Sentry. But AFAIK this can display nice tracebacks with local variables.

答:
Use -l/--showlocals option:

```<code>pytest --showlocals # show local variables in tracebacks
pytest -l           # show local variables (shortcut)
</code>```

example:

```<code>    def foo():
        a = 1
>       assert 0
E       assert 0

a          = 1

test_foo.py:8: AssertionError
</code>```

see more details in the doc.

Body:
Up to now we call py.test via Jenkins.

If a test fails, we see the usual stacktrace like this

Traceback (most recent call last):
  File "/home/u/src/foo/bar/tests/test_x.py", line 36, in test_schema_migrations
    errors, out))
AssertionError: Unknown output: ["Migrations for 'blue':", ...]

It would be really great, if I could see local variables like in the django debug page (See https://djangobook.com/wp-content/uploads/figure2_3a.png).

.... But they should only be visible if I want to see them. I guess this means I need a different format than text. Maybe HTML?

Is there a way to enable this?

I never used the tool Sentry. But AFAIK this can display nice tracebacks with local variables.

Body:
Use -l/--showlocals option:

pytest --showlocals # show local variables in tracebacks
pytest -l           # show local variables (shortcut)

example:

    def foo():
        a = 1
>       assert 0
E       assert 0

a          = 1

test_foo.py:8: AssertionError

see more details in the doc.


问:
How can i run artisan commands in cpanel
How can i run these artisan commands in my application that is hosted in the net? Is there like a cmd in my cpanel where i can do these commands? Thanks in advance.

php artisan clear:cache

php artisan view:clear

答:
You can make a personalized route, and call it when you need it:

```<code>Route::get('/clear-cache', function() {
    $output = new \Symfony\Component\Console\Output\BufferedOutput;
    \Artisan::call('cache:clear', $output);
    dd($output->fetch());
});
</code>```

Another solution is to access ssh to your server and to run the commands.

Body:
You can make a personalized route, and call it when you need it:

Route::get('/clear-cache', function() {
    $output = new \Symfony\Component\Console\Output\BufferedOutput;
    \Artisan::call('cache:clear', $output);
    dd($output->fetch());
});

Another solution is to access ssh to your server and to run the commands.


问:
How to group results with different non unique columns pushing all the grouped json rows into a single array in PostgreSQL?
I have to tables with a one to many relation, here the query:

```<code>SELECT t1.id, t1.deployment_id, (select row_to_json(_) from (select t2.room_id, t2.unit) as _) AS rooms FROM devices_device AS t1 LEFT OUTER JOIN devices_deviceunitroom AS t2 ON t1.id = t2.device_id;
</code>```

the result of this query is the following:

Now what I would like to achieve is:

if t2.roomid and t2.unit are null I want a simple {}

the result should be grouped so that at the end I'll have only one row representing id and deployment_id and the rooms should be all into one array

let's say something similar

```<code>d9:7f:d1:ed:ea:72:4a |                                      | []
a9:e7:68:95:88:0b:40 | 6c742391-436c-4fa2-8dc2-6064aad290d0 | [{"room_id":"4f1680ad-43cc-4f16-969e-1a9a00763efd","unit":0},  {"room_id":"16b26a1a-c0dd-4b88-91db-f4809c70396a","unit":1}, {"room_id":"4f1680ad-43cc-4f16-969e-1a9a00763efd","unit":2}]
</code>```

I'm unsuccessful with GROUP BY since Postgres wants all the columns to be in the GROUP BY clause which leads to duplicates. Can somebody lead me on the good path for this?

答:
I was able at the end to find a nice way to do it, leaving the answer here if anybody will ever have a similar problem:

The SQL I generated to achieve this is:

```<code>SELECT
  t1.id,
  t1.deployment_id,
  array_to_json(COALESCE(array_agg(json_build_object('room_id', t2.room_id, 'unit', t2.unit)) FILTER (WHERE t2.room_id IS NOT NULL),ARRAY[]::json[])) AS rooms

FROM
  table_1 AS t1

LEFT OUTER JOIN
  table_2 AS t2

ON
  t1.id = t2.device_id

WHERE
  t1.deployment_id = %s::uuid

GROUP BY
  t1.id;
</code>```

Body:
I have to tables with a one to many relation, here the query:

SELECT t1.id, t1.deployment_id, (select row_to_json(_) from (select t2.room_id, t2.unit) as _) AS rooms FROM devices_device AS t1 LEFT OUTER JOIN devices_deviceunitroom AS t2 ON t1.id = t2.device_id;

the result of this query is the following:

Now what I would like to achieve is:

if t2.roomid and t2.unit are null I want a simple {}

the result should be grouped so that at the end I'll have only one row representing id and deployment_id and the rooms should be all into one array

let's say something similar

d9:7f:d1:ed:ea:72:4a |                                      | []
a9:e7:68:95:88:0b:40 | 6c742391-436c-4fa2-8dc2-6064aad290d0 | [{"room_id":"4f1680ad-43cc-4f16-969e-1a9a00763efd","unit":0},  {"room_id":"16b26a1a-c0dd-4b88-91db-f4809c70396a","unit":1}, {"room_id":"4f1680ad-43cc-4f16-969e-1a9a00763efd","unit":2}]

I'm unsuccessful with GROUP BY since Postgres wants all the columns to be in the GROUP BY clause which leads to duplicates. Can somebody lead me on the good path for this?

Body:
I was able at the end to find a nice way to do it, leaving the answer here if anybody will ever have a similar problem:

The SQL I generated to achieve this is:

SELECT
  t1.id,
  t1.deployment_id,
  array_to_json(COALESCE(array_agg(json_build_object('room_id', t2.room_id, 'unit', t2.unit)) FILTER (WHERE t2.room_id IS NOT NULL),ARRAY[]::json[])) AS rooms

FROM
  table_1 AS t1

LEFT OUTER JOIN
  table_2 AS t2

ON
  t1.id = t2.device_id

WHERE
  t1.deployment_id = %s::uuid

GROUP BY
  t1.id;


问:
linked gradle project Nothing to show
I have installed Android Studio 3.0,gradle 4.4 on my mac.
and I created a new android project , it can not build ,

Error:Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"

I tried to set the gradle , but  it say nothing to show.
like this

答:
you need to upgrade your gradle to 4.4 because android studio version 3.0.0+ needs 4.1+ gradle see more details at

https://developer.android.com/studio/releases/gradle-plugin.html

Title: linked gradle project Nothing to show


问:
Bootstrap grid place div next to div in a row
I want div 4 next to div 1 and below div 2 and 3 like the image below the code. How can I do that? Actual Code:

```<code>       <div class="container-fluid">
          <div class="row">
             <div class="col-md-4 col_trainings">1</div>
             <div class="col-md-3 col_downloads">2</div>
             <div class="col-md-3 col_project">3</div>
             <div class="col-sm-6 col_contact">4</div>
          </div>
       </div>
</code>```

答:
You can use mx-auto class to your 4th div.

```<code>   <div class="container-fluid">
      <div class="row">
         <div class="col-md-4 col_trainings">1</div>
         <div class="col-md-3 col_downloads">2</div>
         <div class="col-md-3 col_project">3</div>
         <div class="col-sm-6 mx-auto col_contact">4</div>
      </div>
   </div>
</code>```

This property will set your last block on the 5th column of bootstrap ;)

Have a look to this post. Enjoy !

Body:
I want div 4 next to div 1 and below div 2 and 3 like the image below the code. How can I do that? Actual Code:

1

2

3

4

Body:
You can use mx-auto class to your 4th div.

   <div class="container-fluid">
      <div class="row">
         <div class="col-md-4 col_trainings">1</div>
         <div class="col-md-3 col_downloads">2</div>
         <div class="col-md-3 col_project">3</div>
         <div class="col-sm-6 mx-auto col_contact">4</div>
      </div>
   </div>

This property will set your last block on the 5th column of bootstrap ;)

Have a look to this post. Enjoy !


问:
Open-source Java-based framework that has many of the common features built in out-of-the-box?
I am looking for something like Drupal in Java -- not Drupal as a CMS but rather as an application programming framework.

For example I would like to get out the the box:

A Login screen

The ability to define new roles

The ability to tie permissions (capabilities) to roles

The ability to assign roles to specific users (and revoke roles)

The ability to self-service passwords (reset ones own password)

An ability to generate a CRUD app

A menu system (that allows you to define menus)

My understanding is that Ruby-on-Rails provides this type of stuff.

Thanks.

答:
You might also look into Backbase http://www.backbase.com/

I have no experience with it, but it's all the rage at my wifes company.


问:
Can't drag and resize with angular gridstack
I am experimenting with the angular gridstack framework. I am trying to get the demo code to work.

This is the link to the framework:

https://github.com/kdietrich/gridstack-angular

This is my angular file:

```<code>generalApp.controller('DashBoardcontroller', ['$scope', '$mdDialog', '$log', function ($scope, $mdDialog, $log) {

$scope.widgets = [{ x: 0, y: 0, width: 1, height: 1 }, { x: 0, y: 0, width: 3, height: 1 }];
$scope.options = {
    cellHeight: 200,
    verticalMargin: 10
};
$scope.addWidget = function () {
    var newWidget = { x: 0, y: 0, width: 1, height: 1 };
    $scope.widgets.push(newWidget);
};
$scope.moveWidget = function () {
    $scope.widgets[0].x = 1;
    $scope.widgets[0].width = 2;
    $scope.widgets[0].height = 2;
};
$scope.removeWidget = function (w) {
    var index = $scope.widgets.indexOf(w);
    $scope.widgets.splice(index, 1);
};
$scope.onChange = function (event, items) {
    $log.log("onChange event: " + event + " items:" + items);
};
$scope.onDragStart = function (event, ui) {
    $log.log("onDragStart event: " + event + " ui:" + ui);
};
$scope.onDragStop = function (event, ui) {
    $log.log("onDragStop event: " + event + " ui:" + ui);
};
$scope.onResizeStart = function (event, ui) {
    $log.log("onResizeStart event: " + event + " ui:" + ui);
};
$scope.onResizeStop = function (event, ui) {
    $log.log("onResizeStop event: " + event + " ui:" + ui);
};
$scope.onItemAdded = function (item) {
    $log.log("onItemAdded item: " + item);
};
$scope.onItemRemoved = function (item) {
    $log.log("onItemRemoved item: " + item);
};
</code>```

}]);

And this is my index.html file:

```<code><div ng-app="generalApp" class="container-fluid" ng-controller="DashBoardcontroller">
<p>{{widgets}}</p>
<div>
    <a class="btn btn-primary" ng-click="addWidget()" href="#">Add Widget</a>
    <a class="btn btn-primary" ng-click="moveWidget()" href="#">Move Widget</a>
</div>
<br>
<div class="row">
    <div class="col-md-12">
        <div gridstack class="grid-stack grid1" options="options" on-change="onChange(event,items)" on-drag-start="onDragStart(event,ui)" on-drag-stop="onDragStop(event,ui)" on-resize-start="onResizeStart(event,ui)" on-resize-stop="onResizeStop(event,ui)">
            <div gridstack-item ng-repeat="w in widgets" class="grid-stack-item" gs-item-x="w.x" gs-item-y="w.y"
                 gs-item-width="w.width" gs-item-height="w.height" gs-item-autopos="1" on-item-added="onItemAdded(item)" on-item-removed="onItemRemoved(item)">
                <div class="grid-stack-item-content">
                    <a class="btn btn-primary" ng-click="removeWidget(w)" href="#">remove</a>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

The libraries are working fine but the problems is I can't move or resize a widget. Is this a bug in the framework? What can I do to move a widget and resize it?

Kind regards

Live demo: http://kdietrich.github.io/gridstack-angular/demo/

Live demo code: https://github.com/kdietrich/gridstack-angular/tree/master/demo

Library list:

```<code><script src="~/Scripts/Gridstack/gridstack.js"></script>
<script src="~/Scripts/Gridstack/gridstack-angular.js"></script>
<script src="~/Scripts/Gridstack/gridstack.controller.js"></script>
<script src="~/Scripts/Gridstack/gridstack.directive.js"></script>
<script src="~/Scripts/Gridstack/gridstackitem.directive.js"></script
</code>```

答: I realize I used a older version of Jquery library! I updated it via nuget package and everything is working fine. </p>

Body:
I am experimenting with the angular gridstack framework. I am trying to get the demo code to work.

This is the link to the framework:

https://github.com/kdietrich/gridstack-angular

This is my angular file:

generalApp.controller('DashBoardcontroller', ['$scope', '$mdDialog', '$log', function ($scope, $mdDialog, $log) {

$scope.widgets = [{ x: 0, y: 0, width: 1, height: 1 }, { x: 0, y: 0, width: 3, height: 1 }];
$scope.options = {
    cellHeight: 200,
    verticalMargin: 10
};
$scope.addWidget = function () {
    var newWidget = { x: 0, y: 0, width: 1, height: 1 };
    $scope.widgets.push(newWidget);
};
$scope.moveWidget = function () {
    $scope.widgets[0].x = 1;
    $scope.widgets[0].width = 2;
    $scope.widgets[0].height = 2;
};
$scope.removeWidget = function (w) {
    var index = $scope.widgets.indexOf(w);
    $scope.widgets.splice(index, 1);
};
$scope.onChange = function (event, items) {
    $log.log("onChange event: " + event + " items:" + items);
};
$scope.onDragStart = function (event, ui) {
    $log.log("onDragStart event: " + event + " ui:" + ui);
};
$scope.onDragStop = function (event, ui) {
    $log.log("onDragStop event: " + event + " ui:" + ui);
};
$scope.onResizeStart = function (event, ui) {
    $log.log("onResizeStart event: " + event + " ui:" + ui);
};
$scope.onResizeStop = function (event, ui) {
    $log.log("onResizeStop event: " + event + " ui:" + ui);
};
$scope.onItemAdded = function (item) {
    $log.log("onItemAdded item: " + item);
};
$scope.onItemRemoved = function (item) {
    $log.log("onItemRemoved item: " + item);
};

}]);

And this is my index.html file:

{{widgets}}

    Add Widget
    Move Widget

                    remove

The libraries are working fine but the problems is I can't move or resize a widget. Is this a bug in the framework? What can I do to move a widget and resize it?

Kind regards

Live demo: http://kdietrich.github.io/gridstack-angular/demo/

Live demo code: https://github.com/kdietrich/gridstack-angular/tree/master/demo

Library list:


问:
jsonpCallback parseResponse is not a function with geoserver
I am getting a 'parseResponse' is not a function when doing a request to a geoserver. I tried several things to get passed this problem, but the outcome remains: 'parseResponse is not a function'

I tried setting the sync options in the fetch,
I tried using cache: true,
I did override the sync

I did look into these possible solutions:
how to set backbone fetch callback method

Caching jsonp callback parameter when doing a backbone fetch

here is the code:

```<code>var APP = APP || {};

APP.WaterDepthStatusModel = Backbone.Model.extend({

    url: '',

    initialize: function (url) {
        this.url = url;
    },

    calcUrl: function (xy, mapInfo, RD, mapUrl, emptyInfo) {

        var mapWidth = mapInfo._size.x;
        var mapHeight = mapInfo._size.y;
        var boundsNE = RD.projection.project(mapInfo.getBounds().getNorthEast());
        var boundsSW = RD.projection.project(mapInfo.getBounds().getSouthWest());
        var BBOX = boundsSW.x + ',' + boundsSW.y + ',' + boundsNE.x + ',' + boundsNE.y;
        var zoom = mapInfo.getZoom();

        var buildUrl = mapUrl;
            buildUrl += '?REQUEST=GetFeatureInfo';
            buildUrl += '&EXCEPTIONS=application/vnd.ogc.se_xml';
            buildUrl += '&INFO_FORMAT=text/javascript';
            buildUrl += '&format=image/png';
            buildUrl += '&QUERY_LAYERS=' + APP.servers.waterDepthStatus;
            buildUrl += '&Layers=' + APP.servers.waterDepthStatus;
            buildUrl += '&BBOX=' + BBOX;
            buildUrl += '&WIDTH=' + mapWidth;
            buildUrl += '&HEIGHT=' + mapHeight;
            buildUrl += '&x=' +  xy.x;
            buildUrl += '&y=' + xy.y;
            buildUrl += '&srs=EPSG:28992';

        this.url = buildUrl;

    },

    sync: function (method, model, options) {

        options.dataType = "jsonp";
        options.crossDomain = true;
        options.jsonpCallback = "parseResponse";
        options.contentType = "application/json; charset=utf-8";

        return Backbone.sync(method, model, options);

    }

});
</code>```

this is the response I get from the server:

```<code>parseResponse({"type":"FeatureCollection","totalFeatures":1,"features":[{"type":"Feature","id":"MEGO_overstromingNL_Status.1754","geometry":null,"properties":{"CODE":3}}]})
</code>```

Any help would be appreciated

答:
This is answered in this question on gis.stackexchange.com.

There are a number of possible issues:

You need to turn Jsonp on in the web.xml file.

You need to provide a function for the Json to callback to.

Make sure you use the text/javascript output format.

Body:
I am getting a 'parseResponse' is not a function when doing a request to a geoserver. I tried several things to get passed this problem, but the outcome remains: 'parseResponse is not a function'

I tried setting the sync options in the fetch,
I tried using cache: true,
I did override the sync

I did look into these possible solutions:
how to set backbone fetch callback method

Caching jsonp callback parameter when doing a backbone fetch

here is the code:

var APP = APP || {};

APP.WaterDepthStatusModel = Backbone.Model.extend({

    url: '',

    initialize: function (url) {
        this.url = url;
    },

    calcUrl: function (xy, mapInfo, RD, mapUrl, emptyInfo) {

        var mapWidth = mapInfo._size.x;
        var mapHeight = mapInfo._size.y;
        var boundsNE = RD.projection.project(mapInfo.getBounds().getNorthEast());
        var boundsSW = RD.projection.project(mapInfo.getBounds().getSouthWest());
        var BBOX = boundsSW.x + ',' + boundsSW.y + ',' + boundsNE.x + ',' + boundsNE.y;
        var zoom = mapInfo.getZoom();

        var buildUrl = mapUrl;
            buildUrl += '?REQUEST=GetFeatureInfo';
            buildUrl += '&EXCEPTIONS=application/vnd.ogc.se_xml';
            buildUrl += '&INFO_FORMAT=text/javascript';
            buildUrl += '&format=image/png';
            buildUrl += '&QUERY_LAYERS=' + APP.servers.waterDepthStatus;
            buildUrl += '&Layers=' + APP.servers.waterDepthStatus;
            buildUrl += '&BBOX=' + BBOX;
            buildUrl += '&WIDTH=' + mapWidth;
            buildUrl += '&HEIGHT=' + mapHeight;
            buildUrl += '&x=' +  xy.x;
            buildUrl += '&y=' + xy.y;
            buildUrl += '&srs=EPSG:28992';

        this.url = buildUrl;

    },

    sync: function (method, model, options) {

        options.dataType = "jsonp";
        options.crossDomain = true;
        options.jsonpCallback = "parseResponse";
        options.contentType = "application/json; charset=utf-8";

        return Backbone.sync(method, model, options);

    }

});

this is the response I get from the server:

parseResponse({"type":"FeatureCollection","totalFeatures":1,"features":[{"type":"Feature","id":"MEGO_overstromingNL_Status.1754","geometry":null,"properties":{"CODE":3}}]})

Any help would be appreciated


问:
exposing composite ID through spring rest repository
I Have a domain object with

id

version

we want to show this in a table, so I need to get it in my rest request.

As suggested, I've implemented a

```<code>@Configuration
public class RepoConf extends RepositoryRestMvcConfiguration {

    public RepoConf(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
        super(context, conversionService);
    }

    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Lot.class);
    }
}
</code>```

I've checked the log that this conf is loaded:

```<code>2017-12-08 07:58:59.966  INFO 10344 --- [  restartedMain] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=repoConf; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [fr/urssaf/genv/back/repository/RepoConf.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]]
</code>```

I have a converter to handle composite ID in URL:

```<code>@Component
class CustomBackendIdConverter implements BackendIdConverter {

    @Override
    public Serializable fromRequestId(String id, Class<?> entityType) {

        switch (entityType.getSimpleName()) {
        case "Lot":
            String[] parts = id.split("_");
            return new LotId(Integer.valueOf(parts[0]), parts[1]);

        default:
            return null;
        }

    }

    @Override
    public String toRequestId(Serializable source, Class<?> entityType) {
        switch (entityType.getSimpleName()) {
        case "Lot":
            LotId id = (LotId) source;
            return String.format("%s_%s", id.getIdLot(), id.getVersionLot());

        default:
            return null;
        }

    }

    @Override
    public boolean supports(Class<?> type) {
        return Lot.class.equals(type);
    }

}
</code>```

But My Id is not shown when I made a request on Lot rest resource, for example on:
http://localhost:9000/lots/1_0
how can I achieve that?

答:
Ok, digging in spring code, it seems that the methods signature off

```<code>RepositoryRestMvcConfiguration
</code>```

has changed, the correct code to expose IDs is:

```<code>@Configuration
public class RepoConf extends RepositoryRestMvcConfiguration {

    public RepoConf(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
        super(context, conversionService);
    }

    @Override
    public ProfileResourceProcessor profileResourceProcessor(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Lot.class);
        return super.profileResourceProcessor(config);
    }

}
</code>```

here is my request working on http://localhost:9000/lots/1_0 :

```<code>{
    "id": {
        "idLot": 1,
        "versionLot": "0"
    },
    "descLot": "test col",
    "etatLot": "init",
    "typeLot": "install",
    "userMaj": "bibi",
    "dateMaj": null,
    "livraisonLots": [],
    "environnementLots": [],
    "_links": {
        "self": {
            "href": "http://localhost:9000/lots/1_0"
        },
        "lot": {
            "href": "http://localhost:9000/lots/1_0"
        }
    }
}
</code>```

Body:
I Have a domain object with

id

version

we want to show this in a table, so I need to get it in my rest request.

As suggested, I've implemented a

@Configuration
public class RepoConf extends RepositoryRestMvcConfiguration {

    public RepoConf(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
        super(context, conversionService);
    }

    protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Lot.class);
    }
}

I've checked the log that this conf is loaded:

2017-12-08 07:58:59.966  INFO 10344 --- [  restartedMain] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=repoConf; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [fr/urssaf/genv/back/repository/RepoConf.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]]

I have a converter to handle composite ID in URL:

@Component
class CustomBackendIdConverter implements BackendIdConverter {

    @Override
    public Serializable fromRequestId(String id, Class<?> entityType) {

        switch (entityType.getSimpleName()) {
        case "Lot":
            String[] parts = id.split("_");
            return new LotId(Integer.valueOf(parts[0]), parts[1]);

        default:
            return null;
        }

    }

    @Override
    public String toRequestId(Serializable source, Class<?> entityType) {
        switch (entityType.getSimpleName()) {
        case "Lot":
            LotId id = (LotId) source;
            return String.format("%s_%s", id.getIdLot(), id.getVersionLot());

        default:
            return null;
        }

    }

    @Override
    public boolean supports(Class<?> type) {
        return Lot.class.equals(type);
    }

}

But My Id is not shown when I made a request on Lot rest resource, for example on:
http://localhost:9000/lots/1_0
how can I achieve that?

Body:
Ok, digging in spring code, it seems that the methods signature off

RepositoryRestMvcConfiguration

has changed, the correct code to expose IDs is:

@Configuration
public class RepoConf extends RepositoryRestMvcConfiguration {

    public RepoConf(ApplicationContext context, ObjectFactory<ConversionService> conversionService) {
        super(context, conversionService);
    }

    @Override
    public ProfileResourceProcessor profileResourceProcessor(RepositoryRestConfiguration config) {
        config.exposeIdsFor(Lot.class);
        return super.profileResourceProcessor(config);
    }

}

here is my request working on http://localhost:9000/lots/1_0 :

{
    "id": {
        "idLot": 1,
        "versionLot": "0"
    },
    "descLot": "test col",
    "etatLot": "init",
    "typeLot": "install",
    "userMaj": "bibi",
    "dateMaj": null,
    "livraisonLots": [],
    "environnementLots": [],
    "_links": {
        "self": {
            "href": "http://localhost:9000/lots/1_0"
        },
        "lot": {
            "href": "http://localhost:9000/lots/1_0"
        }
    }
}


问:
How to Position Anchors in HTML Tables in the Viewport

I am using anchor elemnts in an html table and want to add some padding to the top of the viewport. I figured out, that I can place the anchor in a dummy DIV element inside of the TD element to achieve this. However I also want to highlight the targets table row.

How can I achieve this without javascript?

I have tried several solutions from
HTML position:fixed page header and in-page anchors,
but they all do not work well in html tables.

Here is some minimal working example.

The "D" anchor has correct highlighting, but positioning does not
work.

The "E" anchor has correct positioning, but no highlighting.

tr:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}

div:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>go to D go to E
<table>
  <tr>
    <th>Symbol</th>
    <th>1932 ITU/ICAN Phonetic</th>
  </tr>
  <tr>
    <td>A</td>
    <td>Amsterdam</td>
  </tr>
  <tr>
    <td>B</td>
    <td>Baltimore</td>
  </tr>
  <tr>
    <td>C</td>
    <td>Casablanca</td>
  </tr>
  <tr id="D">
    <td>D</td>
    <td>Denmark</td>
  </tr>
  <tr>
    <td>
      <div id="E"></div>E</td>
    <td>Edison</td>
  </tr>
  <tr>
    <td>F</td>
    <td>Florida</td>
  </tr>
  <tr>
    <td>G</td>
    <td>Gallipoli</td>
  </tr>
  <tr>
    <td>H</td>
    <td>Havana</td>
  </tr>
  <tr>
    <td>I</td>
    <td>Italia</td>
  </tr>
  <tr>
    <td>J</td>
    <td>Jerusalem</td>
  </tr>
  <tr>
    <td>K</td>
    <td>Kilogramme</td>
  </tr>
  <tr>
    <td>L</td>
    <td>Liverpool</td>
  </tr>
  <tr>
    <td>M</td>
    <td>Madagascar</td>
  </tr>
  <tr>
    <td>N</td>
    <td>New York</td>
  </tr>
  <tr>
    <td>O</td>
    <td>Oslo</td>
  </tr>
  <tr>
    <td>P</td>
    <td>Paris</td>
  </tr>
  <tr>
    <td>Q</td>
    <td>Quebec</td>
  </tr>
  <tr>
    <td>R</td>
    <td>Roma</td>
  </tr>
  <tr>
    <td>S</td>
    <td>Santiago</td>
  </tr>
  <tr>
    <td>T</td>
    <td>Tripoli</td>
  </tr>
  <tr>
    <td>U</td>
    <td>Upsala</td>
  </tr>
  <tr>
    <td>V</td>
    <td>Valencia</td>
  </tr>
  <tr>
    <td>W</td>
    <td>Washington</td>
  </tr>
  <tr>
    <td>X</td>
    <td>Xanthippe</td>
  </tr>
  <tr>
    <td>Y</td>
    <td>Yokohama</td>
  </tr>
  <tr>
    <td>Z</td>
    <td>Zurich</td>
  </tr>
</table></code>```

答:
The intended behaviour can be achieved if you consider combining both the initial solutions attempted into one standard, as demonstrated by the code snippet embedded below.

Create separate table-rows for your anchor points, assign your
respective ids to these elements.

Use the adjacent sibling combinator Ref (+) to
declare your pseudo-selector :target styles

Declare your anchor point table-row with absolute positioning and
use margin-top property values to offset the position instead of
the top property (as this will position the element n question
relative to the document or the closest containing/parent element with a relative positioning)

Code Snippet Demonstration:

table {
  border-spacing: 0;
}

.anchor-row:target + tr {
  color: #ee4444;
}

.anchor-row {
  position: absolute;
  margin-top: -40px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>go to D go to E
<table>
  <tr>
    <th>Symbol</th>
    <th>1932 ITU/ICAN Phonetic</th>
  </tr>
  <tr>
    <td>A</td>
    <td>Amsterdam</td>
  </tr>
  <tr>
    <td>B</td>
    <td>Baltimore</td>
  </tr>
  <tr>
    <td>C</td>
    <td>Casablanca</td>
  </tr>
  <tr class="anchor-row" id="D">
    <td colspan="2"></td>
  </tr>
  <tr>
    <td>D</td>
    <td>Denmark</td>
  </tr>
  <tr class="anchor-row" id="E">
    <td colspan="2"></td>
  </tr>
  <tr>
    <td>E</td>
    <td>Edison</td>
  </tr>
  <tr>
    <td>F</td>
    <td>Florida</td>
  </tr>
  <tr>
    <td>G</td>
    <td>Gallipoli</td>
  </tr>
  <tr>
    <td>H</td>
    <td>Havana</td>
  </tr>
  <tr>
    <td>I</td>
    <td>Italia</td>
  </tr>
  <tr>
    <td>J</td>
    <td>Jerusalem</td>
  </tr>
  <tr>
    <td>K</td>
    <td>Kilogramme</td>
  </tr>
  <tr>
    <td>L</td>
    <td>Liverpool</td>
  </tr>
  <tr>
    <td>M</td>
    <td>Madagascar</td>
  </tr>
  <tr>
    <td>N</td>
    <td>New York</td>
  </tr>
  <tr>
    <td>O</td>
    <td>Oslo</td>
  </tr>
  <tr>
    <td>P</td>
    <td>Paris</td>
  </tr>
  <tr>
    <td>Q</td>
    <td>Quebec</td>
  </tr>
  <tr>
    <td>R</td>
    <td>Roma</td>
  </tr>
  <tr>
    <td>S</td>
    <td>Santiago</td>
  </tr>
  <tr>
    <td>T</td>
    <td>Tripoli</td>
  </tr>
  <tr>
    <td>U</td>
    <td>Upsala</td>
  </tr>
  <tr>
    <td>V</td>
    <td>Valencia</td>
  </tr>
  <tr>
    <td>W</td>
    <td>Washington</td>
  </tr>
  <tr>
    <td>X</td>
    <td>Xanthippe</td>
  </tr>
  <tr>
    <td>Y</td>
    <td>Yokohama</td>
  </tr>
  <tr>
    <td>Z</td>
    <td>Zurich</td>
  </tr>
</table></code>```

Body:
I am using anchor elemnts in an html table and want to add some padding to the top of the viewport. I figured out, that I can place the anchor in a dummy DIV element inside of the TD element to achieve this. However I also want to highlight the targets table row.

How can I achieve this without javascript?

I have tried several solutions from
HTML position:fixed page header and in-page anchors,
but they all do not work well in html tables.

Here is some minimal working example.

The "D" anchor has correct highlighting, but positioning does not
work.

The "E" anchor has correct positioning, but no highlighting.

tr:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}

div:target {
  color: #ee4444;
  position: relative;
  top: -40px;
}

go to D go to E

    Symbol
    1932 ITU/ICAN Phonetic

    A
    Amsterdam

    B
    Baltimore

    C
    Casablanca

    D
    Denmark

E
    Edison

    F
    Florida

    G
    Gallipoli

    H
    Havana

    I
    Italia

    J
    Jerusalem

    K
    Kilogramme

    L
    Liverpool

    M
    Madagascar

    N
    New York

    O
    Oslo

    P
    Paris

    Q
    Quebec

    R
    Roma

    S
    Santiago

    T
    Tripoli

    U
    Upsala

    V
    Valencia

    W
    Washington

    X
    Xanthippe

    Y
    Yokohama

    Z
    Zurich

Body:
The intended behaviour can be achieved if you consider combining both the initial solutions attempted into one standard, as demonstrated by the code snippet embedded below.

Create separate table-rows for your anchor points, assign your
respective ids to these elements.

Use the adjacent sibling combinator Ref (+) to
declare your pseudo-selector :target styles

Declare your anchor point table-row with absolute positioning and
use margin-top property values to offset the position instead of
the top property (as this will position the element n question
relative to the document or the closest containing/parent element with a relative positioning)

Code Snippet Demonstration:

table {
  border-spacing: 0;
}

.anchor-row:target + tr {
  color: #ee4444;
}

.anchor-row {
  position: absolute;
  margin-top: -40px;
}

<a href="#D">go to D</a> <a href="#E">go to E</a>
<table>
  <tr>
    <th>Symbol</th>
    <th>1932 ITU/ICAN Phonetic</th>
  </tr>
  <tr>
    <td>A</td>
    <td>Amsterdam</td>
  </tr>
  <tr>
    <td>B</td>
    <td>Baltimore</td>
  </tr>
  <tr>
    <td>C</td>
    <td>Casablanca</td>
  </tr>
  <tr class="anchor-row" id="D">
    <td colspan="2"></td>
  </tr>
  <tr>
    <td>D</td>
    <td>Denmark</td>
  </tr>
  <tr class="anchor-row" id="E">
    <td colspan="2"></td>
  </tr>
  <tr>
    <td>E</td>
    <td>Edison</td>
  </tr>
  <tr>
    <td>F</td>
    <td>Florida</td>
  </tr>
  <tr>
    <td>G</td>
    <td>Gallipoli</td>
  </tr>
  <tr>
    <td>H</td>
    <td>Havana</td>
  </tr>
  <tr>
    <td>I</td>
    <td>Italia</td>
  </tr>
  <tr>
    <td>J</td>
    <td>Jerusalem</td>
  </tr>
  <tr>
    <td>K</td>
    <td>Kilogramme</td>
  </tr>
  <tr>
    <td>L</td>
    <td>Liverpool</td>
  </tr>
  <tr>
    <td>M</td>
    <td>Madagascar</td>
  </tr>
  <tr>
    <td>N</td>
    <td>New York</td>
  </tr>
  <tr>
    <td>O</td>
    <td>Oslo</td>
  </tr>
  <tr>
    <td>P</td>
    <td>Paris</td>
  </tr>
  <tr>
    <td>Q</td>
    <td>Quebec</td>
  </tr>
  <tr>
    <td>R</td>
    <td>Roma</td>
  </tr>
  <tr>
    <td>S</td>
    <td>Santiago</td>
  </tr>
  <tr>
    <td>T</td>
    <td>Tripoli</td>
  </tr>
  <tr>
    <td>U</td>
    <td>Upsala</td>
  </tr>
  <tr>
    <td>V</td>
    <td>Valencia</td>
  </tr>
  <tr>
    <td>W</td>
    <td>Washington</td>
  </tr>
  <tr>
    <td>X</td>
    <td>Xanthippe</td>
  </tr>
  <tr>
    <td>Y</td>
    <td>Yokohama</td>
  </tr>
  <tr>
    <td>Z</td>
    <td>Zurich</td>
  </tr>
</table>


问:
Set Correct header for SOAP request
I have a generated class from a SOAP api.

When Sending out the request it sends in this format:

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<Login>
<username>Ayo.K</username>
<password>password</password>
</Login>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

But what the api expects is:

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:adm="http://example.org/test_Service">
<soapenv:Header/>
<soapenv:Body>
<adm:Login>
<adm:username>Ayo.K</adm:username>
<adm:password>password</adm:password>
</adm:Login>
</soapenv:Body>
</soapenv:Envelope>
</code>```

My Login Class:

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
        name = "",
        propOrder = {"username", "password"}
)
@XmlRootElement(
        name = "Login",
)
public class Login {
    protected String username;
    protected String password;

    public Login() {
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String value) {
        this.username = value;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String value) {
        this.password = value;
    }
}
</code>```

When i add namespace = "http://example.org/test_Service" to the @XmlRootElement for the Login class I get:

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns3:Login xmlns:ns3="http://example.org/test_Service">
<username>Ayo.K</username>
<password>password</password>
</ns3:Login>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

How can I set the correct namespace in the right format?

Thanks!

答:
Eventually found a solution to my problem myself, but my implementation had to change.

First I used SOAPPart and SOAPEnvelope to create my request. I could then explicitly set my namespace declarations. I folowed the implementation here

Then my generated classes changed a bit

Login Class

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
        name = "",
        propOrder = {"username", "password"}
)
@XmlRootElement(
        name = "Login",
        namespace = "http://example.org/test_Service"
)
public class Login {
    protected String username;
    protected String password;

    public Login() {
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String value) {
        this.username = value;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String value) {
        this.password = value;
    }
}
</code>```

Title: Set Correct header for SOAP request

Body:
I have a generated class from a SOAP api.

When Sending out the request it sends in this format:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<Login>
<username>Ayo.K</username>
<password>password</password>
</Login>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

But what the api expects is:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:adm="http://example.org/test_Service">
<soapenv:Header/>
<soapenv:Body>
<adm:Login>
<adm:username>Ayo.K</adm:username>
<adm:password>password</adm:password>
</adm:Login>
</soapenv:Body>
</soapenv:Envelope>

My Login Class:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
        name = "",
        propOrder = {"username", "password"}
)
@XmlRootElement(
        name = "Login",
)
public class Login {
    protected String username;
    protected String password;

    public Login() {
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String value) {
        this.username = value;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String value) {
        this.password = value;
    }
}

When i add namespace = "http://example.org/test_Service" to the @XmlRootElement for the Login class I get:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns3:Login xmlns:ns3="http://example.org/test_Service">
<username>Ayo.K</username>
<password>password</password>
</ns3:Login>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

How can I set the correct namespace in the right format?

Thanks!

Body:
Eventually found a solution to my problem myself, but my implementation had to change.

First I used SOAPPart and SOAPEnvelope to create my request. I could then explicitly set my namespace declarations. I folowed the implementation here

Then my generated classes changed a bit

Login Class

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
        name = "",
        propOrder = {"username", "password"}
)
@XmlRootElement(
        name = "Login",
        namespace = "http://example.org/test_Service"
)
public class Login {
    protected String username;
    protected String password;

    public Login() {
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String value) {
        this.username = value;
    }

    public String getPassword() {
        return this.password;
    }

    public void setPassword(String value) {
        this.password = value;
    }
}


问:
How do I make a duplicate of a folder on a remote server with asp.net and keep it speedy?
I have an ASP.NET page that needs to make a duplicate of a folder that resides on another server.   All of the file IO runs on the remote server.  This is not a question about how to copy files from one computer to another, nor is it a question about how to do a recursive directory copy.  Those tasks are pretty easy.

What I've found is that making a copy of a directory on the server running the ASP.NET application is nice and fast.  As soon as the source and destination folder reside on a remote server (i.e. a file server), it becomes incredibly slow.  I can't figure out why it's so slow, which means I can't really figure out a good way to get around the problem.  To be perfectly clear, here's an example of what I'm trying to accomplish:

The asp.net application is running on a server named "webserver"

The files are located on a server named "fileserver"

I need the website running on "webserver" to make a recursive duplicate of \\fileserver\files\setup named \\fileserver\files\setup_temp

If there are already answers to this question then please point me in the right direction.  I found loads of answers to the "how do I make a recursive copy" and "how do I copy a folder to another server"

答: How does the Webserver communicate with the Fileserver? The transfer of data between those two is definitely your bottleneck. I would recommend using a WCF service to transfer one file/folder at a time (depending on the size of the data). If the files are really large i would also recommend enabling streaming.</p>


问:
Setting value in JS, but codebehind doesn't get updated value. ASP.Net
I'm using bootbox prompt to do validation before saving, in the callback function I'm setting a hiddenfield value and then going into a button click event. But hiddenfield in the C# part doesn't get the value I've set in the JS. How should I fix this?

JS:

```<code>function notePrompt() {
    var protNumber = $("#hfProtNumberGen").val();
    var hfNote = document.getElementById("<%= hfNote.ClientID %>");
    var btnHidden = document.getElementById('btnHidden');
    if (protNumber != "") {
        bootbox.prompt({
            title: "Въведете причина за промяната. Повърдете запазването на информацията.",
            inputType: 'textarea',
            buttons: {
                confirm: {
                    label: "Запази"
                },
                cancel: {
                    label: "Откажи"
                }
            },
            callback: function (result) {
                if (result == null) {
                    hfNote.value = "";
                }
                else {
                    var MaxLenghtResult = result.slice(0, 200);
                    hfNote.value = MaxLenghtResult;
                    if (hfNote.value != "") {
                        setTimeout(function () { btnHidden.click(); }, 1000);
                    }
                }
            }
        });
    }
    else {
        setTimeout(function () { btnHidden.click(); }, 1000);
    }
}
</code>```

C#:

```<code>string Note = hfNote.Value; //always gets ""
</code>```

答:
you have to do like this , means you have to make control runat ="server" and in javascript need to udpate value in control by getting clientid of control </p>

```<code>//axps file - this seems working for you
<asp:HiddenField ID = "hfName" runat = "server" />

//javascript --- you need to this change
document.getElementById("<%=hfName.ClientID %>").value = MaxLenghtResult;

//in aspx.cs file
string note = Request.Form[hfName.UniqueID];
</code>```

Body:
I'm using bootbox prompt to do validation before saving, in the callback function I'm setting a hiddenfield value and then going into a button click event. But hiddenfield in the C# part doesn't get the value I've set in the JS. How should I fix this?

JS:

function notePrompt() {
    var protNumber = $("#hfProtNumberGen").val();
    var hfNote = document.getElementById("<%= hfNote.ClientID %>");
    var btnHidden = document.getElementById('btnHidden');
    if (protNumber != "") {
        bootbox.prompt({
            title: "Въведете причина за промяната. Повърдете запазването на информацията.",
            inputType: 'textarea',
            buttons: {
                confirm: {
                    label: "Запази"
                },
                cancel: {
                    label: "Откажи"
                }
            },
            callback: function (result) {
                if (result == null) {
                    hfNote.value = "";
                }
                else {
                    var MaxLenghtResult = result.slice(0, 200);
                    hfNote.value = MaxLenghtResult;
                    if (hfNote.value != "") {
                        setTimeout(function () { btnHidden.click(); }, 1000);
                    }
                }
            }
        });
    }
    else {
        setTimeout(function () { btnHidden.click(); }, 1000);
    }
}

C#:

string Note = hfNote.Value; //always gets ""

Body:
you have to do like this , means you have to make control runat ="server" and in javascript need to udpate value in control by getting clientid of control

//axps file - this seems working for you
<asp:HiddenField ID = "hfName" runat = "server" />

//javascript --- you need to this change
document.getElementById("<%=hfName.ClientID %>").value = MaxLenghtResult;

//in aspx.cs file
string note = Request.Form[hfName.UniqueID];


问:
When formflatten is set to false using PdfStamper still flattens few form fields
I don't want my PDF file to be flattened by PdfStamper. So I am doing stamper.setFormFlattening(false). But still there are few fields which are flattened. Most of them are dropdowns and checkboxes. Can I know what is making it to flatten?

答:
You can check whether it is a 'reader-enabled'/extended rights PDF by opening that document in *dobe reader afterwards. Current versions then show an error message indicating a problem with the usage rights. Here's the code of what mkl describes:</p>

```<code>PdfDictionary perms = stamper.getReader().getCatalog().getAsDict(PdfName.PERMS);

if (perms != null){
    perms.remove(PdfName.UR);
    perms.remove(PdfName.UR3);

    if (perms.size() == 0) stamper.getReader().getCatalog().remove(PdfName.PERMS);
}
</code>```

Body:
You can check whether it is a 'reader-enabled'/extended rights PDF by opening that document in *dobe reader afterwards. Current versions then show an error message indicating a problem with the usage rights. Here's the code of what mkl describes:

PdfDictionary perms = stamper.getReader().getCatalog().getAsDict(PdfName.PERMS);

if (perms != null){
    perms.remove(PdfName.UR);
    perms.remove(PdfName.UR3);

    if (perms.size() == 0) stamper.getReader().getCatalog().remove(PdfName.PERMS);
}