问:
WebApi with backslash (%2f) in ID parameter causes 404 not found
I am calling a WebAPI method with a parameter containing a / (%2f).  If I call this with a parameter without this character it works fine.

Following advice in this link Escape characters in WebApi call I tried the following, but it hasn't made any difference.

```<code><httpRuntime targetFramework="4.5.1" relaxedUrlToFileSystemMapping="true"/>
</code>```

The code i am using to call the WebAPI method is below

```<code>var id = "AA/F1"; // This causes a problem of 404 not found
var workingId = "BB-F2"; // This works fine
using (var client = new HttpClient(new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip}))
{
    var uri = new Uri(string.Format("http://[testServer]/[Controller]/Get/{0}", WebUtility.UrlEncode(id)));
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    var response = client.GetAsync(uri).GetAwaiter().GetResult();
    if (response.IsSuccessStatusCode)
        return JsonConvert.DeserializeObject<ReturnType>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

    throw new Exception(response.ReasonPhrase);
}
</code>```

I only have one route configured - as so:

```<code>GlobalConfiguration.Configuration.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { id = RouteParameter.Optional });
</code>```

I have also tried hitting it directly using Fiddler and get the same error.

答:
You can try  var id = "AA%2fF1";

Update:

You can also use Base64 encoding, something similar to this:

```<code>var id = "AA/F1";
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(id);
var encodedId = System.Convert.ToBase64String(plainTextBytes);
</code>```

Body:
I am calling a WebAPI method with a parameter containing a / (%2f).  If I call this with a parameter without this character it works fine.

Following advice in this link Escape characters in WebApi call I tried the following, but it hasn't made any difference.

<httpRuntime targetFramework="4.5.1" relaxedUrlToFileSystemMapping="true"/>

The code i am using to call the WebAPI method is below

var id = "AA/F1"; // This causes a problem of 404 not found
var workingId = "BB-F2"; // This works fine
using (var client = new HttpClient(new HttpClientHandler {AutomaticDecompression = DecompressionMethods.GZip}))
{
    var uri = new Uri(string.Format("http://[testServer]/[Controller]/Get/{0}", WebUtility.UrlEncode(id)));
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
    var response = client.GetAsync(uri).GetAwaiter().GetResult();
    if (response.IsSuccessStatusCode)
        return JsonConvert.DeserializeObject<ReturnType>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());

    throw new Exception(response.ReasonPhrase);
}

I only have one route configured - as so:

GlobalConfiguration.Configuration.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { id = RouteParameter.Optional });

I have also tried hitting it directly using Fiddler and get the same error.

Body:
You can try  var id = "AA%2fF1";

Update:

You can also use Base64 encoding, something similar to this:

var id = "AA/F1";
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(id);
var encodedId = System.Convert.ToBase64String(plainTextBytes);


来源: stackexchange

问:
How to generate different headers in first page and other pages in poi word XWPF?
I want to generate different headers in first page and other pages in poi word, So I used XWPFHeaderFooterPolicy.FIRST and XWPFHeaderFooterPolicy.DEFAULT. when I using XWPFHeaderFooterPolicy.DEFAULT I can insert my header successfully, but when I change to XWPFHeaderFooterPolicy.FIRST, I cannot see there is a header in my first page, this is my code in below, what's wrong with it? thanks!  </p>

```<code>XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.FIRST);
      paragraph = header.createParagraph();
      paragraph.setAlignment(ParagraphAlignment.LEFT);
      run = paragraph.createRun();
      run.setText("header");
</code>```

答:
That there is a different header set for first page only, means not that this header will also be shown. In Word GUI there is a checkbox [x] Different First Page in Header & Footer Tools to achieve that.

And according Office Open XML Part 4 - Markup Language Reference there must a boolean XML element titlePg be set to determine that there is a title page present.

In actual final apache poi version 3.15 this XML element titlePg can only be set using underlying low level objects using doc.getDocument().getBody().getSectPr().addNewTitlePg();.

But apache poi version 3.16 Beta 2 has doc.createHeader(HeaderFooterType.FIRST); which sets titlePg flag in XML.

Complete example:

```<code>import java.io.*;

import org.apache.poi.wp.usermodel.*;

import org.apache.poi.xwpf.usermodel.*;

public class CreateWordHeaderFooterDifferent {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

  // the body content
  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The Body:");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();
  run.setText("Lorem ipsum.... page 1");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();
  run.addBreak(BreakType.PAGE);
  run.setText("Lorem ipsum.... page 2");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();
  run.addBreak(BreakType.PAGE);
  run.setText("Lorem ipsum.... page 3");

  // create first page header
  XWPFHeader header = doc.createHeader(HeaderFooterType.FIRST);

  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  run = paragraph.createRun();
  run.setText("The first page header:");

  // create default page header
  header = doc.createHeader(HeaderFooterType.DEFAULT);

  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  run = paragraph.createRun();
  run.setText("The default page header:");

  // create footer
  XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);

  paragraph = footer.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.CENTER);

  run = paragraph.createRun();
  run.setText("Page ");
  paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* MERGEFORMAT");
  run = paragraph.createRun();
  run.setText(" of ");
  paragraph.getCTP().addNewFldSimple().setInstr("NUMPAGES \\* MERGEFORMAT");

  doc.write(new FileOutputStream("CreateWordHeaderFooterDifferent.docx"));

 }
}
</code>```

But in my opinion the setting titlePg flag in XML automatically while HeaderFooterType.FIRST is created is not correct. Since Word can toggle between  [x] Different First Page and  [] Different First Page, apache poi should also be able to do so. So the setting the titlePg flag should be a method in XWPFDocument.

ContentLicense: CC BY-SA 3.0

Body:
I want to generate different headers in first page and other pages in poi word, So I used XWPFHeaderFooterPolicy.FIRST and XWPFHeaderFooterPolicy.DEFAULT. when I using XWPFHeaderFooterPolicy.DEFAULT I can insert my header successfully, but when I change to XWPFHeaderFooterPolicy.FIRST, I cannot see there is a header in my first page, this is my code in below, what's wrong with it? thanks!

XWPFHeader header = headerFooterPolicy.createHeader(XWPFHeaderFooterPolicy.FIRST);
      paragraph = header.createParagraph();
      paragraph.setAlignment(ParagraphAlignment.LEFT);
      run = paragraph.createRun();
      run.setText("header");

Body:
That there is a different header set for first page only, means not that this header will also be shown. In Word GUI there is a checkbox [x] Different First Page in Header & Footer Tools to achieve that.

And according Office Open XML Part 4 - Markup Language Reference there must a boolean XML element titlePg be set to determine that there is a title page present.

In actual final apache poi version 3.15 this XML element titlePg can only be set using underlying low level objects using doc.getDocument().getBody().getSectPr().addNewTitlePg();.

But apache poi version 3.16 Beta 2 has doc.createHeader(HeaderFooterType.FIRST); which sets titlePg flag in XML.

Complete example:

import java.io.*;

import org.apache.poi.wp.usermodel.*;

import org.apache.poi.xwpf.usermodel.*;

public class CreateWordHeaderFooterDifferent {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

  // the body content
  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run=paragraph.createRun();
  run.setText("The Body:");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();
  run.setText("Lorem ipsum.... page 1");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();
  run.addBreak(BreakType.PAGE);
  run.setText("Lorem ipsum.... page 2");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();
  run.addBreak(BreakType.PAGE);
  run.setText("Lorem ipsum.... page 3");

