问:
FullCalendar.io - all day event update
Trying to figure out exactly how I can through my code behind convert an appointment from time ranged to all day using JQuery FullCalendar. What I get when making the appointment dragged into allday slot is an error that the end time is null. Has anyone had success getting this to work? I am using EWS to update the Exchange calendar on the server. That part works well, I just need a little clarification on how to change time range to all day. Thanks! </p>

```<code><%@ Page Title="Group Calendar" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Calendar.aspx.cs" Inherits="WebUI.Calendar" %>

<asp:Content ID="HeaderContent" ContentPlaceHolderID="HeadContent" runat="server">
<link type="text/css" href='<% = Page.ResolveUrl("~/Scripts/fullcalendar/fullcalendar.min.css")%>' rel='stylesheet' />
<link type="text/css" href='<% = Page.ResolveUrl("~/Scripts/fullcalendar/fullcalendar.print.min.css")%>' rel='stylesheet' media='print' />
<script type="text/javascript" src='<% = Page.ResolveUrl("~/Scripts/fullcalendar/moment.min.js")%>'></script>
<script type="text/javascript" src='<% = Page.ResolveUrl("~/Scripts/fullcalendar/jquery.min.js")%>'></script>
<script type="text/javascript" src='<% = Page.ResolveUrl("~/Scripts/fullcalendar/jquery-ui.min.js")%>'></script>
<script type="text/javascript" src='<% = Page.ResolveUrl("~/Scripts/fullcalendar/fullcalendar.min.js")%>'></script>
<script type="text/javascript" src='<% = Page.ResolveUrl("~/Scripts/fullcalendar/theme-chooser.min.js")%>'></script>

<script type="text/javascript">
    $(document).ready(function () {
        initThemeChooser({
            init: function (themeSystem) {
                $('#calendar').fullCalendar({
                    themeSystem: themeSystem,
                    header: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'month,agendaWeek,agendaDay,listMonth'
                    },
                    selectable: true,
                    selectHelper: true,
                    weekNumbers: true,
                    navLinks: true,
                    editable: true,
                    eventLimit: true,
                    events:  <% =JsonEvent %>,
                    eventDrop: function (event, delta, revertFunc) {
                        if (!confirm("Are you sure about this change?"))     {
                            revertFunc();
                        } else {
                            UpdateEvent(event);
                            $(this).fullCalendar( 'refetchEvents' );
                        }
                    },
                    eventResize: function(event, delta, revertFunc) {
                        alert(event.title + " changed end is now " + event.end.format());
                        if (!confirm("is this okay?")) {
                            revertFunc();
                        }
                        else
                        {
                            UpdateEvent(event);
                            $(this).fullCalendar( 'refetchEvents' );
                        }
                    },
                    eventClick: function(calEvent, jsEvent, view) {

                        alert('Event: ' + calEvent.title + '\nDate: ' + moment(calEvent.Start).format("MM-DD-YYYY") + '\nStart: ' + moment(calEvent.start).format("hh:mm:ss A") + '\nEnd: ' + moment(calEvent.end).format("hh:mm:ss A"));
                        $(this).fullCalendar( 'refetchEvents' );
                        // change the border color just for fun
                        $(this).css('border-color', 'red');

                    }
                });

                function UpdateEvent(event)
                {
                    var data = {};
                    data.id = event.id;
                    data.starts = event.start;
                    data.ends = event.end;
                    data.subject = event.title;

                    $.ajax({
                        url: 'Calendar.aspx/UpdateEvent',
                        method: 'POST',
                        dataType: 'JSON',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify(data),
                        success: function (response, type, xhr) {
                            var retVal = JSON.stringify(response);
                        },
                        error: function (xhr) {
                            window.alert('error: ' + xhr.statusText);
                        }

                    });

                }
            },
            change: function (themeSystem) {
                $('#calendar').fullCalendar('option', 'themeSystem', themeSystem);
            }

        });
    });
</script>

<style type="text/css">
    body {
        margin: 0;
        padding: 0;
        font-size: 14px;
    }

    #top,
    #calendar.fc-unthemed {
        font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
    }

    #top {
        background: #eee;
        border-bottom: 1px solid #ddd;
        padding: 0 10px;
        line-height: 40px;
        font-size: 12px;
        color: #000;
    }

        #top .selector {
            display: inline-block;
            margin-right: 10px;
        }

        #top select {
            font: inherit; /* mock what Boostrap does, don't compete  */
        }

    .left {
        float: left;
    }

    .right {
        float: right;
    }

    .clear {
        clear: both;
    }

    #calendar {
        max-width: 900px;
        margin: 40px auto;
        padding: 0 10px;
    }

    body {
        margin: 40px 10px;
        padding: 0;
        font-family: "Lucida Grande", Helvetica, Arial, Verdana, sans-serif;
        font-size: 14px;
    }

    .fc th {
        padding: 10px 0px;
        vertical-align: middle;
        background: #F2F2F2;
    }

    .fc-day-grid-event > .fc-content {
        padding: 4px;
    }

    #calendar {
        max-width: 900px;
        margin: 0 auto;
    }

    .error {
        color: #ac2925;
        margin-bottom: 15px;
    }

    .event-tooltip {
        width: 150px;
        background: rgba(0, 0, 0, 0.85);
        color: #FFF;
        padding: 10px;
        position: absolute;
        -webkit-border-radius: 4px;
        -moz-border-radius: 4px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 11px;
    }
</style>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id='top'>
    <div class='left'>
        <div id='theme-system-selector' class='selector'>
            Theme System:

            <select>
                <option value='bootstrap3' selected>Bootstrap 3</option>
                <option value='jquery-ui'>jQuery UI</option>
                <option value='standard'>unthemed</option>
            </select>
        </div>

        <div data-theme-system="bootstrap3" class='selector' style='display: none'>
            Theme Name:

            <select>
                <option value='' selected>Default</option>
                <option value='cosmo'>Cosmo</option>
                <option value='cyborg'>Cyborg</option>
                <option value='darkly'>Darkly</option>
                <option value='flatly'>Flatly</option>
                <option value='journal'>Journal</option>
                <option value='lumen'>Lumen</option>
                <option value='paper'>Paper</option>
                <option value='readable'>Readable</option>
                <option value='sandstone'>Sandstone</option>
                <option value='simplex'>Simplex</option>
                <option value='slate'>Slate</option>
                <option value='solar'>Solar</option>
                <option value='spacelab'>Spacelab</option>
                <option value='superhero'>Superhero</option>
                <option value='united'>United</option>
                <option value='yeti'>Yeti</option>
            </select>
        </div>

        <div data-theme-system="jquery-ui" class='selector' style='display: none'>
            Theme Name:

            <select>
                <option value='black-tie'>Black Tie</option>
                <option value='blitzer'>Blitzer</option>
                <option value='cupertino' selected>Cupertino</option>
                <option value='dark-hive'>Dark Hive</option>
                <option value='dot-luv'>Dot Luv</option>
                <option value='eggplant'>Eggplant</option>
                <option value='excite-bike'>Excite Bike</option>
                <option value='flick'>Flick</option>
                <option value='hot-sneaks'>Hot Sneaks</option>
                <option value='humanity'>Humanity</option>
                <option value='le-frog'>Le Frog</option>
                <option value='mint-choc'>Mint Choc</option>
                <option value='overcast'>Overcast</option>
                <option value='pepper-grinder'>Pepper Grinder</option>
                <option value='redmond'>Redmond</option>
                <option value='smoothness'>Smoothness</option>
                <option value='south-street'>South Street</option>
                <option value='start'>Start</option>
                <option value='sunny'>Sunny</option>
                <option value='swanky-purse'>Swanky Purse</option>
                <option value='trontastic'>Trontastic</option>
                <option value='ui-darkness'>UI Darkness</option>
                <option value='ui-lightness'>UI Lightness</option>
                <option value='vader'>Vader</option>
            </select>
        </div>

        <span id='loading' style='display: none'>loading theme...</span>
    </div>

    <div class='right'>
    </div>

    <div class='clear'></div>
</div>
<br />
<div class="container" style="z-index: 10; width: auto;">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div id='calendar'></div>
        </div>
    </div>
</div>

<div class="modal fade" style="z-index: 10">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title"></h4>
            </div>
            <div class="modal-body">
                <div class="error"></div>
                <form class="form-horizontal" id="crud-form">
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="title">Title</label>
                        <div class="col-md-4">
                            <input id="title" name="title" type="text" class="form-control input-md" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="time">Time</label>
                        <div class="col-md-4 input-append bootstrap-timepicker">
                            <input id="time" name="time" type="text" class="form-control input-md" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="description">Description</label>
                        <div class="col-md-4">
                            <textarea class="form-control" id="description" name="description"></textarea>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="color">Color</label>
                        <div class="col-md-4">
                            <input id="color" name="color" type="text" class="form-control input-md" readonly="readonly" />
                            <span class="help-block">Click to pick a color</span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>
</asp:Content>
</code>```