  // create first page header
  XWPFHeader header = doc.createHeader(HeaderFooterType.FIRST);

  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  run = paragraph.createRun();
  run.setText("The first page header:");

  // create default page header
  header = doc.createHeader(HeaderFooterType.DEFAULT);

  paragraph = header.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.LEFT);

  run = paragraph.createRun();
  run.setText("The default page header:");

  // create footer
  XWPFFooter footer = doc.createFooter(HeaderFooterType.DEFAULT);

  paragraph = footer.createParagraph();
  paragraph.setAlignment(ParagraphAlignment.CENTER);

  run = paragraph.createRun();
  run.setText("Page ");
  paragraph.getCTP().addNewFldSimple().setInstr("PAGE \\* MERGEFORMAT");
  run = paragraph.createRun();
  run.setText(" of ");
  paragraph.getCTP().addNewFldSimple().setInstr("NUMPAGES \\* MERGEFORMAT");

  doc.write(new FileOutputStream("CreateWordHeaderFooterDifferent.docx"));

 }
}

But in my opinion the setting titlePg flag in XML automatically while HeaderFooterType.FIRST is created is not correct. Since Word can toggle between  [x] Different First Page and  [] Different First Page, apache poi should also be able to do so. So the setting the titlePg flag should be a method in XWPFDocument.


问:
Spring JNDI-lookup ternary operator
I have XML configuration in my web-app. I have following tag in this file:

```<code><jee:jndi-lookup id="my.super.queue" resource-ref="true"
     jndi-name="#{ ${my.flag} ? ${jms.my.queue1} : ${jms.my.queue2} }"/>
</code>```

The idea is to initiate queue based on a flag in properties. But, it seems that jee:jndi does not support ternary operator. I have the following error:

```<code>Error creating bean with name 'my.super.queue': Initialization of bean failed
Property or field 'jms' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
<jee:jndi-lookup id="my.super.queue" resource-ref="true" jndi-name="#{ ${my.flag} ? ${jms.my.queue1} : ${jms.my.queue2} }"/>
</code>```

How to fix it?

答:
Fixed. Need just to add quotes ' to the operator:

```<code><jee:jndi-lookup id="my.super.queue" resource-ref="true"
     jndi-name="#{ ${my.flag} ? '${jms.my.queue1}' : '${jms.my.queue2}' }"/>
</code>```

That's all. Thanks @M. Denium for inspiration.

Title: Spring JNDI-lookup ternary operator

Body:
I have XML configuration in my web-app. I have following tag in this file:

<jee:jndi-lookup id="my.super.queue" resource-ref="true"
     jndi-name="#{ ${my.flag} ? ${jms.my.queue1} : ${jms.my.queue2} }"/>

The idea is to initiate queue based on a flag in properties. But, it seems that jee:jndi does not support ternary operator. I have the following error:

Error creating bean with name 'my.super.queue': Initialization of bean failed
Property or field 'jms' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public?
<jee:jndi-lookup id="my.super.queue" resource-ref="true" jndi-name="#{ ${my.flag} ? ${jms.my.queue1} : ${jms.my.queue2} }"/>

How to fix it?

Body:
Fixed. Need just to add quotes ' to the operator:

<jee:jndi-lookup id="my.super.queue" resource-ref="true"
     jndi-name="#{ ${my.flag} ? '${jms.my.queue1}' : '${jms.my.queue2}' }"/>

That's all. Thanks @M. Denium for inspiration.


问:
How can i customize the button if it set a AcceptButton of the form?
I have implemented the custom button control with some additional options. And added my custom button into the form. When i set the Form.Acception is the added custom button, then I want to do some customization in the Button. I want to customize the button appearance in the Custom button class implementation, when it marked as AcceptButton of the Form.

Anyone suggest how can i know the button is marked as AcceptButton of the form in Button class?

答:
You could traverse the parents to find the form via the parent property of its base class Control:

```<code>public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();
    }

    private Form CheckParentForm(Control current)
    {
        // if the current is a form, return it.
        if (current is Form)
            return (Form)current;

        // if the parent of the current not is null,
        if (current.Parent != null)
            // check his parent.
            return CheckParentForm(current.Parent);

        // there is no parent found and we didn't find a Form.
        return null;
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        // find the parent form.
        var form = CheckParentForm(this);

        // if a form was found,
        if (form != null)
            // check if this is set as accept button
            if (this == form.AcceptButton)
                // for example, change the background color (i used for testing)
                this.BackColor = Color.RosyBrown;
    }
}
</code>```

Because of the recursion, it also works when the Button is placed on a Panel.

Note: The accept button must be set before OnCreateControl is called (for example in the form's constructor)

After some googling I found a standard implementation:

You can also use: this.FindForm();

```<code>public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();

    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        var form = FindForm();

        if (form != null)
            if (this == form.AcceptButton)
                this.BackColor = Color.RosyBrown;

    }
}
</code>```

Event shorter in C# 6.0:

```<code>public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();

    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        if (this == FindForm()?.AcceptButton)
            this.BackColor = Color.RosyBrown;
    }
}
</code>```

\o/

Body:
You could traverse the parents to find the form via the parent property of its base class Control:

public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();
    }

    private Form CheckParentForm(Control current)
    {
        // if the current is a form, return it.
        if (current is Form)
            return (Form)current;

        // if the parent of the current not is null,
        if (current.Parent != null)
            // check his parent.
            return CheckParentForm(current.Parent);

        // there is no parent found and we didn't find a Form.
        return null;
    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        // find the parent form.
        var form = CheckParentForm(this);

        // if a form was found,
        if (form != null)
            // check if this is set as accept button
            if (this == form.AcceptButton)
                // for example, change the background color (i used for testing)
                this.BackColor = Color.RosyBrown;
    }
}

Because of the recursion, it also works when the Button is placed on a Panel.

Note: The accept button must be set before OnCreateControl is called (for example in the form's constructor)

After some googling I found a standard implementation:

You can also use: this.FindForm();

public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();

    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        var form = FindForm();

        if (form != null)
            if (this == form.AcceptButton)
                this.BackColor = Color.RosyBrown;

    }
}

Event shorter in C# 6.0:

public partial class MyButton : Button
{
    public MyButton()
    {
        InitializeComponent();

    }

    protected override void OnCreateControl()
    {
        base.OnCreateControl();

        if (this == FindForm()?.AcceptButton)
            this.BackColor = Color.RosyBrown;
    }
}

\o/


问:
How to add dividers in Bottom Navigation View
I'm trying to add divider in menu items of BottomNavigationView

All items are showing horizontally in the bottom but I'm not able to add dividers into it.

Bottom Navigation View xml:

```<code><android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:focusable="false"
        app:itemBackground="@color/colorPrimaryDark"
        app:itemIconTint="@color/bottom_navigation_selector"
        app:itemTextColor="@color/bottom_navigation_selector"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom"
        app:menu="@menu/bottom_nav_items" />
</code>```

And bottom_nav_items.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/menu_family"
    android:checked="false"
    android:icon="@drawable/family"
    android:title="@string/family" />
<item
    android:id="@+id/menu_me"
    android:checked="false"
    android:icon="@drawable/me"
    android:title="@string/me" />

<item
    android:id="@+id/menu_blank"
    android:checkable="false"
    android:enabled="false"
    android:title="" />