答:
I suspect that fullCalendar drops the end time when you make it all-day for 1 single day, because it's not needed (by fullCalendar). Exchange clearly doesn't understand that. So perhaps before you send the event via UpdateEvent you need to check whether the end time is null, and if so then set it to be the same as the start date.

You may need to adjust this slightly, either if event.end is not literally null (perhaps it's some other kind of "empty" or invalid value, you can check), or if your Exchange server needs a slightly different value for the end - perhaps the day after, or 23:59 that day, or whatever it needs. You may want to consider checking the allDay flag as well and using/sending that - I'm pretty sure Exchange has the concept of all-day, but I don't know if it actually has a field for it, or just that to default the times (e.g. when you tick the "All Day" box when creating an event via Outlook).

Anyway here's the general idea:

```<code>function UpdateEvent(event)
{
  var data = {};
  data.id = event.id;
  data.starts = event.start;
  data.ends = (event.end != null ? event.end : event.start);
  data.subject = event.title;

  //...etc
</code>```

Title: FullCalendar.io - all day event update

Body:
Trying to figure out exactly how I can through my code behind convert an appointment from time ranged to all day using JQuery FullCalendar. What I get when making the appointment dragged into allday slot is an error that the end time is null. Has anyone had success getting this to work? I am using EWS to update the Exchange calendar on the server. That part works well, I just need a little clarification on how to change time range to all day. Thanks!

<%@ Page Title="Group Calendar" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Calendar.aspx.cs" Inherits="WebUI.Calendar" %>

<asp:Content ID="HeaderContent" ContentPlaceHolderID="HeadContent" runat="server">
<link type="text/css" href='<% = Page.ResolveUrl("~/Scripts/fullcalendar/fullcalendar.min.css")%>' rel='stylesheet' />
<link type="text/css" href='<% = Page.ResolveUrl("~/Scripts/fullcalendar/fullcalendar.print.min.css")%>' rel='stylesheet' media='print' />

</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

            Theme System:

            <select>
                <option value='bootstrap3' selected>Bootstrap 3</option>
                <option value='jquery-ui'>jQuery UI</option>
                <option value='standard'>unthemed</option>
            </select>

            Theme Name:

            <select>
                <option value='' selected>Default</option>
                <option value='cosmo'>Cosmo</option>
                <option value='cyborg'>Cyborg</option>
                <option value='darkly'>Darkly</option>
                <option value='flatly'>Flatly</option>
                <option value='journal'>Journal</option>
                <option value='lumen'>Lumen</option>
                <option value='paper'>Paper</option>
                <option value='readable'>Readable</option>
                <option value='sandstone'>Sandstone</option>
                <option value='simplex'>Simplex</option>
                <option value='slate'>Slate</option>
                <option value='solar'>Solar</option>
                <option value='spacelab'>Spacelab</option>
                <option value='superhero'>Superhero</option>
                <option value='united'>United</option>
                <option value='yeti'>Yeti</option>
            </select>

            Theme Name:

            <select>
                <option value='black-tie'>Black Tie</option>
                <option value='blitzer'>Blitzer</option>
                <option value='cupertino' selected>Cupertino</option>
                <option value='dark-hive'>Dark Hive</option>
                <option value='dot-luv'>Dot Luv</option>
                <option value='eggplant'>Eggplant</option>
                <option value='excite-bike'>Excite Bike</option>
                <option value='flick'>Flick</option>
                <option value='hot-sneaks'>Hot Sneaks</option>
                <option value='humanity'>Humanity</option>
                <option value='le-frog'>Le Frog</option>
                <option value='mint-choc'>Mint Choc</option>
                <option value='overcast'>Overcast</option>
                <option value='pepper-grinder'>Pepper Grinder</option>
                <option value='redmond'>Redmond</option>
                <option value='smoothness'>Smoothness</option>
                <option value='south-street'>South Street</option>
                <option value='start'>Start</option>
                <option value='sunny'>Sunny</option>
                <option value='swanky-purse'>Swanky Purse</option>
                <option value='trontastic'>Trontastic</option>
                <option value='ui-darkness'>UI Darkness</option>
                <option value='ui-lightness'>UI Lightness</option>
                <option value='vader'>Vader</option>
            </select>

        loading theme...

                <button type="button" class="close" data-dismiss="modal">×Close</button>

                <form class="form-horizontal" id="crud-form">

                        Title

                            <input id="title" name="title" type="text" class="form-control input-md" />

                        Time

                            <input id="time" name="time" type="text" class="form-control input-md" />

                        Description

                            <textarea class="form-control" id="description" name="description"></textarea>

                        Color

                            <input id="color" name="color" type="text" class="form-control input-md" readonly="readonly" />
                            Click to pick a color

                </form>

                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

</asp:Content>

Body:
I suspect that fullCalendar drops the end time when you make it all-day for 1 single day, because it's not needed (by fullCalendar). Exchange clearly doesn't understand that. So perhaps before you send the event via UpdateEvent you need to check whether the end time is null, and if so then set it to be the same as the start date.

You may need to adjust this slightly, either if event.end is not literally null (perhaps it's some other kind of "empty" or invalid value, you can check), or if your Exchange server needs a slightly different value for the end - perhaps the day after, or 23:59 that day, or whatever it needs. You may want to consider checking the allDay flag as well and using/sending that - I'm pretty sure Exchange has the concept of all-day, but I don't know if it actually has a field for it, or just that to default the times (e.g. when you tick the "All Day" box when creating an event via Outlook).

Anyway here's the general idea:

function UpdateEvent(event)
{
  var data = {};
  data.id = event.id;
  data.starts = event.start;
  data.ends = (event.end != null ? event.end : event.start);
  data.subject = event.title;

  //...etc


来源: stackexchange

问:
Fetching data with respect to array with in array Json
I need to fetch two arrays from a json response
Here is my response.

```<code>{
"data": [
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            }
        ],
        "id": "14",
        "cat_id": "x",
        "category": "Casual shirts"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            }
        ],
        "id": "15",
        "cat_id": "x",
        "category": "Jackets"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            },
            {
                "id": "833",
                "cat_id": "154",
                "sub_category": "Pepe jeans"
            },
            {
                "id": "834",
                "cat_id": "154",
                "sub_category": "John players"
            }
        ],
        "id": "154",
        "cat_id": "x",
        "category": "Jeans"
    }
],
"status": 100
}
</code>```

While trying to fetch data, and put it in to a list adapter in which i want to display categories in one text box and subcategories in other with comma separation.
Like this:

```<code>Category : Jeans

Sub Category :John players,Pepe jeans,Pan America,Roadster,wildcraft
</code>```

I tried implementing this by creating model class for both category and sub category. Getting category correctly, but getting all subcategories.

答:
Here is code for same:

```<code> try{
        JSONObject jsonObject = new JSONObject(jsonString);

        ArrayList<String> categoryList = new ArrayList<>();

        HashMap<String,ArrayList<String>> allCategory = new HashMap<>();
        JSONArray dataArray  = jsonObject.getJSONArray("data");
        for(int i=0;i<dataArray.length();i++)
        {
            JSONObject internalObject = dataArray.getJSONObject(i);

            categoryList.add(internalObject.getString("category"));

            JSONArray jsonArray = internalObject.getJSONArray("sub_cat");

            ArrayList<String> subCategoryList = new ArrayList<>();
            for(int j=0;j<jsonArray.length();j++)
            {
                subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
            }

            allCategory.put(categoryList.get(i),subCategoryList);
        }

        Log.d("Check",hashMap+" ");
    }
    catch (Exception exe)
    {
        exe.printStackTrace();
    }
</code>```

You will get categoryList for all category and allCategory containing Hashmap. For mapping of category with its list of sub_categories.

Edited

Here is MainActivity.java class from where list is called:

```<code>public class MainActivity extends Activity {

ExpandableListAdapter listAdapter;
ExpandableListView expListView;

HashMap<String,ArrayList<String>> allCategory;
private ArrayList<String> categoryList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String[] mStrings = new String[20];

    allCategory= new HashMap<>();

    // get the listview
    expListView = (ExpandableListView) findViewById(R.id.lvExp);

    String jsonString = "{\n" +
            "\"data\": [\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"14\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Casual shirts\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"835\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"Roadster\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"836\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"wildcraft\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"15\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Jackets\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"835\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"Roadster\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"836\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"wildcraft\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"833\",\n" +
            "                \"cat_id\": \"154\",\n" +
            "                \"sub_category\": \"Pepe jeans\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"834\",\n" +
            "                \"cat_id\": \"154\",\n" +
            "                \"sub_category\": \"John players\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"154\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Jeans\"\n" +
            "    }\n" +
            "],\n" +
            "\"status\": 100\n" +
            "}";

    // preparing list data
    prepareListData(jsonString);

    listAdapter = new ExpandableListAdapter(this, categoryList, allCategory);

    // setting list adapter
    expListView.setAdapter(listAdapter);

}

/*
 * Preparing the list data
 */
private void prepareListData(String jsonString) {
    try{
        JSONObject jsonObject = new JSONObject(jsonString);

       categoryList = new ArrayList<>();

        JSONArray dataArray  = jsonObject.getJSONArray("data");
        for(int i=0;i<dataArray.length();i++)
        {
            JSONObject internalObject = dataArray.getJSONObject(i);

            categoryList.add(internalObject.getString("category"));

            JSONArray jsonArray = internalObject.getJSONArray("sub_cat");

            ArrayList<String> subCategoryList = new ArrayList<>();
            for(int j=0;j<jsonArray.length();j++)
            {
                subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
            }

            allCategory.put(categoryList.get(i),subCategoryList);
        }

        Log.d("Check",allCategory+" ");
    }
    catch (Exception exe)
    {
        exe.printStackTrace();
    }

}
}
</code>```

Here is Expandlist Adapter:

```<code>public class ExpandableListAdapter extends BaseExpandableListAdapter {

HashMap<String,ArrayList<String>> listDataEditText;

int expandedGroup=0;

private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, ArrayList<String>> _listDataChild;

public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, ArrayList<String>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;

    listDataEditText  = new HashMap<>();

    for(int j=0;j<listDataHeader.size();j++) {
        ArrayList<String> preInsertion = new ArrayList<>();
        for (int i =0;i<this._listDataChild.get(_listDataHeader.get(j)).size();i++)
        {
                preInsertion.add("");
        }

        listDataEditText.put(listDataHeader.get(j),preInsertion);

    }

}

@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public View getChildView(final int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    final String childText = (String) getChild(groupPosition, childPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }
    TextView txtListChild = convertView.findViewById(R.id.lblListItem);

    txtListChild.setText(childText);
    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this._listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(final int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);

    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

 }
</code>```

and here is list items:

for GroupView "list_group":

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="81dp">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/lblListHeader"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="48dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="33dp" />

</RelativeLayout>
</android.support.constraint.ConstraintLayout>
</code>```

for Child View "list_item":

```<code> <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/linearLayout4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.194"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.137">

    <TextView
        android:id="@+id/lblListItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="17dp" />

</LinearLayout>

</android.support.constraint.ConstraintLayout>
</code>```

Try it and let me know if need more.

Edited latest

Use this SimpleAdapter for showing all sub_categories list:

```<code>public class SimpleAdapter extends BaseAdapter {

ArrayList<String> stringArrayList;
Context context;

public SimpleAdapter(Context context,ArrayList<String> stringArrayList)
{
    this.context = context;
    this.stringArrayList = stringArrayList;
}

@Override
public int getCount() {
    return stringArrayList.size();
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    if (view == null) {
        LayoutInflater infalInflater = (LayoutInflater) this.context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = infalInflater.inflate(R.layout.list_item, null);
    }
    TextView txtListChild = view.findViewById(R.id.lblListItem);

    txtListChild.setText(stringArrayList.get(i));

    return view;
}
}
</code>```

and make main layout as:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
>

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</ListView>

</LinearLayout>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to fetch two arrays from a json response
Here is my response.

{
"data": [
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            }
        ],
        "id": "14",
        "cat_id": "x",
        "category": "Casual shirts"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            }
        ],
        "id": "15",
        "cat_id": "x",
        "category": "Jackets"
    },
    {
        "sub_cat": [
            {
                "id": "770",
                "cat_id": "14",
                "sub_category": "Pan America"
            },
            {
                "id": "771",
                "cat_id": "14",
                "sub_category": "John Players"
            },
            {
                "id": "835",
                "cat_id": "15",
                "sub_category": "Roadster"
            },
            {
                "id": "836",
                "cat_id": "15",
                "sub_category": "wildcraft"
            },
            {
                "id": "833",
                "cat_id": "154",
                "sub_category": "Pepe jeans"
            },
            {
                "id": "834",
                "cat_id": "154",
                "sub_category": "John players"
            }
        ],
        "id": "154",
        "cat_id": "x",
        "category": "Jeans"
    }
],
"status": 100
}

While trying to fetch data, and put it in to a list adapter in which i want to display categories in one text box and subcategories in other with comma separation.
Like this:

Category : Jeans

Sub Category :John players,Pepe jeans,Pan America,Roadster,wildcraft

I tried implementing this by creating model class for both category and sub category. Getting category correctly, but getting all subcategories.

Body:
Here is code for same:

 try{
        JSONObject jsonObject = new JSONObject(jsonString);

        ArrayList<String> categoryList = new ArrayList<>();

        HashMap<String,ArrayList<String>> allCategory = new HashMap<>();
        JSONArray dataArray  = jsonObject.getJSONArray("data");
        for(int i=0;i<dataArray.length();i++)
        {
            JSONObject internalObject = dataArray.getJSONObject(i);

            categoryList.add(internalObject.getString("category"));

            JSONArray jsonArray = internalObject.getJSONArray("sub_cat");

            ArrayList<String> subCategoryList = new ArrayList<>();
            for(int j=0;j<jsonArray.length();j++)
            {
                subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
            }

            allCategory.put(categoryList.get(i),subCategoryList);
        }

        Log.d("Check",hashMap+" ");
    }
    catch (Exception exe)
    {
        exe.printStackTrace();
    }

You will get categoryList for all category and allCategory containing Hashmap. For mapping of category with its list of sub_categories.

Edited

Here is MainActivity.java class from where list is called:

public class MainActivity extends Activity {

ExpandableListAdapter listAdapter;
ExpandableListView expListView;

HashMap<String,ArrayList<String>> allCategory;
private ArrayList<String> categoryList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    String[] mStrings = new String[20];

    allCategory= new HashMap<>();

    // get the listview
    expListView = (ExpandableListView) findViewById(R.id.lvExp);

    String jsonString = "{\n" +
            "\"data\": [\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"14\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Casual shirts\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"835\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"Roadster\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"836\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"wildcraft\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"15\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Jackets\"\n" +
            "    },\n" +
            "    {\n" +
            "        \"sub_cat\": [\n" +
            "            {\n" +
            "                \"id\": \"770\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"Pan America\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"771\",\n" +
            "                \"cat_id\": \"14\",\n" +
            "                \"sub_category\": \"John Players\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"835\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"Roadster\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"836\",\n" +
            "                \"cat_id\": \"15\",\n" +
            "                \"sub_category\": \"wildcraft\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"833\",\n" +
            "                \"cat_id\": \"154\",\n" +
            "                \"sub_category\": \"Pepe jeans\"\n" +
            "            },\n" +
            "            {\n" +
            "                \"id\": \"834\",\n" +
            "                \"cat_id\": \"154\",\n" +
            "                \"sub_category\": \"John players\"\n" +
            "            }\n" +
            "        ],\n" +
            "        \"id\": \"154\",\n" +
            "        \"cat_id\": \"x\",\n" +
            "        \"category\": \"Jeans\"\n" +
            "    }\n" +
            "],\n" +
            "\"status\": 100\n" +
            "}";

    // preparing list data
    prepareListData(jsonString);

    listAdapter = new ExpandableListAdapter(this, categoryList, allCategory);

    // setting list adapter
    expListView.setAdapter(listAdapter);

}

/*
 * Preparing the list data
 */
private void prepareListData(String jsonString) {
    try{
        JSONObject jsonObject = new JSONObject(jsonString);

       categoryList = new ArrayList<>();

        JSONArray dataArray  = jsonObject.getJSONArray("data");
        for(int i=0;i<dataArray.length();i++)
        {
            JSONObject internalObject = dataArray.getJSONObject(i);

            categoryList.add(internalObject.getString("category"));

            JSONArray jsonArray = internalObject.getJSONArray("sub_cat");

            ArrayList<String> subCategoryList = new ArrayList<>();
            for(int j=0;j<jsonArray.length();j++)
            {
                subCategoryList.add(jsonArray.getJSONObject(j).getString("sub_category"));
            }

            allCategory.put(categoryList.get(i),subCategoryList);
        }

        Log.d("Check",allCategory+" ");
    }
    catch (Exception exe)
    {
        exe.printStackTrace();
    }

}
}

Here is Expandlist Adapter:

public class ExpandableListAdapter extends BaseExpandableListAdapter {

HashMap<String,ArrayList<String>> listDataEditText;

int expandedGroup=0;

private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, ArrayList<String>> _listDataChild;

public ExpandableListAdapter(Context context, List<String> listDataHeader,
                             HashMap<String, ArrayList<String>> listChildData) {
    this._context = context;
    this._listDataHeader = listDataHeader;
    this._listDataChild = listChildData;

    listDataEditText  = new HashMap<>();

    for(int j=0;j<listDataHeader.size();j++) {
        ArrayList<String> preInsertion = new ArrayList<>();
        for (int i =0;i<this._listDataChild.get(_listDataHeader.get(j)).size();i++)
        {
                preInsertion.add("");
        }

        listDataEditText.put(listDataHeader.get(j),preInsertion);

    }

}

@Override
public Object getChild(int groupPosition, int childPosititon) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .get(childPosititon);
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    return childPosition;
}

@Override
public View getChildView(final int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    final String childText = (String) getChild(groupPosition, childPosition);

    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_item, null);
    }
    TextView txtListChild = convertView.findViewById(R.id.lblListItem);

    txtListChild.setText(childText);
    return convertView;
}

@Override
public int getChildrenCount(int groupPosition) {
    return this._listDataChild.get(this._listDataHeader.get(groupPosition))
            .size();
}

@Override
public Object getGroup(int groupPosition) {
    return this._listDataHeader.get(groupPosition);
}

@Override
public int getGroupCount() {
    return this._listDataHeader.size();
}

@Override
public long getGroupId(int groupPosition) {
    return groupPosition;
}

@Override
public View getGroupView(final int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    String headerTitle = (String) getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.list_group, null);
    }

    TextView lblListHeader = (TextView) convertView
            .findViewById(R.id.lblListHeader);
    lblListHeader.setTypeface(null, Typeface.BOLD);
    lblListHeader.setText(headerTitle);

    return convertView;
}

@Override
public boolean hasStableIds() {
    return false;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    return true;
}

 }

and here is list items:

for GroupView "list_group":

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="81dp">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/lblListHeader"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="48dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="33dp" />

</RelativeLayout>
</android.support.constraint.ConstraintLayout>

for Child View "list_item":

 <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:id="@+id/linearLayout4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:orientation="horizontal"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.194"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.137">

    <TextView
        android:id="@+id/lblListItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="TextView"
        android:textColor="#000000"
        android:textSize="17dp" />

</LinearLayout>

</android.support.constraint.ConstraintLayout>

Try it and let me know if need more.

Edited latest

Use this SimpleAdapter for showing all sub_categories list:

public class SimpleAdapter extends BaseAdapter {

ArrayList<String> stringArrayList;
Context context;

public SimpleAdapter(Context context,ArrayList<String> stringArrayList)
{
    this.context = context;
    this.stringArrayList = stringArrayList;
}

@Override
public int getCount() {
    return stringArrayList.size();
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    if (view == null) {
        LayoutInflater infalInflater = (LayoutInflater) this.context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = infalInflater.inflate(R.layout.list_item, null);
    }
    TextView txtListChild = view.findViewById(R.id.lblListItem);

    txtListChild.setText(stringArrayList.get(i));

    return view;
}
}

and make main layout as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
>

<ListView
    android:id="@+id/listView"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</ListView>

</LinearLayout>

ContentLicense: CC BY-SA 4.0


问:
Where to place AdMob banner?
I am about to implement AdMob banner into my application with 1000 active users.

I have 1 main Activity with 5 fragments inside, each fragment represents different tab.

Shall I use 1 main banner on main activity that is holding these fragments or should I use different banner on each fragment?

Remember, I am making decision on best earning solution. Can I get more money on 5 banners each on his own banner? AdMob does give a little for impresions.

答: You should place ads in mainactivity to make the ads not request a new ads again. If u choose to put ads on every each fragment, it just only make your apps take much data that make user run it slow if they have many task. And also you can prevent the ads from invalid click.</p>

Title: Where to place AdMob banner?


问:
Regarding WPF and web development?
i don't know anything about WPF. so a question has come to my mind that when we develop apps in WPF that can be run as web application without changing code. please comment. thanks.</p>

答:
WPF is a graphic user interface technology for windows client application. So you cannot do web applications with WPF ( i'm simplying , it is not entirely true ).
If you want to create an application that runs in a browser , you can use Silverlight which is a different solution.
So to sum up. If you want to create a software like photoshop , use WPF.
if you want to make a website ( web apps are web sites ), use Silverlight ( or javascript and HTML or Flash ... ).</p>

ContentLicense: CC BY-SA 2.5

Title: Regarding WPF and web development?


问:
Why i cant join string with first value of dictionary?
I would like to ask that why cant i join the string with the first value of the dictionary?

```<code>Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));
</code>```

These are the value of Z now

```<code>0
Test_1
Test_2
Test_3
</code>```

答:
string.Join concatenates the strings with specified value. What you want is to prepend a value to all of the strings, so use String.Concat instead:

```<code>string z = string.Concat(d.Select(x => "Test_" + x.Value + "\n"));
</code>```

Body:
I would like to ask that why cant i join the string with the first value of the dictionary?

Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));

These are the value of Z now

0
Test_1
Test_2
Test_3

Body:
string.Join concatenates the strings with specified value. What you want is to prepend a value to all of the strings, so use String.Concat instead:

string z = string.Concat(d.Select(x => "Test_" + x.Value + "\n"));


问:
TypeError: (intermediate value).keys(...).map is not a function
I am getting a strange error, could somebody help me fix this out?

```<code>const myArray = new Array(4)
    .keys()
    .map((v, i) => (
          console.log('print:', v, i)
      )
    )
console.log('myArray print: ', myArray);
</code>```

I am getting this error:

```<code>TypeError: (intermediate value).keys(...).map is not a function
</code>```

update:

i want to use the i to look up some stuff from another existing array.

```<code>const myArray = new Array(4)
    .keys()
    .map((v, i) => ({
      name: i
      })
    )
console.log('myArray print: ', myArray);
</code>```

edit:

this question is not a duplicate, It is trying to iterate over a certain number and create a new object using the iterations.

答:
Array.keys() returns an iterator Object which is an object and does not have a property map in it. You can convert it to do

const myArray = [...new Array(4).keys()].map((v, i) => ({
      name: i
      })
    )
console.log('myArray print: ', myArray);```

Body:
I am getting a strange error, could somebody help me fix this out?

const myArray = new Array(4)
    .keys()
    .map((v, i) => (
          console.log('print:', v, i)
      )
    )
console.log('myArray print: ', myArray);

I am getting this error:

TypeError: (intermediate value).keys(...).map is not a function

update:

i want to use the i to look up some stuff from another existing array.

const myArray = new Array(4)
    .keys()
    .map((v, i) => ({
      name: i
      })
    )
console.log('myArray print: ', myArray);

edit:

this question is not a duplicate, It is trying to iterate over a certain number and create a new object using the iterations.


答:
I would suggest putting only one banner into one Activity. It can be placed outside of any fragment. It is better for user and developer. For the user: lesser internet connections, a lesser number of lags, better UI.
For you: only a click of a user gives to you the money. But if you increase the number of downloaded banners it obviously decreases eCPM. BTW, it improves the UI test too, lesser memory usage, etc.</p>

Title: Where to place AdMob banner?

Body:
I am about to implement AdMob banner into my application with 1000 active users.

I have 1 main Activity with 5 fragments inside, each fragment represents different tab.

Shall I use 1 main banner on main activity that is holding these fragments or should I use different banner on each fragment?

Remember, I am making decision on best earning solution. Can I get more money on 5 banners each on his own banner? AdMob does give a little for impresions.


问:
Excel VBA - find and delete blank cells in a row-range
I want to make a macro that finds every blank cell in column D. For example: If D4 has a blank cell, the cells B4, C4, D4, E4 should be deleted and shifted up so that there are now more blank cells.

Somehow the macro doesn't delete anything.

```<code>Dim delREASON As Variant
Dim findReason As Range
Dim DelRng As Range

    With ThisWorkbook.Sheets("getDATA")
        delREASON = Null
        For Each findReason In .Range(.Range("D8"), .Range("D8").End(xlDown))
            If Not (IsError(Application.Match(findReason.Value, delREASON, 0))) Then
                If Not DelRng Is Nothing Then
            Set DelRng = Application.Union(DelRng, .Range(.Cells(findReason.Row, "B"), .Cells(findReason.Row, "E")))
        Else
            Set DelRng = .Range(.Cells(findReason.Row, "B"), .Cells(findReason.Row, "E"))
        End If
    End If
Next
    End With
</code>```

答:
Locate the blank cells in column D and then create a union of the other adjoining columns.</p>

```<code>Dim blnks As Range
With ThisWorkbook.Sheets("getDATA")
    On Error Resume Next
    Set blnks = .Columns("D").SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0
    If Not blnks Is Nothing Then
        Set blnks = Union(blnks.Offset(0, -2), blnks.Offset(0, -1), _
                          blnks, blnks.Offset(0, 1))
        blnks.Delete shift:=xlUp
    End If
End With
</code>```

Body:
I want to make a macro that finds every blank cell in column D. For example: If D4 has a blank cell, the cells B4, C4, D4, E4 should be deleted and shifted up so that there are now more blank cells.

Somehow the macro doesn't delete anything.

Dim delREASON As Variant
Dim findReason As Range
Dim DelRng As Range

    With ThisWorkbook.Sheets("getDATA")
        delREASON = Null
        For Each findReason In .Range(.Range("D8"), .Range("D8").End(xlDown))
            If Not (IsError(Application.Match(findReason.Value, delREASON, 0))) Then
                If Not DelRng Is Nothing Then
            Set DelRng = Application.Union(DelRng, .Range(.Cells(findReason.Row, "B"), .Cells(findReason.Row, "E")))
        Else
            Set DelRng = .Range(.Cells(findReason.Row, "B"), .Cells(findReason.Row, "E"))
        End If
    End If
Next
    End With

Body:
Locate the blank cells in column D and then create a union of the other adjoining columns.

Dim blnks As Range
With ThisWorkbook.Sheets("getDATA")
    On Error Resume Next
    Set blnks = .Columns("D").SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0
    If Not blnks Is Nothing Then
        Set blnks = Union(blnks.Offset(0, -2), blnks.Offset(0, -1), _
                          blnks, blnks.Offset(0, 1))
        blnks.Delete shift:=xlUp
    End If
End With


问:
GuavaCache expireAfterWrite() is causing too many blocked threads
We have a use case where our data is becoming stale after some time. Hence we chose expireAfterWrite cache eviction strategy. However this is causing too many blocked threads in threadpool. Any idea why this might be happening and if there is any way to avoid this.

sample thread pool log:

```<code>Debugger attached successfully.
Server compiler detected.
JVM version is 25.112-b15
Deadlock Detection:

No deadlocks found.

Thread 7546: (state = BLOCKED)
 - sun.misc.Unsafe.park(boolean, long) @bci=0 (Compiled frame; information may be imprecise)
 - java.util.concurrent.locks.LockSupport.parkNanos(java.lang.Object, long) @bci=20, line=215 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(java.util.concurrent.SynchronousQueue$TransferStack$SNode, boolean, long) @bci=160, line=460 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.transfer(java.lang.Object, boolean, long) @bci=102, line=362 (Compiled frame)
 - java.util.concurrent.SynchronousQueue.poll(long, java.util.concurrent.TimeUnit) @bci=11, line=941 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.getTask() @bci=134, line=1066 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.runWorker(java.util.concurrent.ThreadPoolExecutor$Worker) @bci=26, line=1127 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor$Worker.run() @bci=5, line=617 (Compiled frame)
 - java.lang.Thread.run() @bci=11, line=745 (Compiled frame)

Locked ownable synchronizers:
    - None

Thread 1268: (state = BLOCKED)
 - sun.misc.Unsafe.park(boolean, long) @bci=0 (Compiled frame; information may be imprecise)
 - java.util.concurrent.locks.LockSupport.park(java.lang.Object) @bci=14, line=175 (Interpreted frame)
 - java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt() @bci=1, line=836 (Interpreted frame)
 - java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(int) @bci=72, line=997 (Interpreted frame)
 - java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(int) @bci=24, line=1304 (Compiled frame)
 - com.amazon.coral.google.common.util.concurrent.AbstractFuture$Sync.get() @bci=2 (Compiled frame)
 - com.amazon.coral.google.common.util.concurrent.AbstractFuture.get() @bci=4 (Compiled frame)
 - com.amazon.coral.google.common.util.concurrent.Uninterruptibles.getUninterruptibly(java.util.concurrent.Future) @bci=3 (Compiled frame)
 - com.amazon.coral.google.common.cache.LocalCache$LoadingValueReference.waitForValue() @bci=4 (Interpreted frame)
 - com.amazon.coral.google.common.cache.LocalCache$Segment.waitForLoadingValue(com.amazon.coral.google.common.cache.LocalCache$ReferenceEntry, java.lang.Object, com.amazon.coral.google.common.cache.LocalCache$ValueReference) @bci=44 (Interpreted frame)
 - com.amazon.coral.google.common.cache.LocalCache$Segment.get(java.lang.Object, int, com.amazon.coral.google.common.cache.CacheLoader) @bci=122 (Interpreted frame)
 - com.amazon.coral.google.common.cache.LocalCache.get(java.lang.Object, com.amazon.coral.google.common.cache.CacheLoader) @bci=17 (Compiled frame)
 - com.amazon.coral.google.common.cache.LocalCache.getOrLoad(java.lang.Object) @bci=6 (Compiled frame)
 - com.amazon.coral.google.common.cache.LocalCache$LocalLoadingCache.get(java.lang.Object) @bci=5 (Compiled frame)
 - com.amazon.csapp.services.SmartVideoCacheService.getVideos(com.amazon.csapp.utils.MetricsContext, com.amazon.csapp.utils.AmazonRequestInfo) @bci=33, line=214 (Compiled frame)
 - com.amazon.csapp.rest.resource.v2.VideoResource.getVideos(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) @bci=67, line=56 (Interpreted frame)
 - sun.reflect.GeneratedMethodAccessor90.invoke(java.lang.Object, java.lang.Object[]) @bci=88 (Compiled frame)
 - sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) @bci=6, line=43 (Compiled frame)
 - java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) @bci=56, line=498 (Compiled frame)
 - org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) @bci=3, line=81 (Interpreted frame)
 - org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(java.lang.Object, java.lang.Object[]) @bci=39, line=128 (Interpreted frame)
 - org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(java.lang.Object, javax.ws.rs.core.Request) @bci=6, line=195 (Interpreted frame)
 - org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(java.lang.Object, org.glassfish.jersey.server.ContainerRequest) @bci=3, line=94 (Compiled frame)
 - org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(org.glassfish.jersey.server.ContainerRequest, java.lang.Object) @bci=13, line=353 (Compiled frame)
 - org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(org.glassfish.jersey.server.ContainerRequest) @bci=103, line=343 (Interpreted frame)
 - org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(java.lang.Object) @bci=5, line=102 (Interpreted frame)
 - org.glassfish.jersey.server.ServerRuntime$1.run() @bci=198, line=237 (Compiled frame)
 - org.glassfish.jersey.internal.Errors$1.call() @bci=4, line=271 (Compiled frame)
 - org.glassfish.jersey.internal.Errors$1.call() @bci=1, line=267 (Compiled frame)
 - org.glassfish.jersey.internal.Errors.process(java.util.concurrent.Callable, boolean) @bci=36, line=315 (Compiled frame)
 - org.glassfish.jersey.internal.Errors.process(org.glassfish.jersey.internal.util.Producer, boolean) @bci=2, line=297 (Compiled frame)
 - org.glassfish.jersey.internal.Errors.process(java.lang.Runnable) @bci=9, line=267 (Compiled frame)
 - org.glassfish.jersey.process.internal.RequestScope.runInScope(java.lang.Runnable) @bci=25, line=322 (Interpreted frame)
 - org.glassfish.jersey.server.ServerRuntime.process(org.glassfish.jersey.server.ContainerRequest) @bci=22, line=211 (Interpreted frame)
 - org.glassfish.jersey.server.ApplicationHandler.handle(org.glassfish.jersey.server.ContainerRequest) @bci=5, line=979 (Compiled frame)
 - org.glassfish.jersey.servlet.WebComponent.service(java.net.URI, java.net.URI, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=115, line=344 (Compiled frame)
 - org.glassfish.jersey.servlet.ServletContainer.service(java.net.URI, java.net.URI, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=9, line=372 (Compiled frame)
 - org.glassfish.jersey.servlet.ServletContainer.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=321, line=335 (Compiled frame)
 - com.amazon.csapp.servlet.JerseyServletContainer.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=15, line=26 (Compiled frame)
 - org.glassfish.jersey.servlet.ServletContainer.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) @bci=39, line=218 (Compiled frame)
 - org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) @bci=376, line=290 (Compiled frame)
 - org.apache.catalina.core.ApplicationFilterChain.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) @bci=101, line=206 (Compiled frame)
 - org.apache.catalina.core.StandardWrapperValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=804, line=233 (Compiled frame)
 - org.apache.catalina.core.StandardContextValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=365, line=191 (Compiled frame)
 - org.apache.catalina.authenticator.AuthenticatorBase.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=327, line=470 (Compiled frame)
 - org.apache.catalina.core.StandardHostValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=64, line=127 (Compiled frame)
 - org.apache.catalina.valves.ErrorReportValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=6, line=103 (Compiled frame)
 - com.amazon.tomcat.valves.QueryLogValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=47, line=78 (Compiled frame)
 - org.apache.catalina.valves.AccessLogValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=24, line=617 (Compiled frame)
 - org.apache.catalina.core.StandardEngineValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=42, line=109 (Compiled frame)
 - org.apache.catalina.connector.CoyoteAdapter.service(org.apache.coyote.Request, org.apache.coyote.Response) @bci=158, line=293 (Compiled frame)
 - org.apache.coyote.http11.Http11Processor.process(java.net.Socket) @bci=545, line=859 (Compiled frame)
 - org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(java.net.Socket) @bci=73, line=610 (Compiled frame)
 - org.apache.tomcat.util.net.JIoEndpoint$Worker.run() @bci=41, line=503 (Compiled frame)
 - java.lang.Thread.run() @bci=11, line=745 (Compiled frame)
</code>```

答:
You should probably add a dedicated thread to refresh the cache's values more frequently. As Ben Manes suggests configuring a refreshAfterWrite that's lower than your expiration threshold would also help, but you'll want to override reload() to do the work asynchronously.

It's also possible there are hotspots in your code causing numerous separate paths to try to hit the same cache keys simultaneously. If you don't expect that behavior (e.g. you expected approximately one thread at a time to be accessing a key) you might want to investigate whether there's some missing locking semantics causing too many threads to be reading from the cache at the same time, or a different cause of hotspots such as unusual request patterns.

Body:
We have a use case where our data is becoming stale after some time. Hence we chose expireAfterWrite cache eviction strategy. However this is causing too many blocked threads in threadpool. Any idea why this might be happening and if there is any way to avoid this.

sample thread pool log:

Debugger attached successfully.
Server compiler detected.
JVM version is 25.112-b15
Deadlock Detection:

No deadlocks found.

Thread 7546: (state = BLOCKED)
 - sun.misc.Unsafe.park(boolean, long) @bci=0 (Compiled frame; information may be imprecise)
 - java.util.concurrent.locks.LockSupport.parkNanos(java.lang.Object, long) @bci=20, line=215 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.awaitFulfill(java.util.concurrent.SynchronousQueue$TransferStack$SNode, boolean, long) @bci=160, line=460 (Compiled frame)
 - java.util.concurrent.SynchronousQueue$TransferStack.transfer(java.lang.Object, boolean, long) @bci=102, line=362 (Compiled frame)
 - java.util.concurrent.SynchronousQueue.poll(long, java.util.concurrent.TimeUnit) @bci=11, line=941 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.getTask() @bci=134, line=1066 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor.runWorker(java.util.concurrent.ThreadPoolExecutor$Worker) @bci=26, line=1127 (Compiled frame)
 - java.util.concurrent.ThreadPoolExecutor$Worker.run() @bci=5, line=617 (Compiled frame)
 - java.lang.Thread.run() @bci=11, line=745 (Compiled frame)

Locked ownable synchronizers:
    - None

Thread 1268: (state = BLOCKED)
 - sun.misc.Unsafe.park(boolean, long) @bci=0 (Compiled frame; information may be imprecise)
 - java.util.concurrent.locks.LockSupport.park(java.lang.Object) @bci=14, line=175 (Interpreted frame)
 - java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt() @bci=1, line=836 (Interpreted frame)
 - java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(int) @bci=72, line=997 (Interpreted frame)
 - java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(int) @bci=24, line=1304 (Compiled frame)
 - com.amazon.coral.google.common.util.concurrent.AbstractFuture$Sync.get() @bci=2 (Compiled frame)
 - com.amazon.coral.google.common.util.concurrent.AbstractFuture.get() @bci=4 (Compiled frame)
 - com.amazon.coral.google.common.util.concurrent.Uninterruptibles.getUninterruptibly(java.util.concurrent.Future) @bci=3 (Compiled frame)
 - com.amazon.coral.google.common.cache.LocalCache$LoadingValueReference.waitForValue() @bci=4 (Interpreted frame)
 - com.amazon.coral.google.common.cache.LocalCache$Segment.waitForLoadingValue(com.amazon.coral.google.common.cache.LocalCache$ReferenceEntry, java.lang.Object, com.amazon.coral.google.common.cache.LocalCache$ValueReference) @bci=44 (Interpreted frame)
 - com.amazon.coral.google.common.cache.LocalCache$Segment.get(java.lang.Object, int, com.amazon.coral.google.common.cache.CacheLoader) @bci=122 (Interpreted frame)
 - com.amazon.coral.google.common.cache.LocalCache.get(java.lang.Object, com.amazon.coral.google.common.cache.CacheLoader) @bci=17 (Compiled frame)
 - com.amazon.coral.google.common.cache.LocalCache.getOrLoad(java.lang.Object) @bci=6 (Compiled frame)
 - com.amazon.coral.google.common.cache.LocalCache$LocalLoadingCache.get(java.lang.Object) @bci=5 (Compiled frame)
 - com.amazon.csapp.services.SmartVideoCacheService.getVideos(com.amazon.csapp.utils.MetricsContext, com.amazon.csapp.utils.AmazonRequestInfo) @bci=33, line=214 (Compiled frame)
 - com.amazon.csapp.rest.resource.v2.VideoResource.getVideos(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) @bci=67, line=56 (Interpreted frame)
 - sun.reflect.GeneratedMethodAccessor90.invoke(java.lang.Object, java.lang.Object[]) @bci=88 (Compiled frame)
 - sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) @bci=6, line=43 (Compiled frame)
 - java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) @bci=56, line=498 (Compiled frame)
 - org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[]) @bci=3, line=81 (Interpreted frame)
 - org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(java.lang.Object, java.lang.Object[]) @bci=39, line=128 (Interpreted frame)
 - org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(java.lang.Object, javax.ws.rs.core.Request) @bci=6, line=195 (Interpreted frame)
 - org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(java.lang.Object, org.glassfish.jersey.server.ContainerRequest) @bci=3, line=94 (Compiled frame)
 - org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(org.glassfish.jersey.server.ContainerRequest, java.lang.Object) @bci=13, line=353 (Compiled frame)
 - org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(org.glassfish.jersey.server.ContainerRequest) @bci=103, line=343 (Interpreted frame)
 - org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(java.lang.Object) @bci=5, line=102 (Interpreted frame)
 - org.glassfish.jersey.server.ServerRuntime$1.run() @bci=198, line=237 (Compiled frame)
 - org.glassfish.jersey.internal.Errors$1.call() @bci=4, line=271 (Compiled frame)
 - org.glassfish.jersey.internal.Errors$1.call() @bci=1, line=267 (Compiled frame)
 - org.glassfish.jersey.internal.Errors.process(java.util.concurrent.Callable, boolean) @bci=36, line=315 (Compiled frame)
 - org.glassfish.jersey.internal.Errors.process(org.glassfish.jersey.internal.util.Producer, boolean) @bci=2, line=297 (Compiled frame)
 - org.glassfish.jersey.internal.Errors.process(java.lang.Runnable) @bci=9, line=267 (Compiled frame)
 - org.glassfish.jersey.process.internal.RequestScope.runInScope(java.lang.Runnable) @bci=25, line=322 (Interpreted frame)
 - org.glassfish.jersey.server.ServerRuntime.process(org.glassfish.jersey.server.ContainerRequest) @bci=22, line=211 (Interpreted frame)
 - org.glassfish.jersey.server.ApplicationHandler.handle(org.glassfish.jersey.server.ContainerRequest) @bci=5, line=979 (Compiled frame)
 - org.glassfish.jersey.servlet.WebComponent.service(java.net.URI, java.net.URI, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=115, line=344 (Compiled frame)
 - org.glassfish.jersey.servlet.ServletContainer.service(java.net.URI, java.net.URI, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=9, line=372 (Compiled frame)
 - org.glassfish.jersey.servlet.ServletContainer.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=321, line=335 (Compiled frame)
 - com.amazon.csapp.servlet.JerseyServletContainer.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) @bci=15, line=26 (Compiled frame)
 - org.glassfish.jersey.servlet.ServletContainer.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse) @bci=39, line=218 (Compiled frame)
 - org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) @bci=376, line=290 (Compiled frame)
 - org.apache.catalina.core.ApplicationFilterChain.doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse) @bci=101, line=206 (Compiled frame)
 - org.apache.catalina.core.StandardWrapperValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=804, line=233 (Compiled frame)
 - org.apache.catalina.core.StandardContextValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=365, line=191 (Compiled frame)
 - org.apache.catalina.authenticator.AuthenticatorBase.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=327, line=470 (Compiled frame)
 - org.apache.catalina.core.StandardHostValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=64, line=127 (Compiled frame)
 - org.apache.catalina.valves.ErrorReportValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=6, line=103 (Compiled frame)
 - com.amazon.tomcat.valves.QueryLogValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=47, line=78 (Compiled frame)
 - org.apache.catalina.valves.AccessLogValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=24, line=617 (Compiled frame)
 - org.apache.catalina.core.StandardEngineValve.invoke(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response) @bci=42, line=109 (Compiled frame)
 - org.apache.catalina.connector.CoyoteAdapter.service(org.apache.coyote.Request, org.apache.coyote.Response) @bci=158, line=293 (Compiled frame)
 - org.apache.coyote.http11.Http11Processor.process(java.net.Socket) @bci=545, line=859 (Compiled frame)
 - org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(java.net.Socket) @bci=73, line=610 (Compiled frame)
 - org.apache.tomcat.util.net.JIoEndpoint$Worker.run() @bci=41, line=503 (Compiled frame)
 - java.lang.Thread.run() @bci=11, line=745 (Compiled frame)


问:
What is the meaning of XOR in x86 assembly?
I'm getting into assembly and I keep running into xor, for example:

```<code>xor     ax, ax
</code>```

Does it just clear the register's value?

答:
xor ax, ax is the fastest possible way to set the ax register to 0. Fastest in terms of the size of instruction and number of instructions. For detail about how it works you need a little knowledge of bit arithmetic.

XOR operation between two bits returns 1 if one and only one of the two bits is 1; 0 otherwise. Another way to explain is that that it returns 1 if the two bits are different; 0 otherwise.

XOR operation between two binary numbers of same length works likewise on a bit-by-bit basis. XOR two numbers you get a number with bits set to 1 where corresponding bits of the two operands differ, 0 when corresponding bits are same.

From this knowledge its fairly easy to see that if the two operands are the same (ax and ax for example) the result will be 0.

Body:
I'm getting into assembly and I keep running into xor, for example:

xor     ax, ax

Does it just clear the register's value?


问:
Registered Plugin on Retrieve of Entity facing an Error "Unauthorized Error"
I registered a plugin on Retrieve of Entity.
but when I open record shows "Unauthorized User Error".
I want to to decode some field values.
I also used Trace log but shows nothing, Shows Same Error</p>

答:
When you have error in code and you registered a plugin on Retrieve of Entity, it shows the "Unauthorized User Error".
Or When you want to Throw Exception in that Plugin means on Retrieve of Entity, it will also shows same Error.
and there is no trace log means you can't trace it.
I registered the Plugin on Retrieve on Pre-Operation of Entity.