<item
    android:id="@+id/menu_event"
    android:checked="false"
    android:icon="@drawable/event"
    android:title="@string/event" />
<item
    android:id="@+id/menu_more"
    android:checked="false"
    android:icon="@drawable/more"
    android:title="@string/more" />
</code>```

Thanks for your support.

答:
create a drawable item_bg.xml like this,

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#F4F4F4" />
        </shape>
    </item>

    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="#EAEAEA" />
        </shape>

    </item>

</layer-list>
</code>```

Then add it to NavigationView as app:itemBackground="@drawable/item_bg"

```<code> <android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:focusable="false"
    app:itemBackground="@drawable/item_bg"
    app:itemIconTint="@color/bottom_navigation_selector"
    app:itemTextColor="@color/bottom_navigation_selector"
    app:layout_anchor="@id/container"
    app:layout_anchorGravity="bottom"
    app:menu="@menu/bottom_nav_items" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add divider in menu items of BottomNavigationView

All items are showing horizontally in the bottom but I'm not able to add dividers into it.

Bottom Navigation View xml:

<android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:focusable="false"
        app:itemBackground="@color/colorPrimaryDark"
        app:itemIconTint="@color/bottom_navigation_selector"
        app:itemTextColor="@color/bottom_navigation_selector"
        app:layout_anchor="@id/container"
        app:layout_anchorGravity="bottom"
        app:menu="@menu/bottom_nav_items" />

And bottom_nav_items.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/menu_family"
    android:checked="false"
    android:icon="@drawable/family"
    android:title="@string/family" />
<item
    android:id="@+id/menu_me"
    android:checked="false"
    android:icon="@drawable/me"
    android:title="@string/me" />

<item
    android:id="@+id/menu_blank"
    android:checkable="false"
    android:enabled="false"
    android:title="" />
<item
    android:id="@+id/menu_event"
    android:checked="false"
    android:icon="@drawable/event"
    android:title="@string/event" />
<item
    android:id="@+id/menu_more"
    android:checked="false"
    android:icon="@drawable/more"
    android:title="@string/more" />

Thanks for your support.

Body:
create a drawable item_bg.xml like this,

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle" >
            <solid android:color="#F4F4F4" />
        </shape>
    </item>

    <item android:top="-2dp" android:right="-2dp" android:left="-2dp">
        <shape>
            <solid android:color="@android:color/transparent" />
            <stroke
                android:width="1dp"
                android:color="#EAEAEA" />
        </shape>

    </item>

</layer-list>

Then add it to NavigationView as app:itemBackground="@drawable/item_bg"

 <android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:focusable="false"
    app:itemBackground="@drawable/item_bg"
    app:itemIconTint="@color/bottom_navigation_selector"
    app:itemTextColor="@color/bottom_navigation_selector"
    app:layout_anchor="@id/container"
    app:layout_anchorGravity="bottom"
    app:menu="@menu/bottom_nav_items" />


问:
Dynamically accessing Ruby JSON object variables
```<code>puts @file
# {
#   "0.js": "js/0.js",
#   "about-page.js": "js/about-page.js",
#   "img/heart.png": "img/ae985f1437f67f39c4393e31c6785970.png",
#   "index-page.js": "js/index-page.js",
#   "init.js": "js/init.js",
#   "main.js": "js/main.js"
# }
a = "0.js"
puts a // => "0.js"
puts @file[a] // => "0.js"  ????!!!???
</code>```

Why the above code wouldn't work? I am expecting the last line to output "js/0.js" instead of "0.js".

Thanks

答:
First, convert the string into an object using JSON.parse()

Then, your code will work fine.

```<code>require json

file = '{"0.js": "js/0.js","about-page.js": "js/about-page.js","img/heart.png": "img/ae985f1437f67f39c4393e31c6785970.png","index-page.js": "js/index-page.js","init.js": "js/init.js","main.js": "js/main.js"}'

file2 = JSON.parse(file)

==> {"0.js"=>"js/0.js", "about-page.js"=>"js/about-page.js", "img/heart.png"=>"img/ae985f1437f67f39c4393e31c6785970.png", "index-page.js"=>"js/index-page.js", "init.js"=>"js/init.js", "main.js"=>"js/main.js"}

a = "0.js"

puts a  => "0.js"

puts file2[a] // => "js/0.js"
</code>```

Body:
puts @file
# {
#   "0.js": "js/0.js",
#   "about-page.js": "js/about-page.js",
#   "img/heart.png": "img/ae985f1437f67f39c4393e31c6785970.png",
#   "index-page.js": "js/index-page.js",
#   "init.js": "js/init.js",
#   "main.js": "js/main.js"
# }
a = "0.js"
puts a // => "0.js"
puts @file[a] // => "0.js"  ????!!!???

Why the above code wouldn't work? I am expecting the last line to output "js/0.js" instead of "0.js".

Thanks

Body:
First, convert the string into an object using JSON.parse()

Then, your code will work fine.

require json

file = '{"0.js": "js/0.js","about-page.js": "js/about-page.js","img/heart.png": "img/ae985f1437f67f39c4393e31c6785970.png","index-page.js": "js/index-page.js","init.js": "js/init.js","main.js": "js/main.js"}'

file2 = JSON.parse(file)

==> {"0.js"=>"js/0.js", "about-page.js"=>"js/about-page.js", "img/heart.png"=>"img/ae985f1437f67f39c4393e31c6785970.png", "index-page.js"=>"js/index-page.js", "init.js"=>"js/init.js", "main.js"=>"js/main.js"}

a = "0.js"

puts a  => "0.js"

puts file2[a] // => "js/0.js"


问:
How to bind a multi-select element with object array?
I have a  element , which I would like to bind with a model to get/set the value and to populate it from a list using angular 1

The way I have it, I am able to bind it from UI to model, not vice versa, what am I doing wrong?

HTML:

```<code><div ng-controller="MyCtrl">
    <select class="form-control"
    ng-options="o as o.prop for o in brands"
    ng-model="selectedBrands"
    multiple="multiple"
    >
    </select>
</div>
</code>```

JS:

```<code>var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.brands = [{
    prop: 1
  }, {
    prop: 2
  }, {
    prop: 3
  }];
  $scope.selectedBrands = [{
    prop: 2
  }];
}
</code>```

JSFiddle:

http://jsfiddle.net/4L8b7cke/

答:
Reuse $scope.brands elements, do not create new for selected items, because ngModel watches the model by reference.

```<code>$scope.selectedBrands = [$scope.brands[0],$scope.brands[1]];
</code>```

Update:

By default, ngModel watches the model by reference, not value. This is important to know when binding the select to a model that is an object or a collection.

From ngOptions documentation

Body:
I have a  element , which I would like to bind with a model to get/set the value and to populate it from a list using angular 1

The way I have it, I am able to bind it from UI to model, not vice versa, what am I doing wrong?

HTML:

    <select class="form-control"
    ng-options="o as o.prop for o in brands"
    ng-model="selectedBrands"
    multiple="multiple"
    >
    </select>

JS:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.brands = [{
    prop: 1
  }, {
    prop: 2
  }, {
    prop: 3
  }];
  $scope.selectedBrands = [{
    prop: 2
  }];
}

JSFiddle:

http://jsfiddle.net/4L8b7cke/

Body:
Reuse $scope.brands elements, do not create new for selected items, because ngModel watches the model by reference.

$scope.selectedBrands = [$scope.brands[0],$scope.brands[1]];

Update:

By default, ngModel watches the model by reference, not value. This is important to know when binding the select to a model that is an object or a collection.

From ngOptions documentation


问:
Firebase database change data notify with RecyclerView Adapter Android
Data Structure:

```<code>factoryConfigs.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            if (dataSnapshot != null && dataSnapshot.getValue() != null){
                Log.i("onChildAdded", "onChildAdded " + dataSnapshot.toString());
                try{
                    FactoryConfig config = dataSnapshot.getValue(FactoryConfig.class);
                    configs.add(config);
                    mFactoryList.scrollToPosition(configs.size());
                    mAdapter.notifyItemInserted(configs.size());

                }catch (Exception e){
                    Log.e("FactoryFragment", e.getMessage());
                }
            }

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            Log.i("datachange", "dataChanged" + dataSnapshot.toString());

            mAdapter.notifyDataSetChanged();

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