I solved the Error, and handle the exceptions.
and then update the Plugin, it is working fine.

On Retrieve you can't Trace plugin, and when you want to throw exception or there is error in your code it will shows Error when you open the record the error is "Unauthorized User Error".


问:
Elements form array.map don't render
I am trying to render elements from my state (array) but they don't want render on the screen. If I perform console.log(b.name) it logs my names in console.

```<code>renderAllElements() {
    this.state.myData.map(b => {
        return(
            <div>
                <h4>{b.name}</h4>
            </div>
        )
    })
}

render() {
    return (
        <div>
            {this.renderAllElements()}
        </div>
    )
}
</code>```

答:
Since you already use array functions you can alternatively rewrite it without curly braces:

```<code>renderAllElements = () => (
    this.state.myData.map(b => (
        <div>
            <h4>{b.name}</h4>
        </div>
    ));
)
</code>```

So you don't need to remember about return statement :)

Title: Elements form array.map don't render

Body:
I am trying to render elements from my state (array) but they don't want render on the screen. If I perform console.log(b.name) it logs my names in console.

renderAllElements() {
    this.state.myData.map(b => {
        return(

{b.name}

        )
    })
}

render() {
    return (

            {this.renderAllElements()}

    )
}

Body:
Since you already use array functions you can alternatively rewrite it without curly braces:

renderAllElements = () => (
    this.state.myData.map(b => (
        <div>
            <h4>{b.name}</h4>
        </div>
    ));
)

So you don't need to remember about return statement :)


问:
I'm not able to connect to SQL Server Express using JDBC with Android studio
I'm trying to connect to SQL Server (localhost) to be able to save information on the database however whenever I try to achieve so for some reason when I go from MainActivity.java to Main2Activity.java my application stops working for about 20 seconds then comes up with a toast message (connection refused) , please advise what am I doing wrong

Main2Activity.java

```<code>package com.example.omar.externaldatabaseconnection;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Main2Activity extends AppCompatActivity {

EditText et_name, et_age, et_address, et_email ,et_telephone;
Button btn_save;
DatabaseConnection db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

if(Build.VERSION.SDK_INT > 9){
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

et_name = (EditText) findViewById(R.id.et_name);
et_age = (EditText) findViewById(R.id.et_age);
et_address = (EditText) findViewById(R.id.et_address);
et_email = (EditText) findViewById(R.id.et_email);
et_telephone = (EditText) findViewById(R.id.et_telephone);
btn_save = (Button) findViewById(R.id.btn_save);
db = (DatabaseConnection) getApplication();
db.open();

btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db.save("insert into Employees values
('"+et_name.getText().toString().trim()+"',
'"+et_age.getText().toString().trim()+"',
'"+et_address.getText().toString().trim()+"',
'"+et_email.getText().toString().trim()+"',
'"+et_telephone.getText().toString().trim()+"')");
finish();
}
});
}

}
</code>```