I have factory_line data that increases as needed.
I need to know what database has to change so I can modify my list and notify the adapter. I can't figure out how to find the adapter position where  the data has been changed.

答: Get the position of the of the item in the adapter and apply use notifyItemChanged(int position).</p>

Body:
Data Structure:

factoryConfigs.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            if (dataSnapshot != null && dataSnapshot.getValue() != null){
                Log.i("onChildAdded", "onChildAdded " + dataSnapshot.toString());
                try{
                    FactoryConfig config = dataSnapshot.getValue(FactoryConfig.class);
                    configs.add(config);
                    mFactoryList.scrollToPosition(configs.size());
                    mAdapter.notifyItemInserted(configs.size());

                }catch (Exception e){
                    Log.e("FactoryFragment", e.getMessage());
                }
            }

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            Log.i("datachange", "dataChanged" + dataSnapshot.toString());

            mAdapter.notifyDataSetChanged();

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

I have factory_line data that increases as needed.
I need to know what database has to change so I can modify my list and notify the adapter. I can't figure out how to find the adapter position where  the data has been changed.


问:
How import dependent jars to JWS?
We are migrating from Applet to JWS. How to provide dependent jar to JWS? Kindly check my JNLP file.

<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/JWSINSTEADOFAPPLET/" href="HelloWorld.jnlp">
<information>
         <title>HelloWorld</title>
         <vendor>IBM - JWS example of HelloWorld</vendor>`
    enter code here
         <description>HelloWorld - Example of JWS</description>
         <description kind="short">HelloWorld example</description>
         <offline-allowed/>
    </information>
    <security>
    <all-permissions/>
</security>
    <resources>
     <j2se version="1.3+"/>
     <jar href="Harper_Colin.jar" main="true"/>
     <jar href="lib/commons-codec-1.10.jar"/>
     <jar href="lib/commons-httpclient-3.1.jar"/>
     <jar href="lib/commons-logging-1.2.jar"/>
     <jar href="lib/commons-net-3.3.jar"/>
     <jar href="lib/httpclient-4.0.2-sources.jar"/>
     <jar href="lib/httpclient-4.5.3.jar"/>
     <jar href="lib/httpcore-4.4.6.jar"/>
     <jar href="lib/plugin.jar"/>

      </resources>
 <application-desc main-class="Harper_Upload_Final"/>
    </jnlp>
```

<p>Even if  provided dependent jars under resources tab, I am getting error like below: </p>

```java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpUriRequest
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.getMethod0(Unknown Source)
    at java.lang.Class.getMethod(Unknown Source)
    at com.sun.javaws.Launcher.doLaunchApp(Unknown Source)
    at com.sun.javaws.Launcher.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.http.client.methods.HttpUriRequest
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 7 more
```

<p>Kindly check Structure of projects below</p>

```JWSINSTEADOFAPPLET
    |
     SRC
       |
         PACKAGE
           |
             .java file
    |
     JBoss 7.1 Runtime
    |
      Maven Dependencies
    |
      JRE System Library
    |
      Web Content
         |
           META_INF
         |
           WEB_INF
             |
              lib
                 |.jars
         HelloWorld.jnlp
         index.html
         MyHarper.jar

    |
      pom.xml
```

What need change Let me know ,Thanks in Advance

答:
From this answer ..

The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client..".

Try doing a direct fetch (by typing the path in your browser) to confirm the server will deny the request.

Title: How import dependent jars to JWS?

Body:
We are migrating from Applet to JWS. How to provide dependent jar to JWS? Kindly check my JNLP file.

<?xml version="1.0" encoding="utf-8"?>
<jnlp spec="1.0+" codebase="http://localhost:8080/JWSINSTEADOFAPPLET/" href="HelloWorld.jnlp">
<information>
         <title>HelloWorld</title>
         <vendor>IBM - JWS example of HelloWorld</vendor>`
    enter code here
         <description>HelloWorld - Example of JWS</description>
         <description kind="short">HelloWorld example</description>
         <offline-allowed/>
    </information>
    <security>
    <all-permissions/>
</security>
    <resources>
     <j2se version="1.3+"/>
     <jar href="Harper_Colin.jar" main="true"/>
     <jar href="lib/commons-codec-1.10.jar"/>
     <jar href="lib/commons-httpclient-3.1.jar"/>
     <jar href="lib/commons-logging-1.2.jar"/>
     <jar href="lib/commons-net-3.3.jar"/>
     <jar href="lib/httpclient-4.0.2-sources.jar"/>
     <jar href="lib/httpclient-4.5.3.jar"/>
     <jar href="lib/httpcore-4.4.6.jar"/>
     <jar href="lib/plugin.jar"/>

      </resources>
 <application-desc main-class="Harper_Upload_Final"/>
    </jnlp>

Even if  provided dependent jars under resources tab, I am getting error like below:

java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpUriRequest
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
    at java.lang.Class.getMethod0(Unknown Source)
    at java.lang.Class.getMethod(Unknown Source)
    at com.sun.javaws.Launcher.doLaunchApp(Unknown Source)
    at com.sun.javaws.Launcher.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: org.apache.http.client.methods.HttpUriRequest
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 7 more

Kindly check Structure of projects below

JWSINSTEADOFAPPLET
    |
     SRC
       |
         PACKAGE
           |
             .java file
    |
     JBoss 7.1 Runtime
    |
      Maven Dependencies
    |
      JRE System Library
    |
      Web Content
         |
           META_INF
         |
           WEB_INF
             |
              lib
                 |.jars
         HelloWorld.jnlp
         index.html
         MyHarper.jar

    |
      pom.xml

What need change Let me know ,Thanks in Advance


问:
Writing npm modules in TypeScript
I am working on my first npm module. I briefly worked with TypeScript before and a big problem was that for many modules there were no definition files available. So I thought it would be a good idea to write my module in TypeScript.

However, I can't find any information on the best way to do that. I found this related question "Can I write npm package in CoffeeScript?" where people suggest only publishing the JavaScript files. But in contrast to the CoffeeScript files, the TypeScript files might actually be useful if they are used within a TypeScript application.

Should I include TypeScript files when publishing an npm module, or should I only publish the JavaScript files and provide the generated .d.ts files to DefinitelyTyped?

答:
I mainly follow the suggestion by Varun Chatterji

But, I would like to show a complete example with unit testing and code coverage and publishing it into npm and importing them using javascript or typescript

This module is written using typescript 2.2 and it is important to configure the prepublish hook to compile the code using tsc before publish it to npm

https://github.com/sweetim/haversine-position

https://www.npmjs.com/package/haversine-position

Title: Writing npm modules in TypeScript


问:
Email Config Google Cloud Platform
Best regards

I have an instance configured in Google Cloud, where I installed cPanel to manage more easily my web project. Everything runs fine, but as much a problem to use email accounts.

I set all MX records in the Network section of the console Google, and have also done the same in cPanel. Then I created email accounts in cPanel, and I can access the accounts (I use RoundCube as an email client), but when sending an email, this is going, but does not arrive to destination, or conversely, sent from another account (such as a Gmail) email, and this is sent but not up to my new personal email account.

I realized that what happens is that Google does not allow use ports 25 and 587, so must perform other configuration.

Someone could help me to know how I can create and use email accounts, from a "normal" way, without using Google Apps (because it is paid) or services like Mailgun.

Thanks so much for any help.

答: You cannot use ports 25 and 587 since GCP block all outbound traffic from those ports, I suggest you use  port 2525 since that's the only smtp port that GCP does not block and most major vendors use. </p>

Title: Email Config Google Cloud Platform


问:
java.sql.Timestamp way of storing NanoSeconds
java.sql.Timestamp constructor go like this:

```<code>public Timestamp(long time) {
    super((time/1000)*1000);
    nanos = (int)((time%1000) * 1000000);
    if (nanos < 0) {
        nanos = 1000000000 + nanos;
        super.setTime(((time/1000)-1)*1000);
    }
}
</code>```

It basically accepts time in millisecond and then extracts the last 3 digits and makes it nanos. So for a millisecond value of 1304135631 421, I'm getting Timestamp.getnanos() as
421000000. This is plain calculation (adding 6 zeroes at the end)... does not seems to be optimum.

A better way could have been Timestamp constructor that accepts time in nanoseconds and then calculates the nanosecond value out of that.

If you run the below program, you'll see the difference between actual nanoseconds and the one returned by Timestamp way of calculating nanosecods.

```<code>long a = System.currentTimeMillis();
    for(;;){
        long b = System.currentTimeMillis();
        Timestamp tm = new Timestamp(System.currentTimeMillis());
        System.out.println(tm.getTime());
        System.out.println(tm.getNanos());
        System.out.println("This is actual nanos" + System.nanoTime()%1000000000);
        System.out.println("--------------------------");
        if(b-a >= 1)
            break;
    }
</code>```

So all the discussion about Timestamp that says it stores time up to nanoseconds , does not seems to be so correct.. Isn't?

答: Since the introduction of java.time.*, there is a new factory method in java.sql.Timestamp: Timestamp.from(Instant.now()) will do the job (with nanoseconds precision). There is also Timestamp.toInstant() to convert it the other way around.

Body:
java.sql.Timestamp constructor go like this:

public Timestamp(long time) {
    super((time/1000)*1000);
    nanos = (int)((time%1000) * 1000000);
    if (nanos < 0) {
        nanos = 1000000000 + nanos;
        super.setTime(((time/1000)-1)*1000);
    }
}

It basically accepts time in millisecond and then extracts the last 3 digits and makes it nanos. So for a millisecond value of 1304135631 421, I'm getting Timestamp.getnanos() as
421000000. This is plain calculation (adding 6 zeroes at the end)... does not seems to be optimum.

A better way could have been Timestamp constructor that accepts time in nanoseconds and then calculates the nanosecond value out of that.

If you run the below program, you'll see the difference between actual nanoseconds and the one returned by Timestamp way of calculating nanosecods.

long a = System.currentTimeMillis();
    for(;;){
        long b = System.currentTimeMillis();
        Timestamp tm = new Timestamp(System.currentTimeMillis());
        System.out.println(tm.getTime());
        System.out.println(tm.getNanos());
        System.out.println("This is actual nanos" + System.nanoTime()%1000000000);
        System.out.println("--------------------------");
        if(b-a >= 1)
            break;
    }

So all the discussion about Timestamp that says it stores time up to nanoseconds , does not seems to be so correct.. Isn't?


问:
How to hide div when click on anywhere on the display
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>
<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </code>```

答:
Try as below, this shows your div when you click button and hides when you click anywhere in page.

e.stopPropagation - Prevents the event from bubbling up the DOM tree,
  preventing any parent handlers from being notified of the event.

$(document).ready(function(){
 var pop = $("#PopupDiv");
  $(pop).hide();
  $("#Btn1").on("click",function(e){
    e.stopPropagation();
   $(pop).show();
  });
   $("p").on("click",function(e){
    e.stopPropagation();
  });
  $("html,body").on("click",function(e){
   e.stopPropagation();
    $(pop).hide();
  });
});

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
   <input type="button" id="Btn1" value="BtnClick" />
</div>
<div id="PopupDiv">
   <p>Hello Popup Grid</p>
</div></code>```

Body:
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

  <input type="button" id="Btn1" value="BtnClick" />

Hello Popup Grid

Body:
Try as below, this shows your div when you click button and hides when you click anywhere in page.

e.stopPropagation - Prevents the event from bubbling up the DOM tree,
  preventing any parent handlers from being notified of the event.

$(document).ready(function(){
 var pop = $("#PopupDiv");
  $(pop).hide();
  $("#Btn1").on("click",function(e){
    e.stopPropagation();
   $(pop).show();
  });
   $("p").on("click",function(e){
    e.stopPropagation();
  });
  $("html,body").on("click",function(e){
   e.stopPropagation();
    $(pop).hide();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
   <input type="button" id="Btn1" value="BtnClick" />
</div>
<div id="PopupDiv">
   <p>Hello Popup Grid</p>
</div>


问:
Hibernate second level cache with Spring
I'm using Spring + JPA + Hibernate. I'm trying to enable Hibernate's second level cache. In my Spring's applicationContext.xml I have:

```<code><prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>
</code>```

When I run I get the error:

```<code>Caused by: org.hibernate.HibernateException: Could not instantiate cache implementation
     at org.hibernate.cache.CacheFactory.createCache(CacheFactory.java:64)

Caused by: org.hibernate.cache.NoCachingEnabledException: Second-level cache is not enabled for usage [hibernate.cache.use_second_level_cache | hibernate.cache.use_query_cache]
     at org.hibernate.cache.NoCacheProvider.buildCache(NoCacheProvider.java:21)
</code>```

So it's complain I don't have second level cache enabled. I attempt to enable it by adding to my applicationContext.xml:

```<code><prop key="hibernate.cache.use_second_level_cache">true</prop>
</code>```

But still no joy. I also tried adding this to my ehcache.xml:

```<code><property name="hibernate.cache.use_second_level_cache">true</property>
</code>```

But it still doesn't work. Changing the provider_class to org.hibernate.cache.EhCacheProvider doesn't help either:

```<code><prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</code>```

My entity classes are annotated to use caching

```<code>@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)
</code>```

So, how do I enable second level cache?

Edit:  This is under the bean:

```<code><bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
</code>```

Resolved: Since I'm using LocalEntityManagerFactoryBean it gets its settings from META-INF/persistence.xml. My settings in applicationContext.xml weren't even being read.

答:
Try this:

```<code><prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.max_fetch_depth">4</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>
</code>```

And if you are using Maven add this to your POM file:

```<code><dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache-core</artifactId>
  <version>2.3.0</version>