DatabaseConnection.java

```<code>package com.example.omar.externaldatabaseconnection;

import android.app.Application;
import android.widget.Toast;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Connection;

public class DatabaseConnection extends Application {

Connection connection;
String url = "";
String DBName = "EmployeesDB";
String DBUserName = "PC NAME";
String DBPassword = "MSSQL Password";
String HostName = "10.0.2.2";
String Port = "MY PORT NUMBER";
Statement statement;

public void open(){
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
url = "jdbc:jtds:sqlserver://" + HostName +":"+Port+";"+ "databaseName=" +
DBName + ";user=" + DBUserName + ";password="+ DBPassword + "
instance=SQLEXPRESS;";
connection = DriverManager.getConnection(url, DBUserName, DBPassword);
}
catch (Exception e){
Toast.makeText(this, e.getCause().getMessage(), Toast.LENGTH_LONG).show();

}
}

public void save (String sql){
try {
statement = connection.createStatement();
statement.executeQuery(sql);
}
catch (Exception ex){
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
</code>```

答:
Sir android is a mobile platform and you just can't connect an android application with any database server i.e. Sql server, mysql or oracle directly, you have to create a local SQLITE database and populate it by fetching data from any of the above mention database servers through a WEB SERVICE again it's totally up to you if you choose php, asp , java etc for making your WEB Service. After you have populated your SQLITE database you will then be able to perform queries on local SQLITE database.