</dependency>
</code>```

Or download the latest jar from http://ehcache.org/

OwnerDisplayName: Steve Kuo

Body:
I'm using Spring + JPA + Hibernate. I'm trying to enable Hibernate's second level cache. In my Spring's applicationContext.xml I have:

<prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">/ehcache.xml</prop>

When I run I get the error:

Caused by: org.hibernate.HibernateException: Could not instantiate cache implementation
     at org.hibernate.cache.CacheFactory.createCache(CacheFactory.java:64)

Caused by: org.hibernate.cache.NoCachingEnabledException: Second-level cache is not enabled for usage [hibernate.cache.use_second_level_cache | hibernate.cache.use_query_cache]
     at org.hibernate.cache.NoCacheProvider.buildCache(NoCacheProvider.java:21)

So it's complain I don't have second level cache enabled. I attempt to enable it by adding to my applicationContext.xml:

<prop key="hibernate.cache.use_second_level_cache">true</prop>

But still no joy. I also tried adding this to my ehcache.xml:

<property name="hibernate.cache.use_second_level_cache">true</property>

But it still doesn't work. Changing the provider_class to org.hibernate.cache.EhCacheProvider doesn't help either:

<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>

My entity classes are annotated to use caching

@Cache(usage=CacheConcurrencyStrategy.READ_ONLY)

So, how do I enable second level cache?

Edit:  This is under the bean:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">

Resolved: Since I'm using LocalEntityManagerFactoryBean it gets its settings from META-INF/persistence.xml. My settings in applicationContext.xml weren't even being read.

LastEditorDisplayName: Steve Kuo

Body:
Try this:

<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.max_fetch_depth">4</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</prop>

And if you are using Maven add this to your POM file:

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache-core</artifactId>
  <version>2.3.0</version>
</dependency>

Or download the latest jar from http://ehcache.org/

ContentLicense: CC BY-SA 2.5


问:
How to invoke pandas str.split() and not python's built in str.split()
I am trying to locate all the rows of a dataframe whose one attribute (say id_proof) value matches to the second part of another column (say adr_proof) that starts with a fixed word (say PARENT) and also the corresponding values should match which are part of the same dataframe.

For example, in the dataframe :

```<code>import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT   B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)
</code>```

I am trying to achieve :

```<code>node1    node2    relation
  1        7      parent-child
  2        8      parent-child
  3        9      parent-child
  4       12      parent-child
  5       10      parent-child
  6       11      parent-child
</code>```

Below is my code. I am aware that my code is incomplete. I am stuck with the split() function. I am new to python and pandas and am not sure how to invoke pandas' split() function rather than python's built-in str.split() function. I have gone through this question

```<code>import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

df_group_count = pd.DataFrame({'count' : main.groupby(['adr_proof']).size()}).reset_index()
adr_type = df_group_count['adr_proof']
adr_type_parent = adr_type.loc[adr_type.str.startswith('PARENT',na=False)]

df_j_ = pd.DataFrame()
for j in adr_type_parent:
    dfn_j = main.loc[(main['adr_proof'] == j)]
    adr_type_parent_type = j.split(' ',expand=True,n=1)
    res = main.loc[(main['id_proof'] == adr_type_parent_type[1]) & (main['id_value'] == dfn_j['adr_value'])]

res
</code>```

Please provide a way to achieve my goal. The output is another dataframe. Please excuse for bad code or any violations. A completely different approach is also appreciated. Thank You.

答:
Since your main question seems to be how to incorporate pandas split function:

You can isolate the rows containing the keyword 'PARENT' using this:

```<code>parent_main = main[main.adr_proof.str.split(' ').str[0] == 'PARENT']
</code>```

Now, you can easily extract the second value:

```<code>parent_main.adr_proof.str.split(' ').str[-1]
</code>```

Body:
I am trying to locate all the rows of a dataframe whose one attribute (say id_proof) value matches to the second part of another column (say adr_proof) that starts with a fixed word (say PARENT) and also the corresponding values should match which are part of the same dataframe.

For example, in the dataframe :

import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT   B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

I am trying to achieve :

node1    node2    relation
  1        7      parent-child
  2        8      parent-child
  3        9      parent-child
  4       12      parent-child
  5       10      parent-child
  6       11      parent-child

Below is my code. I am aware that my code is incomplete. I am stuck with the split() function. I am new to python and pandas and am not sure how to invoke pandas' split() function rather than python's built-in str.split() function. I have gone through this question

import pandas as pd

main = {'account_number' : [1,2,3,4,5,6,7,8,9,10,11,12],
    'id_proof' : ['A','B','B','A','C','C','X','Y','X','Y','Y','X'],
    'id_value' : [101,201,301,401,501,601,111,222,333,444,555,666],
    'adr_proof' : ['Z','E','E','G','G','I','PARENT A','PARENT B','PARENT B','PARENT C','PARENT C','PARENT A'],
    'adr_value' : [11,22,33,44,55,66,101,201,301,501,601,401]}
main = pd.DataFrame(main)

df_group_count = pd.DataFrame({'count' : main.groupby(['adr_proof']).size()}).reset_index()
adr_type = df_group_count['adr_proof']
adr_type_parent = adr_type.loc[adr_type.str.startswith('PARENT',na=False)]

df_j_ = pd.DataFrame()
for j in adr_type_parent:
    dfn_j = main.loc[(main['adr_proof'] == j)]
    adr_type_parent_type = j.split(' ',expand=True,n=1)
    res = main.loc[(main['id_proof'] == adr_type_parent_type[1]) & (main['id_value'] == dfn_j['adr_value'])]

res

Please provide a way to achieve my goal. The output is another dataframe. Please excuse for bad code or any violations. A completely different approach is also appreciated. Thank You.

Body:
Since your main question seems to be how to incorporate pandas split function:

You can isolate the rows containing the keyword 'PARENT' using this:

parent_main = main[main.adr_proof.str.split(' ').str[0] == 'PARENT']

Now, you can easily extract the second value:

parent_main.adr_proof.str.split(' ').str[-1]


问:
Swift2 : checking the timeinterval repeatedly in iOS
As I have three time intervals one is less than 15 mins, second one greater than or equal to 15 and third one is greater than or equal to
30.In my case am checking only once the conditions.But i want to check the conditions for every 1 minute.Because after the certain timeinterval all the button colors for me should change into appYellowColor() only.Any help is appreciable.Thanks in advance! Here is my code.</p>

```<code> if NetworkService.weAreOnline(true) && interval/60 < 15  {

       print("appYellowColor()")
       startButton.backgroundColor = UIColor.appYellowColor()

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 15  && interval/60 < 30 {

       print("grayColor()")
       startButton.backgroundColor = UIColor.grayColor()
       startButton.userInteractionEnabled = false

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 30 {

       print("redColor()")
       startButton.backgroundColor = UIColor.redColor()
       startButton.userInteractionEnabled = false

 }
</code>```

答:
I dont know swift but in objective c like this.If you call particular method continuesly with particular time intervals you can use NSTimer.

First thing your Secound time intervals greater than or equal to 15.interval/60 >= 15 if we are placing this it will not go to third one because it always true so we need keep like this

NetworkService.weAreOnline(true) && interval/60 >= 15 && interval/60 < 30 when it fails it goes to third condition

```<code>NSTimer *reachTimer;
//NSInteger secondsLeft;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //to stop the timer you can use secondsLeft
    //secondsLeft = 0;
    reachTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];

}