In simple words WEB SERVICE is the bridge between android application and a database server and you have to use one.

Body:
I'm trying to connect to SQL Server (localhost) to be able to save information on the database however whenever I try to achieve so for some reason when I go from MainActivity.java to Main2Activity.java my application stops working for about 20 seconds then comes up with a toast message (connection refused) , please advise what am I doing wrong

Main2Activity.java

package com.example.omar.externaldatabaseconnection;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class Main2Activity extends AppCompatActivity {

EditText et_name, et_age, et_address, et_email ,et_telephone;
Button btn_save;
DatabaseConnection db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);

if(Build.VERSION.SDK_INT > 9){
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

et_name = (EditText) findViewById(R.id.et_name);
et_age = (EditText) findViewById(R.id.et_age);
et_address = (EditText) findViewById(R.id.et_address);
et_email = (EditText) findViewById(R.id.et_email);
et_telephone = (EditText) findViewById(R.id.et_telephone);
btn_save = (Button) findViewById(R.id.btn_save);
db = (DatabaseConnection) getApplication();
db.open();

btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db.save("insert into Employees values
('"+et_name.getText().toString().trim()+"',
'"+et_age.getText().toString().trim()+"',
'"+et_address.getText().toString().trim()+"',
'"+et_email.getText().toString().trim()+"',
'"+et_telephone.getText().toString().trim()+"')");
finish();
}
});
}

}

DatabaseConnection.java

package com.example.omar.externaldatabaseconnection;

import android.app.Application;
import android.widget.Toast;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Connection;

public class DatabaseConnection extends Application {

Connection connection;
String url = "";
String DBName = "EmployeesDB";
String DBUserName = "PC NAME";
String DBPassword = "MSSQL Password";
String HostName = "10.0.2.2";
String Port = "MY PORT NUMBER";
Statement statement;

public void open(){
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
url = "jdbc:jtds:sqlserver://" + HostName +":"+Port+";"+ "databaseName=" +
DBName + ";user=" + DBUserName + ";password="+ DBPassword + "
instance=SQLEXPRESS;";
connection = DriverManager.getConnection(url, DBUserName, DBPassword);
}
catch (Exception e){
Toast.makeText(this, e.getCause().getMessage(), Toast.LENGTH_LONG).show();

}
}

public void save (String sql){
try {
statement = connection.createStatement();
statement.executeQuery(sql);
}
catch (Exception ex){
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
}


问:
How To get id of each Android notification?
Excuse me but other similar posts didn't help me.
 I use Xamarin and i appoint each notification an Id .
 I want to get clicked notification ID  in opened activity , and search it in my list and show related information
Thanks.</p>

答:
Try this:

MainActivity:

```<code>[Activity(Label = "App26", MainLauncher = true)]
    public class MainActivity : Activity
    {
        Button bt1;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            initVicew();
        }
        private void initVicew()
        {
            bt1 = FindViewById<Button>(Resource.Id.bt);
            bt1.Click += Bt1_Click;
        }
        private void Bt1_Click(object sender, EventArgs e)
        {
            for (int id=0;id<10;id++) {
                Intent activityIntent = new Intent(this, typeof(Activity1));
                activityIntent.PutExtra("id",""+id);
                var pendingIntent = PendingIntent.GetActivity(this, id, activityIntent, PendingIntentFlags.CancelCurrent);
                NotificationCompat.Builder builder = new  NotificationCompat.Builder(this);
                builder.SetAutoCancel(true)
                .SetDefaults((int)NotificationDefaults.All)
                .SetSmallIcon(Resource.Drawable.Capture)
                       .SetContentTitle("دنیا طب دام")
                       .SetContentText(""+id)
                       .SetContentIntent(pendingIntent)
                       .SetContentInfo("info");
                NotificationManager manager = (NotificationManager)this.GetSystemService(Context.NotificationService);
                manager.Notify(id, builder.Build());
                System.Diagnostics.Debug.Write("id="+id);
            }
        }
    }
</code>```

Main.axml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="click"
        android:id="@+id/bt" />
</LinearLayout>
</code>```

Activity1:

```<code>[Activity(Label = "Activity1")]
    public class Activity1 : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.layout2);
            string str = this.Intent.GetStringExtra("id");
            System.Diagnostics.Debug.Write(str);
        }
    }
</code>```

layout2:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>
</code>```

Body:
Try this:

MainActivity:

[Activity(Label = "App26", MainLauncher = true)]
    public class MainActivity : Activity
    {
        Button bt1;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            initVicew();
        }
        private void initVicew()
        {
            bt1 = FindViewById<Button>(Resource.Id.bt);
            bt1.Click += Bt1_Click;
        }
        private void Bt1_Click(object sender, EventArgs e)
        {
            for (int id=0;id<10;id++) {
                Intent activityIntent = new Intent(this, typeof(Activity1));
                activityIntent.PutExtra("id",""+id);
                var pendingIntent = PendingIntent.GetActivity(this, id, activityIntent, PendingIntentFlags.CancelCurrent);
                NotificationCompat.Builder builder = new  NotificationCompat.Builder(this);
                builder.SetAutoCancel(true)
                .SetDefaults((int)NotificationDefaults.All)
                .SetSmallIcon(Resource.Drawable.Capture)
                       .SetContentTitle("دنیا طب دام")
                       .SetContentText(""+id)
                       .SetContentIntent(pendingIntent)
                       .SetContentInfo("info");
                NotificationManager manager = (NotificationManager)this.GetSystemService(Context.NotificationService);
                manager.Notify(id, builder.Build());
                System.Diagnostics.Debug.Write("id="+id);
            }
        }
    }

Main.axml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="click"
        android:id="@+id/bt" />
</LinearLayout>

Activity1:

[Activity(Label = "Activity1")]
    public class Activity1 : Activity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.layout2);
            string str = this.Intent.GetStringExtra("id");
            System.Diagnostics.Debug.Write(str);
        }
    }

layout2:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</LinearLayout>