// This method is called every 300 secs

-(void)updateCounter:(NSTimer *)theTimer{

    // Build your login here

    //    //if you want to stop timer after 300 sec you can use below code
    //    secondsLeft = secondsLeft+5;
    //    if(secondsLeft>=300) // 60sec * 5min= 300
    //    {
    //        [reachTimer invalidate];// stop timer
    //    }

 }
</code>```

Body:
As I have three time intervals one is less than 15 mins, second one greater than or equal to 15 and third one is greater than or equal to
30.In my case am checking only once the conditions.But i want to check the conditions for every 1 minute.Because after the certain timeinterval all the button colors for me should change into appYellowColor() only.Any help is appreciable.Thanks in advance! Here is my code.

 if NetworkService.weAreOnline(true) && interval/60 < 15  {

       print("appYellowColor()")
       startButton.backgroundColor = UIColor.appYellowColor()

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 15  && interval/60 < 30 {

       print("grayColor()")
       startButton.backgroundColor = UIColor.grayColor()
       startButton.userInteractionEnabled = false

 }
 else if NetworkService.weAreOnline(true) && interval/60 >= 30 {

       print("redColor()")
       startButton.backgroundColor = UIColor.redColor()
       startButton.userInteractionEnabled = false

 }

Body:
I dont know swift but in objective c like this.If you call particular method continuesly with particular time intervals you can use NSTimer.

First thing your Secound time intervals greater than or equal to 15.interval/60 >= 15 if we are placing this it will not go to third one because it always true so we need keep like this

NetworkService.weAreOnline(true) && interval/60 >= 15 && interval/60 < 30 when it fails it goes to third condition

NSTimer *reachTimer;
//NSInteger secondsLeft;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    //to stop the timer you can use secondsLeft
    //secondsLeft = 0;
    reachTimer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(updateCounter:) userInfo:nil repeats:YES];

}

// This method is called every 300 secs

-(void)updateCounter:(NSTimer *)theTimer{

    // Build your login here

    //    //if you want to stop timer after 300 sec you can use below code
    //    secondsLeft = secondsLeft+5;
    //    if(secondsLeft>=300) // 60sec * 5min= 300
    //    {
    //        [reachTimer invalidate];// stop timer
    //    }

 }


问:
Spring Boot Application deployment on remote server
I have a Java Spring Boot Application, and I build it with Maven. With
spring-boot-maven-plugin,

I can create fat, executable jar file.

Then I copy it to the remote server and run. But sometimes,

I change only one line or event one word in my code and I had to do whole build/copy step again. I'm sure that I'm doing it wrong, but I couldn't find another way that more efficient (Like capistrano in Rails).

At this point, I'm planning to clone source code to server, push from local, pull from remote, build and run approach. What is the correct (or elegant) way of doing this deployment?

答:
I would say it depends where are you trying to do it.

The best and the most agile way to do it for a controlled environment is surely a CI-CD (Continuous Integration and Continuous Deployment) pipelines, which complies-builds-tests-deploys your code against every commit made to the source code BUT it may be too slow to use CI-CD for a development environment where you had like to have a shorter feedback cycle and faster feedback to see how the code is progressing.

However, if you are talking about development environment, I will hit another chord and ask you why to deploy to the external server AT ALL while developing. When you use Spring Boot, which helps you develop a self-contained application, you get the Tomcat Server embedded with it for free. That gives you the choice to run the code anywhere you develop and test to move forward.

A simple maven goal - mvn spring-boot:run can make the code run anywhere you had like.

There is another magical library available in Spring-Boot, known as Devtools, which is meant to support agile developers. The library once in the app classpath, performs hot-swapping of byte-code to auto reload of code into the running application (running locally with embedded Tomcat) as soon there is a saved change. This is one of the coolest gadget that a developer can have.

Use of Spring-Loaded (or JRebel for non spring-boot apps) libraries can also help a developer do hot-swapping of byte code to load changes in running application as soon saved.

I hope it helps.


问:
Multiple SonarQube analysis on one pull-request
We used to have a big project that had SonarQube analysis run on it for every pull-request on GitHub. Everything worked fine.

Then we did some refactoring, and split the code into separate projects. Since the code is related, the repo is still the same. But, instead of running just one build+analysis we run multiple ones per pull-request.

Everything else works fine, except that the SonarQube GitHub plugin writes the problems found in the first build, then removes them in the second build and so on. So I get an email about problems in the first build, but when I go and look at the PR in GitHub, it's all green and no messages anywhere.

Optimally I would like to specify to SonarQube GH plugin that these builds should be handled as separate in the PR, but I haven't found a way to do that yet.

答:
What you are trying to achieve is not possible with the SonarQube GitHub plugin. If you want PR analysis back, you have 2 ways:

Either you gather those projects under the same umbrella, making them modules of a top project

Or you extract them in different repositories

The best solution depends on how your "new" projects are coupled to each other. If they have the same lifecycle (~ the same versioning scheme), then it's best to gather them under a top project. If not (i.e. they can be released independently with different versions), then moving them to dedicated repositories would be the best approach.


问:
Javascript dynamic input fields on a dynamic inputfield
I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.

This new text box should get numbers from the User and add new text fields under the Element for options.

For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:

Option 1 _____________
Option 2 _____________
Option 3 _____________

// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var counter = 'Element';
    counter+= a;
    var prviElement=document.createElement('span');
    prviElement.textContent= counter + ':' +'  ';
    document.body.appendChild(prviElement);
    var pitanje= document.createElement('span');
    var unos='unos';
    unos += i;
    pitanje.id=unos;
    pitanje.textContent=question + ' ';
    document.body.appendChild(pitanje);
    var tip1 = document.createElement("input");
    var element='element';
    element += i;
    tip1.id=element;
    if (type1=='textbox') {
        tip1.type=type2
    } else {
        tip1.type=type1
    }
    document.body.appendChild(tip1);
    var linija1= document.createElement("br");
    document.body.appendChild(linija1);
    var linija2= document.createElement("br");
    document.body.appendChild(linija2);
    i++;
    a++;
}

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">
    <script src="basa.js"></script>
    <title>OnlineForms</title>
    </head>
<body>
    <!--Ovaj kod je za Main Page-->
    <Main class="kocka">
        <div align="left">
            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>

            <button class="dropbtn" id="getAllButton">Forms</button>
        </div>
        <br>
        <div align="left">
            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>
            <br>
            <br>
        </div>
    </Main>
    <!--Ovaj kod je za Elemente-->
    <div id="element" class="hide">
            <h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>
            </h1>
        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>
        <br>
        <br>
        <button id="addButton" class='dropbtn'>Save</button>
        </div>
    <br>
    <br>
<div id="status"></div>
    <br>
<div id="status2"></div>
</body>
</html></code>```

答:
Read about the Conditional (Ternary) Operator

then simplify your js:

```<code>option ? option1 : option2
</code>```

as for the display, I would use:

```<code>if (option === 'option1'){
  $('option2).hide() // or show
}
</code>```

a little jquery in there, and so forth.

Body:
I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.

This new text box should get numbers from the User and add new text fields under the Element for options.

For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:

Option 1 _____________
Option 2 _____________
Option 3 _____________

// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
    var type1 = document.getElementById('type1').value;
    var type2 = document.getElementById('type2').value;
    var question = document.getElementById('question').value;
    var counter = 'Element';
    counter+= a;
    var prviElement=document.createElement('span');
    prviElement.textContent= counter + ':' +'  ';
    document.body.appendChild(prviElement);
    var pitanje= document.createElement('span');
    var unos='unos';
    unos += i;
    pitanje.id=unos;
    pitanje.textContent=question + ' ';
    document.body.appendChild(pitanje);
    var tip1 = document.createElement("input");
    var element='element';
    element += i;
    tip1.id=element;
    if (type1=='textbox') {
        tip1.type=type2
    } else {
        tip1.type=type1
    }
    document.body.appendChild(tip1);
    var linija1= document.createElement("br");
    document.body.appendChild(linija1);
    var linija2= document.createElement("br");
    document.body.appendChild(linija2);
    i++;
    a++;
}

function AddTextBox(elm) {
    var v = elm.value;
    var iCounter = elm.id.replace('type1', '');

    if (v == 'radio') {
        var textbox = document.createElement('input');
        textbox.type = 'text';
        textbox.id = 'txtSecond' + iCounter;
        elm.parentNode.insertBefore(textbox, elm.nextSibling);
    } else {
        //Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
        var rmv = document.getElementById('txtSecond' + iCounter);
        if (rmv != undefined) {
            rmv.remove();
        }
    }
}

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="pepo.css">
    <meta charset="UTF-8">

    <title>OnlineForms</title>

            <input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>

            <button class="dropbtn" id="getAllButton">Forms</button>

            <input type="number" id="key" class="dropbtn"  Placeholder="Type the key value"/>
            <button class="dropbtn" id="getButton"> Search </button>

Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
            <select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="textbox">textbox</option>
                <option value="checkbox">checkbox</option>
                <option value="radio">radio button</option>
                </select>
            <select title="ddmenu" class="dropbtn" id="type2">
                <option selected disabled hidden value="Please select">Please select</option>
                <option value="none">none</option>
                <option value="mandatory">mandatory</option>
                <option value="number">numeric</option>
            </select>

        <input type="button"  id="adddugme" class="dropbtn2" value="Add"  onclick="mojaFunkcija()"/>

        <button id="addButton" class='dropbtn'>Save</button>

Body:
Read about the Conditional (Ternary) Operator

then simplify your js:

option ? option1 : option2

as for the display, I would use:

if (option === 'option1'){
  $('option2).hide() // or show
}

a little jquery in there, and so forth.


问:
How to resolve ambiguous column names when retrieving results?
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

```<code>SELECT * FROM news JOIN users ON news.user = user.id
</code>```

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

答:
You can do something like

```<code>SELECT news.id as news_id, user.id as user_id ....
</code>```

And then $row['news_id'] will be the news id and $row['user_id'] will be the user id

OwnerDisplayName: Dan

Body:
I have two tables in my database:

NEWS table with columns:

id - the news id

user - the user id of the author)

USERS table with columns:

id - the user id

I want to execute this SQL:

SELECT * FROM news JOIN users ON news.user = user.id

When I get the results in PHP I would like to get associative array and get column names by $row['column-name']. How do I get the news ID and the user ID, having the same column name?

LastEditorDisplayName: Dan

Body:
You can do something like

SELECT news.id as news_id, user.id as user_id ....

And then $row['news_id'] will be the news id and $row['user_id'] will be the user id

OwnerDisplayName: Paolo Bergantino


问:
RemoteObjecting to BlazeDS in Flex
I have a blazeds amf url, which is https://..../afm/MessageBrok. Actually im not sure if it's what is referred to as the amf gateway or what. But basically, how do I do a remoteobject call to a blazeds location, for a service/destination and then use it like a web service, without having to set an xml file or anything on the flex side. The BlazeDS side is working fine, but basically, I need to know the code in the mxml file i need to use to get to that...</p>

答:
a) Create your remote object (you can do it from mxml or as):

```<code><mx:RemoteObject id="remoteObject" destination="campaignRemoteServices">
    <mx:method name="method1" result="createResult1(event)" fault="createFault1(event)"/>
    <mx:method name="method2" result="createResult2(event)" fault="createFault2(event)"/>
    <mx:.......
</mx:RemoteObject>
</code>```

Before doing that you need to know the destination name and the exposed methods.

b) Configure the channels for your remote object:

```<code>var channelSet:ChannelSet = new ChannelSet();
var channel:AMFChannel = new AMFChannel("amf", "blazeds amf endpoint , for example http://localhost:8080/myapp/messagebroker/amf");
channelSet.addChannel(channel);
remoteObject.channelSet = channelSet;
</code>```

c)Invoke the methods:

```<code>remoteObject.method1("test");
</code>```

Title: RemoteObjecting to BlazeDS in Flex

Body:
a) Create your remote object (you can do it from mxml or as):

<mx:RemoteObject id="remoteObject" destination="campaignRemoteServices">
    <mx:method name="method1" result="createResult1(event)" fault="createFault1(event)"/>
    <mx:method name="method2" result="createResult2(event)" fault="createFault2(event)"/>
    <mx:.......
</mx:RemoteObject>

Before doing that you need to know the destination name and the exposed methods.

b) Configure the channels for your remote object:

var channelSet:ChannelSet = new ChannelSet();
var channel:AMFChannel = new AMFChannel("amf", "blazeds amf endpoint , for example http://localhost:8080/myapp/messagebroker/amf");
channelSet.addChannel(channel);
remoteObject.channelSet = channelSet;

c)Invoke the methods:

remoteObject.method1("test");


问:
includes() not working in IE
I am using the following code. It works perfectly in browsers such as Chrome, Firefox or Edge. However when I check in IE11 it does not work and breaks all the functionality.

```<code>var href = jQuery(this).attr('href');
if (href.includes('#')) {
  // action
}
</code>```

I think includes() does not work in IE11. Is there a solution for this?

答:
Firstly you can check. Because IE does not support includes: MDN Reference

You can use like this. Yes, I know this is VanillaJS way. If you work cross browser use this way to avoid errors.:

var btn = document.querySelector('button')
var link = document.querySelector('a')
var isIE = window.navigator.userAgent.indexOf('Triden') > -1

btn.addEventListener("click", function() {

  var isHash = (!isIE) ? link.href.includes('#') : link.href.indexOf('#') > -1
  alert(isHash)
}, false)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button>Control hash</button>
<hr />

Users</code>```

Title: includes() not working in IE

Body:
I am using the following code. It works perfectly in browsers such as Chrome, Firefox or Edge. However when I check in IE11 it does not work and breaks all the functionality.

var href = jQuery(this).attr('href');
if (href.includes('#')) {
  // action
}

I think includes() does not work in IE11. Is there a solution for this?

Body:
Firstly you can check. Because IE does not support includes: MDN Reference

You can use like this. Yes, I know this is VanillaJS way. If you work cross browser use this way to avoid errors.:

var btn = document.querySelector('button')
var link = document.querySelector('a')
var isIE = window.navigator.userAgent.indexOf('Triden') > -1

btn.addEventListener("click", function() {

  var isHash = (!isIE) ? link.href.includes('#') : link.href.indexOf('#') > -1
  alert(isHash)
}, false)

<button>Control hash</button>
<hr />

<a href="http://somesite.com/#/GetUsers">Users</a>