问:
helpers definition with `helper_method` in rails 5 api mode
Writing Rails applications I used to not have any instance variable in the views, instead I define helper_methods on the controller. Those methods will be used by the controller and the views the same way. This makes my code clean. Now with the api mode in Rails 5, I can't do that anymore, the helper_method is not there. The use of variables in the views is one of the things that I hate the most.

for example

```<code>class ProductsController < ActionController::API
   helper_method :products, :current_user

   private

   def products
     @products ||= current_user.products
   end

   def current_user
     @current_user ||= User.find(session[:user_id])
   end
end
</code>```

in the index.json.jbuilder view I'd like to use it this way.

```<code> json.products products do |product|
    json.name product.name
    json.price product.price
    # and so on
 end
</code>```

答:
I've not tested this but you can try to add AbstractController::Helpers module in your controller before helper_method

include AbstractController::Helpers

The source code of helper_method https://github.com/rails/rails/blob/b5db73076914e7103466bd76bec785cbcfe88875/actionpack/lib/abstract_controller/helpers.rb

Body:
Writing Rails applications I used to not have any instance variable in the views, instead I define helper_methods on the controller. Those methods will be used by the controller and the views the same way. This makes my code clean. Now with the api mode in Rails 5, I can't do that anymore, the helper_method is not there. The use of variables in the views is one of the things that I hate the most.

for example

class ProductsController < ActionController::API
   helper_method :products, :current_user

   private

   def products
     @products ||= current_user.products
   end

   def current_user
     @current_user ||= User.find(session[:user_id])
   end
end

in the index.json.jbuilder view I'd like to use it this way.

 json.products products do |product|
    json.name product.name
    json.price product.price
    # and so on
 end


来源: stackexchange

问:
Left join not working in codeigniter
I written query to get record from main table tpl_upload_csv_file and get related record from tbl_process_csv. I get all the records but the problem is if i have 1 id from tpl_upload_csv_file in tbl_process_csv for 5 rows its displaying 5 times. Same record is displaying 5 times.

```<code>$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
print_r($query->result());die;
return $query->result();
</code>```

My table structure is

tpl_upload_csv_file :

id

uploaded_file_name

uploaded_date_time

records_available

tbl_process_csv :

id

csv_file_id   -->(Reference if for table tpl_upload_csv_file)

record_no

process_status

reason

答:
Try this and let me know if any problem occur:</p>

```<code>$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->group_by('tbl_process_csv.csv_file_id');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
return $query->result();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Left join not working in codeigniter

Body:
I written query to get record from main table tpl_upload_csv_file and get related record from tbl_process_csv. I get all the records but the problem is if i have 1 id from tpl_upload_csv_file in tbl_process_csv for 5 rows its displaying 5 times. Same record is displaying 5 times.

$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
print_r($query->result());die;
return $query->result();

My table structure is

tpl_upload_csv_file :

id

uploaded_file_name

uploaded_date_time

records_available

tbl_process_csv :

id

csv_file_id   -->(Reference if for table tpl_upload_csv_file)

record_no

process_status

reason

Body:
Try this and let me know if any problem occur:

$this->db->select('tbl_process_csv.id, tbl_process_csv.record_no, tbl_process_csv.reason,tpl_upload_csv_file.uploaded_file_name, tpl_upload_csv_file.uploaded_date_time');
$this->db->from('tpl_upload_csv_file');
$this->db->join('tbl_process_csv', 'tbl_process_csv.csv_file_id = tpl_upload_csv_file.id', 'left');
$this->db->where('tbl_process_csv.process_status', 3);
$this->db->group_by('tbl_process_csv.csv_file_id');
$this->db->order_by('tbl_process_csv.date_of_processing', 'desc');
$query = $this->db->get();
return $query->result();


问:
How to delete duplicates in a list of lists?
What did I do wrong and what should I do to fix my error in line three?

I'm trying to

Go through each inside list in expsList

Delete any duplicates using DeleteDuplicates and using the Table form of
Table[expr,{i,{i1,i2.....}}] uses the successive values i1,i2,......

I'm trying to delete duplicates within each individual list of lists and then trying to save the output into a variable named theDeleted. My code seems to work if I type   theDeleted = DeletedDuplicates[expList[[1]]] but not when I make use of the Table command. So what was the reason for the error and how will I be able to fix it (suing the specifics listed above).

```<code> n = 3;
  expList = Table[RandomInteger[{1, 365}, 20], {n}];
  theDeleted = DeleteDuplicates[expList[[Table[x, {x, {1, 2, 3}}]]]];
</code>```

答:
Try

```<code>theDeleted = Table[DeleteDuplicates[ expList[[x]] ], {x, {1, 2, 3 }} ];
</code>```

Your code creates something that looking at the Part Documentation is of type

expr[[{i1,i2,…}]]
    gives a list of the parts i1, i2, … of expr.

which just is the original list again.

Eventually you'd want something like

```<code>Map[ DeleteDuplicates, expList ]
</code>```

Body:
What did I do wrong and what should I do to fix my error in line three?

I'm trying to

Go through each inside list in expsList

Delete any duplicates using DeleteDuplicates and using the Table form of
Table[expr,{i,{i1,i2.....}}] uses the successive values i1,i2,......

I'm trying to delete duplicates within each individual list of lists and then trying to save the output into a variable named theDeleted. My code seems to work if I type   theDeleted = DeletedDuplicates[expList[[1]]] but not when I make use of the Table command. So what was the reason for the error and how will I be able to fix it (suing the specifics listed above).

 n = 3;
  expList = Table[RandomInteger[{1, 365}, 20], {n}];
  theDeleted = DeleteDuplicates[expList[[Table[x, {x, {1, 2, 3}}]]]];

Body:
Try

theDeleted = Table[DeleteDuplicates[ expList[[x]] ], {x, {1, 2, 3 }} ];

Your code creates something that looking at the Part Documentation is of type

expr[[{i1,i2,…}]]
    gives a list of the parts i1, i2, … of expr.

which just is the original list again.

Eventually you'd want something like

Map[ DeleteDuplicates, expList ]


问:
Add content type filter to existing view programmatically
I'm fairly new to Views and wanted to modify an existing view programatically. This artcile helps programmatically-set-a-views-filter-in-drupal-6-and-views-2, yet I have no idea how to customize it for my needs.

I need to modify a view and add a content type filter. Can anyone help?

答: I suspect that your best bet is to use hook_views_query_alter to add a WHERE to limit to a particular node.type.  You can examine $view to determine whether your view in question is being called, and then use the $query object to add the constraint.  Unfortunately, the views hooks are sparsely documented, and you often need to look at the actual module source to see what is really happening.

ContentLicense: CC BY-SA 2.5


问:
Close menus when clicking outside
I am working on a navbar for a website. It contains 3 dropdowns (and a bunch of other stuff I removed to keep the code concise). I want to be able to close the dropdowns by clicking outside of them. I have found many solutions which dealt with this (including the ones on this site), but all of them only accounted for having one such dropdown and I was unable to adapt them to my situation. What I want to achieve is:

If you click one of the buttons, it gets a is-active class (which makes its dropdown visible via a sibling selector in CSS) and removes it from all other buttons in the menu.

If you click on an open dropdown window, nothing happens.

If you click outside of any dropdown buttons and windows, the is-active class gets removed from all the nav buttons that have it.

No matter which recommended solution I tried, one or more of these stopped working as expected. Could anyone help me figure it out?

$('[data-toggle]').click(function() {
    var params = $(this).data('toggle');
    $(params['target']).toggleClass(params['class']);
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-nav__inner" style="height: 100%;">
        <div class="main-nav__group d-none d-md-block">
            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"books\"","class":"is-active"}' data-toggle-target="books">Knihy</button>
            <div class="main-nav__dropdown">
                // Dropdown contents
            </div>
        </div>
        <div class="main-nav__group d-none d-md-block">
            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"info\"","class":"is-active"}' data-toggle-target="info">Informácie</button>
            <div class="main-nav__dropdown">
                // Dropdown contents
            </div>
        </div>
        <div class="main-nav__group main-nav__group--popup">
            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"profile\"","class":"is-active"}' data-toggle-target="profile">
                <i class="icon-left fa fa-user" aria-hidden="true"></i>
            </button>
            <div class="main-nav__popup">
                // Dropdown contents
            </div>
        </div>
    </div></code>```

This code just toggles the dropdowns. My attempts at autoclosing functionality were in separate functions, but I no longer have them, since none of them worked - sorry.

A bonus question: Is there a way of putting the self keyword into an HTML data-attribute?

答:
You can try having another div, which would have 100% width and height. Then, add an onClick event to the div that removes the is-active class from your dropdowns. </p>

<p>Just make sure that the div has a lower z-index than the menu so it doesn't go above the menu. </p>

Title: Close menus when clicking outside

Body:
I am working on a navbar for a website. It contains 3 dropdowns (and a bunch of other stuff I removed to keep the code concise). I want to be able to close the dropdowns by clicking outside of them. I have found many solutions which dealt with this (including the ones on this site), but all of them only accounted for having one such dropdown and I was unable to adapt them to my situation. What I want to achieve is:

If you click one of the buttons, it gets a is-active class (which makes its dropdown visible via a sibling selector in CSS) and removes it from all other buttons in the menu.

If you click on an open dropdown window, nothing happens.

If you click outside of any dropdown buttons and windows, the is-active class gets removed from all the nav buttons that have it.

No matter which recommended solution I tried, one or more of these stopped working as expected. Could anyone help me figure it out?

$('[data-toggle]').click(function() {
    var params = $(this).data('toggle');
    $(params['target']).toggleClass(params['class']);
})

            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"books\"","class":"is-active"}' data-toggle-target="books">Knihy</button>

                // Dropdown contents

            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"info\"","class":"is-active"}' data-toggle-target="info">Informácie</button>

                // Dropdown contents

            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"profile\"","class":"is-active"}' data-toggle-target="profile">

            </button>

                // Dropdown contents

This code just toggles the dropdowns. My attempts at autoclosing functionality were in separate functions, but I no longer have them, since none of them worked - sorry.

A bonus question: Is there a way of putting the self keyword into an HTML data-attribute?

Body:
You can try having another div, which would have 100% width and height. Then, add an onClick event to the div that removes the is-active class from your dropdowns.

Just make sure that the div has a lower z-index than the menu so it doesn't go above the menu.


问:
Stacked chart with data array in d3 js
I have try to customize my existing code of Stacked Bar graph with the help of this link
https://bl.ocks.org/mbostock/1134768.

I have done this graph with the help of given link but i have some confusion about the data points on y axis as shown below in picture

Here is my full code of Stacked bar Graph

```<code>var data = [
    {month: 'Jan',total:100 ,A: 35, B: 5, C: 10},
    {month: 'Feb',total:200 ,A: 30, B: 10, C: 20},
    {month: 'Mar',total:300 ,A: 0, B: 10, C: 20}
];

var xData = ["A", "B", "C"];

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 400 - margin.left - margin.right,
        height = 300 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#chart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      xData.forEach(function(c) {
        d[c] = +d[c];}); })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};});});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x; }));

y.domain([0,d3.max(dataStackLayout[dataStackLayout.length - 1],
            function (d) { return d.y0 + d.y;}) ]).nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);});

layer.selectAll("rect")
        .data(function (d) {
            return d;})
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);})
        .attr("y", function (d) {
            return y(d.y + d.y0);})
        .attr("height", function (d) {
            return y(d.y0) - y(d.y + d.y0); })
        .attr("width", x.rangeBand() -1);

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
</code>```

As i have taken help from the given url, i have change my code which take array data as input instead of CSV file. But i think my data points(label) on y axis is not according to given data(key:total).

Any help should be appreciated.

答:
Here is solution about my confusion on how can i show the total count on y axis
because in my array data there is key 'total' which is total count of all states such as 'A','B' & 'C' shown in array data

```<code>    var data = [
    {month: "4/1854",total:"100" ,A: "45", B:"45", C:"10"},
    {month: "5/1854",total:"200" ,A:"80", B:"70", C:"50"},
    {month: "6/1854",total:"300" ,A:"0", B:"100", C:"200"}
];
</code>```

So as there is a total key in array data and i have to show as label on y axis.Here is my full code

```<code> var data = [
    {month: "4/1854",total:"100" ,A: "45", B:"45", C:"10"},
    {month: "5/1854",total:"200" ,A:"80", B:"70", C:"50"},
    {month: "6/1854",total:"300" ,A:"0", B:"100", C:"200"}
];

var xData = ["A", "B", "C"];

  var parseDate = d3.time.format("%m/%Y").parse;

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 500 - margin.left - margin.right,
        height = 350 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();
//console.info(color(0));

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(d3.time.format("%b"));

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#pie").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      d.month = parseDate(d.month);
      xData.forEach(function(c) {
        d[c] = +d[c];
      });

    })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};
    });
});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x;
}));

y.domain([0,
   d3.max(data, function(d) { return d.total; })
    ])
  .nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);
        });

layer.selectAll("rect")
        .data(function (d) {
            return d;
        })
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);
        })
        .attr("y", function (d) {
            return y(d.y + d.y0);
        })
        .attr("height", function (d) {
            // console.info(d.y0, d.y, y(d.y0), y(d.y))
            return y(d.y0) - y(d.y + d.y0);
        })
        .attr("width", x.rangeBand() -1);

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
}
</code>```

Title: Stacked chart with data array in d3 js

Body:
I have try to customize my existing code of Stacked Bar graph with the help of this link
https://bl.ocks.org/mbostock/1134768.

I have done this graph with the help of given link but i have some confusion about the data points on y axis as shown below in picture

Here is my full code of Stacked bar Graph

var data = [
    {month: 'Jan',total:100 ,A: 35, B: 5, C: 10},
    {month: 'Feb',total:200 ,A: 30, B: 10, C: 20},
    {month: 'Mar',total:300 ,A: 0, B: 10, C: 20}
];

var xData = ["A", "B", "C"];

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 400 - margin.left - margin.right,
        height = 300 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#chart").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      xData.forEach(function(c) {
        d[c] = +d[c];}); })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};});});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x; }));

y.domain([0,d3.max(dataStackLayout[dataStackLayout.length - 1],
            function (d) { return d.y0 + d.y;}) ]).nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);});

layer.selectAll("rect")
        .data(function (d) {
            return d;})
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);})
        .attr("y", function (d) {
            return y(d.y + d.y0);})
        .attr("height", function (d) {
            return y(d.y0) - y(d.y + d.y0); })
        .attr("width", x.rangeBand() -1);

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");

As i have taken help from the given url, i have change my code which take array data as input instead of CSV file. But i think my data points(label) on y axis is not according to given data(key:total).

Any help should be appreciated.

Body:
Here is solution about my confusion on how can i show the total count on y axis
because in my array data there is key 'total' which is total count of all states such as 'A','B' & 'C' shown in array data

    var data = [
    {month: "4/1854",total:"100" ,A: "45", B:"45", C:"10"},
    {month: "5/1854",total:"200" ,A:"80", B:"70", C:"50"},
    {month: "6/1854",total:"300" ,A:"0", B:"100", C:"200"}
];

So as there is a total key in array data and i have to show as label on y axis.Here is my full code

 var data = [
    {month: "4/1854",total:"100" ,A: "45", B:"45", C:"10"},
    {month: "5/1854",total:"200" ,A:"80", B:"70", C:"50"},
    {month: "6/1854",total:"300" ,A:"0", B:"100", C:"200"}
];

var xData = ["A", "B", "C"];

  var parseDate = d3.time.format("%m/%Y").parse;

var margin = {top: 20, right: 50, bottom: 30, left: 50},
        width = 500 - margin.left - margin.right,
        height = 350 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
        .rangeRoundBands([0, width], .35);

var y = d3.scale.linear()
        .rangeRound([height, 0]);

var color = d3.scale.category20();
//console.info(color(0));

var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .tickFormat(d3.time.format("%b"));

var yAxis = d3.svg.axis()
        .scale(y)
      .orient("left");

var svg = d3.select("#pie").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

data.forEach(function(d) {
      d.month = parseDate(d.month);
      xData.forEach(function(c) {
        d[c] = +d[c];
      });

    })

var dataIntermediate = xData.map(function (c) {
    return data.map(function (d) {
        return {x: d.month, y: d[c]};
    });
});

var dataStackLayout = d3.layout.stack()(dataIntermediate);

x.domain(dataStackLayout[0].map(function (d) {
    return d.x;
}));

y.domain([0,
   d3.max(data, function(d) { return d.total; })
    ])
  .nice();

var layer = svg.selectAll(".stack")
        .data(dataStackLayout)
        .enter().append("g")
        .attr("class", "stack")
        .style("fill", function (d, i) {
            console.info(i, color(i));
            return color(i);
        });

layer.selectAll("rect")
        .data(function (d) {
            return d;
        })
        .enter().append("rect")
        .attr("x", function (d) {
            console.info("dx", d.x,x(d.x), x.rangeBand());
            return x(d.x);
        })
        .attr("y", function (d) {
            return y(d.y + d.y0);
        })
        .attr("height", function (d) {
            // console.info(d.y0, d.y, y(d.y0), y(d.y))
            return y(d.y0) - y(d.y + d.y0);
        })
        .attr("width", x.rangeBand() -1);

svg.append("g")
        .attr("class", "axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

  svg.append("g")
      .attr("class", "axis axis--y")
      .call(yAxis)
       .append("text")
      .attr("transform", "rotate(-90)")
      .attr("y", 6)
      .attr("dy", ".71em")
      .style("text-anchor", "end");
}


问:
JxBrowser 6.14.2 System Requirements are unclear. Browser creation fails on several Linux distros
I'm using JxBrowser version 6.14.2 in an application that needs to work on as many OS's as possible, The System Requirements page states that JxBrowser runs on:

Windows, and macOS platforms (Intel and AMD), both 32- and 64-bit, and Linux 64-bit

Sidenote:
There is a dependency for jxbrowser-linux32 alongside these at http://maven.teamdev.com/repository/products/com/teamdev/jxbrowser/ which doesn't seem to work in my 32 bit linux VMs.  Is there something I am missing to get JxBrowser working on 32bit linux systems?

I have also tested this on 64 bit VMs with Ubuntu 17.04, Centos 6.8 and Fedora 25, all Java 1.8 and I continue to get the following error:

IPC process exited. exit code 127

People are saying I am missing a libcrypto.so.1.0.0 file but that file exists in my jxbrowser chromium dir.

Why won't JxBrowser work properly on my linux VMs? Thanks!

答:
Please take into account that the System Requirements in the article that you have mentioned are specified for the latest version of JxBrowser, which is 6.17 at the moment, and JxBrowser 6.14.2 is out of date.

Here are the platforms supported by JxBrowser 6.17:

Windows (32-bit & 64-bit)

Windows 7

Windows 8

Windows 8.1

Windows 10

Windows Server 2008 R2

Windows Server 2012

Windows Server 2016

Linux (64-bit)

Ubuntu 17.04 Desktop

Ubuntu 14.04+

Debian 8+

Fedora 24+

openSUSE 13.3+

RedHat Enterprise Linux 7

macOS (64-bit)

macOS 10.9.x - 10.13.x (Core i5, Core i7)

You can also look through the JxBrowser release notes to understand when the support of the platforms was added or removed.

For instance, Ubuntu 17.04 support was added in JxBrowser 6.16.

In addition, the Linux 32-bit support was dropped after migrating to Chromium 60 in JxBrowser 6.15, because Chromium itself does not support those platforms anymore.


问:
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
I have a java.util.Date in the format yyyy-mm-dd. I want it to be in the format mm-dd-yyyy

Below is the sample util I tried out for this conversion:

```<code>// Setting the pattern
SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");
// myDate is the java.util.Date in yyyy-mm-dd format
// Converting it into String using formatter
String strDate = sm.format(myDate);
//Converting the String back to java.util.Date
Date dt = sm.parse(strDate);
</code>```

Still the output I am getting is not in the format mm-dd-yyyy.

Kindly let me know how to format a java.util.Date from yyyy-mm-dd to mm-dd-yyyy

答:
It is simple use below codes.</p>

```<code>final Date todayDate = new Date();

System.out.println(todayDate);

System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(todayDate));

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(todayDate));

System.out.println(todayDate);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a java.util.Date in the format yyyy-mm-dd. I want it to be in the format mm-dd-yyyy

Below is the sample util I tried out for this conversion:

// Setting the pattern
SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");
// myDate is the java.util.Date in yyyy-mm-dd format
// Converting it into String using formatter
String strDate = sm.format(myDate);
//Converting the String back to java.util.Date
Date dt = sm.parse(strDate);

Still the output I am getting is not in the format mm-dd-yyyy.

Kindly let me know how to format a java.util.Date from yyyy-mm-dd to mm-dd-yyyy

Body:
It is simple use below codes.

final Date todayDate = new Date();

System.out.println(todayDate);

System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(todayDate));

System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(todayDate));

System.out.println(todayDate);


问:
T-SQL with three sub queries causing long execution time, any combination of 2 is near instant
I have the following T-SQL:

```<code>SELECT TOP (1) *, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 31
)  a, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 32
)  b, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 33
)  c
FROM RegressionRun RR
ORDER BY regression_run_id DESC
</code>```

Columns a, b and c are executing almost identical sub queries, the only difference being the result_type_id comparison in the WHERE clause.

If I run this query it takes ~10 seconds to complete.

If I remove any one of the sub query columns (a, b or c) it takes a few milliseconds to complete.

Why is adding the third sub query causing such a significant increase in performance?

Other possibly useful information:

The RegressionRun table has ~300 rows, TestRun has ~600 rows and Result has ~5 million rows

Issue is 100% reproducible

The SQL Server has plenty of spare resource and nothing else is using it when I am executing these queries

Using SQL Server 2017

Any suggestions as to why this may be occurring and how to resolve it would be greatly appreciated.

答:
I tryed not to change your query greatly.

Try this variant

```<code>SELECT *,
  (
      SELECT COUNT(result_id)
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 31
  )  a,
  (
      SELECT COUNT(result_id)
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 32
  )  b,
  (
      SELECT COUNT(result_id)
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 33
  )  c
FROM
  (
    SELECT TOP (1) *
    FROM RegressionRun
    ORDER BY regression_run_id DESC
  ) RR
</code>```

Or you can use OUTER APPLY

```<code>SELECT RR.*,C.a,C.b,C.c
FROM
  (
    SELECT TOP (1) *
    FROM RegressionRun
    ORDER BY regression_run_id DESC
  ) RR
OUTER APPLY
  (
      SELECT
        COUNT(CASE WHEN result_type_id = 31 THEN result_id END) a,
        COUNT(CASE WHEN result_type_id = 32 THEN result_id END) b,
        COUNT(CASE WHEN result_type_id = 33 THEN result_id END) c
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id
  ) C
</code>```

Body:
I have the following T-SQL:

SELECT TOP (1) *, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 31
)  a, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 32
)  b, (
    SELECT COUNT(result_id)
    FROM Result
    JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
    JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
    WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 33
)  c
FROM RegressionRun RR
ORDER BY regression_run_id DESC

Columns a, b and c are executing almost identical sub queries, the only difference being the result_type_id comparison in the WHERE clause.

If I run this query it takes ~10 seconds to complete.

If I remove any one of the sub query columns (a, b or c) it takes a few milliseconds to complete.

Why is adding the third sub query causing such a significant increase in performance?

Other possibly useful information:

The RegressionRun table has ~300 rows, TestRun has ~600 rows and Result has ~5 million rows

Issue is 100% reproducible

The SQL Server has plenty of spare resource and nothing else is using it when I am executing these queries

Using SQL Server 2017

Any suggestions as to why this may be occurring and how to resolve it would be greatly appreciated.

Body:
I tryed not to change your query greatly.

Try this variant

SELECT *,
  (
      SELECT COUNT(result_id)
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 31
  )  a,
  (
      SELECT COUNT(result_id)
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 32
  )  b,
  (
      SELECT COUNT(result_id)
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id AND result_type_id = 33
  )  c
FROM
  (
    SELECT TOP (1) *
    FROM RegressionRun
    ORDER BY regression_run_id DESC
  ) RR

Or you can use OUTER APPLY

SELECT RR.*,C.a,C.b,C.c
FROM
  (
    SELECT TOP (1) *
    FROM RegressionRun
    ORDER BY regression_run_id DESC
  ) RR
OUTER APPLY
  (
      SELECT
        COUNT(CASE WHEN result_type_id = 31 THEN result_id END) a,
        COUNT(CASE WHEN result_type_id = 32 THEN result_id END) b,
        COUNT(CASE WHEN result_type_id = 33 THEN result_id END) c
      FROM Result
      JOIN TestRun ON (TestRun.test_run_id = Result.test_run_id)
      JOIN RegressionRun ON (RegressionRun.regression_run_id = TestRun.regression_run_id)
      WHERE RegressionRun.regression_run_id = RR.regression_run_id
  ) C


问:
how to include constraint layout in main layout appropriately?
I have a main layout in which I am adding constraint layout as include tag.
Here is my main layout.

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

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/text1"
        android:textAlignment="center"
        android:textColor="@color/app_theme_primary"
        android:textSize="@dimen/large_header_text_size" />

    <TextView
        android:id="@+id/version_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/version_number"
        android:textAlignment="center"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size"/>

    <TextView
        android:id="@+id/develop_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/padding_10dp"
        android:gravity="center"
        android:text="@string/developed_text"
        android:textColor="@color/common_main_background"
        android:textStyle="bold" />

    <include layout="@layout/common_layout"/>

    <TextView
        android:id="@+id/trademarks"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="@string/trademarks"
        android:textAlignment="center"
        android:paddingTop="@dimen/multi_screen_small_padding"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size" />
    </LinearLayout>
</code>```

My constraint layout which consists of Two imageViews as below

```<code><android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/logo1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@null"
        android:paddingTop="@dimen/multi_screen_medium_padding"
        android:paddingStart="@dimen/multi_screen_medium_padding"
        android:paddingEnd="@dimen/multi_screen_medium_padding"
        android:src="@drawable/logo1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginRight="16dp"/>

    <ImageView
        android:id="@+id/logo2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:contentDescription="@null"
        android:src="@drawable/logo2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo1"
        android:layout_marginTop="8dp"
        app:layout_constraintDimensionRatio="w,1:1"/>

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

My requirement are

1.Constraint layout should be fitted properly in main layout but here I facing problem is last textview (id:trademarks) not showing on screen since constraint layout occupied the screen till bottom of the screen.

2. Second image (logo2) should adjust appropriately as per screen size (small screen small bigger screens some what bigger).

Please help me how to do it? Thanks in advance.

答:
After several hours hardwork, myself got perfect answer for my question. Please Check below

My main_layout.xml

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

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/app_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textColor="@color/theme_primary"
        android:textSize="@dimen/large_header_text_size"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/version_number"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/version_number"
        android:textAlignment="center"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/app_name"/>

    <TextView
        android:id="@+id/develop_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingTop="@dimen/padding_10dp"
        android:text="@string/developed_by"
        android:textColor="@color/common_main_background"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/version_number"/>

    <include
        android:id="@+id/common_layout"
        layout="@layout/common_layout"
        android:layout_width="0dp"
        android:layout_height="324dp"
        android:layout_marginTop="@dimen/multi_screen_medium_padding"
        app:layout_constraintBottom_toTopOf="@+id/trademarks"
        app:layout_constraintDimensionRatio="1:0.90"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/develop_text"/>

    <TextView
        android:id="@+id/trademarks"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/multi_screen_medium_padding"
        android:text="@string/trademarks"
        android:textAlignment="center"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/common_layout"/>

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

My include xml (secondary_layout.xml)

```<code><android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/logos"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@null"
    android:src="@drawable/logos"
    app:layout_constraintBottom_toTopOf="@+id/alliance"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginLeft="@dimen/multi_screen_medium_padding"
    android:layout_marginRight="@dimen/multi_screen_medium_padding"
    android:layout_marginTop="@dimen/multi_screen_medium_padding"
    android:layout_marginBottom="@dimen/multi_screen_medium_padding"/>

<ImageView
    android:id="@+id/alliance"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="@dimen/multi_screen_medium_padding"
    android:contentDescription="@null"
    android:src="@drawable/alliance"
    app:layout_constraintBottom_toBottomOf="@+id/main_layout"
    app:layout_constraintDimensionRatio="3:1"
    app:layout_constraintHorizontal_bias="0.50"
    app:layout_constraintLeft_toLeftOf="@+id/logos"
    app:layout_constraintRight_toRightOf="@+id/logos"
    app:layout_constraintTop_toBottomOf="@+id/logos"
    app:layout_constraintVertical_bias="0.50"/>
</android.support.constraint.ConstraintLayout>
</code>```

Thanks for suggestions.

Body:
I have a main layout in which I am adding constraint layout as include tag.
Here is my main layout.

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

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/text1"
        android:textAlignment="center"
        android:textColor="@color/app_theme_primary"
        android:textSize="@dimen/large_header_text_size" />

    <TextView
        android:id="@+id/version_number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/version_number"
        android:textAlignment="center"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size"/>

    <TextView
        android:id="@+id/develop_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/padding_10dp"
        android:gravity="center"
        android:text="@string/developed_text"
        android:textColor="@color/common_main_background"
        android:textStyle="bold" />

    <include layout="@layout/common_layout"/>

    <TextView
        android:id="@+id/trademarks"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="@string/trademarks"
        android:textAlignment="center"
        android:paddingTop="@dimen/multi_screen_small_padding"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size" />
    </LinearLayout>

My constraint layout which consists of Two imageViews as below

<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/logo1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:contentDescription="@null"
        android:paddingTop="@dimen/multi_screen_medium_padding"
        android:paddingStart="@dimen/multi_screen_medium_padding"
        android:paddingEnd="@dimen/multi_screen_medium_padding"
        android:src="@drawable/logo1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="8dp"
        android:layout_marginRight="16dp"/>

    <ImageView
        android:id="@+id/logo2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:contentDescription="@null"
        android:src="@drawable/logo2"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logo1"
        android:layout_marginTop="8dp"
        app:layout_constraintDimensionRatio="w,1:1"/>

</android.support.constraint.ConstraintLayout>

My requirement are

1.Constraint layout should be fitted properly in main layout but here I facing problem is last textview (id:trademarks) not showing on screen since constraint layout occupied the screen till bottom of the screen.

2. Second image (logo2) should adjust appropriately as per screen size (small screen small bigger screens some what bigger).

Please help me how to do it? Thanks in advance.

Body:
After several hours hardwork, myself got perfect answer for my question. Please Check below

My main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/app_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textColor="@color/theme_primary"
        android:textSize="@dimen/large_header_text_size"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/version_number"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/version_number"
        android:textAlignment="center"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/app_name"/>

    <TextView
        android:id="@+id/develop_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:paddingTop="@dimen/padding_10dp"
        android:text="@string/developed_by"
        android:textColor="@color/common_main_background"
        android:textStyle="bold"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/version_number"/>

    <include
        android:id="@+id/common_layout"
        layout="@layout/common_layout"
        android:layout_width="0dp"
        android:layout_height="324dp"
        android:layout_marginTop="@dimen/multi_screen_medium_padding"
        app:layout_constraintBottom_toTopOf="@+id/trademarks"
        app:layout_constraintDimensionRatio="1:0.90"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/develop_text"/>

    <TextView
        android:id="@+id/trademarks"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/multi_screen_medium_padding"
        android:text="@string/trademarks"
        android:textAlignment="center"
        android:textColor="@color/common_main_background"
        android:textSize="@dimen/secondary_text_size"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/common_layout"/>

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

My include xml (secondary_layout.xml)

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
    android:id="@+id/logos"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:contentDescription="@null"
    android:src="@drawable/logos"
    app:layout_constraintBottom_toTopOf="@+id/alliance"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginLeft="@dimen/multi_screen_medium_padding"
    android:layout_marginRight="@dimen/multi_screen_medium_padding"
    android:layout_marginTop="@dimen/multi_screen_medium_padding"
    android:layout_marginBottom="@dimen/multi_screen_medium_padding"/>

<ImageView
    android:id="@+id/alliance"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginRight="0dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="@dimen/multi_screen_medium_padding"
    android:contentDescription="@null"
    android:src="@drawable/alliance"
    app:layout_constraintBottom_toBottomOf="@+id/main_layout"
    app:layout_constraintDimensionRatio="3:1"
    app:layout_constraintHorizontal_bias="0.50"
    app:layout_constraintLeft_toLeftOf="@+id/logos"
    app:layout_constraintRight_toRightOf="@+id/logos"
    app:layout_constraintTop_toBottomOf="@+id/logos"
    app:layout_constraintVertical_bias="0.50"/>
</android.support.constraint.ConstraintLayout>

Thanks for suggestions.


问:
Resizing qt widgets when their children are hidden
How would I go about resizing the widget when the retry child is hidden so that it looks as in the first image? The main layout is a QVBoxLayout, the retry child is a widget with a QVBoxLayout as well.

I've tried the following:

update()

updateGeometry()

setGeometry(childrenRect())

layout()->activate()

on the main widget as soon as I've set the retry widget to hidden. Do I need to intercept some event to do this?

答:
My problem was a little different in that I had a top-level QWidget (instead of a QDialog or a QMainWindow) that had children within a layout.  When those children were resizing to larger, the QWidget would resize to accommodate, but not when they became SMALLER.  Much like above, the area just had empty space.  I finally found a solution:

The layout used in my QWidget had a property called setSizeConstraint().  This is normally set to "QLayout::SetDefaultConstraint", which simply affects the "minimumSize" of the QWidget that owns it.  Instead, I chose "QLayout::SetFixedSize" which made the layout adjust the fixed size of the owning QWidget, effectively making it SMALLER when it needed to be.


问:
Count entries of specific object property name within current index
How would I efficiently go about counting the .length of a specific object property within a current object index?

Would I need to iterate through each content.item index and then iterate through content.item.itemSettings.item.monsters and on the way do a "manual" countup?

In the below im trying to count a specific property for each
content.item where the property im trying to count is "monsters":

```<code>content.item.itemSettings.item.monsters
</code>```

The first (index) count [0] of content.item would be expected to be = 4

The second (index) count [1] of content.item would be expected to be = 3

var content = {
  item: [{
      mainId: 50,

      itemSettings: {
        item: [{
            level: 1,

            monsters: [{
                name: 'monster 1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 1,

            monsters: [{
                name: 'monster 3',

                item: [{
                  innerLabel: 'gray',
                  year: [{
                      yearVal: 2016,
                      yearStat: 50,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 55,
                    }
                  ]
                }]
              },
              {
                name: 'monster 4',

                item: [{
                  innerLabel: 'red',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 100,
                    }
                  ]
                }]
              },
            ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

    //NEW
    {
      mainId: 60,

      itemSettings: {
        item: [{
            level: 2,

            monsters: [{
                name: 'monster 2-1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2-2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 2,

            monsters: [{
              name: 'monster 2-3',

              item: [{
                innerLabel: 'gray',
                year: [{
                    yearVal: 2016,
                    yearStat: 50,
                  },
                  {
                    yearVal: 2012,
                    yearStat: 55,
                  }
                ]
              }]
            }, ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

  ]
}; //content
```

答:
If you need the length of each index separately, you can use the following code:

```<code>content.item.map(item =>
  item.itemSettings.item.reduce((count, itemInner) =>
    count + itemInner.monsters.length, 0
  )
);
</code>```

Output: [4, 3]

Body:
How would I efficiently go about counting the .length of a specific object property within a current object index?

Would I need to iterate through each content.item index and then iterate through content.item.itemSettings.item.monsters and on the way do a "manual" countup?

In the below im trying to count a specific property for each
content.item where the property im trying to count is "monsters":

content.item.itemSettings.item.monsters

The first (index) count [0] of content.item would be expected to be = 4

The second (index) count [1] of content.item would be expected to be = 3

var content = {
  item: [{
      mainId: 50,

      itemSettings: {
        item: [{
            level: 1,

            monsters: [{
                name: 'monster 1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 1,

            monsters: [{
                name: 'monster 3',

                item: [{
                  innerLabel: 'gray',
                  year: [{
                      yearVal: 2016,
                      yearStat: 50,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 55,
                    }
                  ]
                }]
              },
              {
                name: 'monster 4',

                item: [{
                  innerLabel: 'red',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 100,
                    }
                  ]
                }]
              },
            ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

    //NEW
    {
      mainId: 60,

      itemSettings: {
        item: [{
            level: 2,

            monsters: [{
                name: 'monster 2-1',

                item: [{
                  innerLabel: 'blue',
                  year: [{
                      yearVal: 2016,
                      yearStat: 70,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 30,
                    }
                  ]
                }]
              },
              {
                name: 'monster 2-2',

                item: [{
                  innerLabel: 'pink',
                  year: [{
                      yearVal: 2016,
                      yearStat: 20,
                    },
                    {
                      yearVal: 2012,
                      yearStat: 90,
                    }
                  ]
                }]
              },
            ]
          },
          {
            level: 2,

            monsters: [{
              name: 'monster 2-3',

              item: [{
                innerLabel: 'gray',
                year: [{
                    yearVal: 2016,
                    yearStat: 50,
                  },
                  {
                    yearVal: 2012,
                    yearStat: 55,
                  }
                ]
              }]
            }, ]
          },
        ] //mainId
      }, //itemSettings
    }, //content.item

  ]
}; //content

Body:
If you need the length of each index separately, you can use the following code:

content.item.map(item =>
  item.itemSettings.item.reduce((count, itemInner) =>
    count + itemInner.monsters.length, 0
  )
);

Output: [4, 3]


问:
Xamarin how to release GPS service
I have written an app that query the Gps coordinates once off. My problem is that sometimes the app does not release the GPS service. The GPS icon stays on the screen forever. What could be the possible cause ? Here is my code below :</p>

```<code>string latitude = string.Empty;
string longitude = string.Empty;
string Area = string.Empty;
Geocoder geoCoder = null;
IGeolocator locator = null;

try
{
    //get gps
    string myGps = string.Empty;
    locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 50;

    TimeSpan sp = new TimeSpan(10000);

    var position = await locator.GetPositionAsync(sp);

    latitude = position.Latitude.ToString();
    longitude = position.Longitude.ToString();

    geoCoder = new Geocoder(this.ApplicationContext);

    var addresses = geoCoder.GetFromLocation(position.Latitude, position.Longitude, 1);

   if (addresses != null)
                        Area = addresses[0].CountryName + ", " + addresses[0].Locality + ", " + addresses[0].SubLocality + ", " + addresses[0].FeatureName;

                    successful = true;
 }
 catch (Exception ex)
 {
 }
</code>```

答:
maybe you should try first if your GPS is enabled.

Try that:

```<code>        if (CrossGeolocator.Current.IsGeolocationEnabled)
            GeoLoc = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
</code>```

or even something like that :

```<code>        if (CrossGeolocator.IsSupported && CrossGeolocator.Current.IsGeolocationAvailable && CrossGeolocator.Current.IsGeolocationEnabled)
            GeoLoc = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));
</code>```

Title: Xamarin how to release GPS service

Body:
I have written an app that query the Gps coordinates once off. My problem is that sometimes the app does not release the GPS service. The GPS icon stays on the screen forever. What could be the possible cause ? Here is my code below :

string latitude = string.Empty;
string longitude = string.Empty;
string Area = string.Empty;
Geocoder geoCoder = null;
IGeolocator locator = null;

try
{
    //get gps
    string myGps = string.Empty;
    locator = CrossGeolocator.Current;
    locator.DesiredAccuracy = 50;

    TimeSpan sp = new TimeSpan(10000);

    var position = await locator.GetPositionAsync(sp);

    latitude = position.Latitude.ToString();
    longitude = position.Longitude.ToString();

    geoCoder = new Geocoder(this.ApplicationContext);

    var addresses = geoCoder.GetFromLocation(position.Latitude, position.Longitude, 1);

   if (addresses != null)
                        Area = addresses[0].CountryName + ", " + addresses[0].Locality + ", " + addresses[0].SubLocality + ", " + addresses[0].FeatureName;

                    successful = true;
 }
 catch (Exception ex)
 {
 }

Body:
maybe you should try first if your GPS is enabled.

Try that:

        if (CrossGeolocator.Current.IsGeolocationEnabled)
            GeoLoc = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));

or even something like that :

        if (CrossGeolocator.IsSupported && CrossGeolocator.Current.IsGeolocationAvailable && CrossGeolocator.Current.IsGeolocationEnabled)
            GeoLoc = await CrossGeolocator.Current.GetPositionAsync(TimeSpan.FromSeconds(10));


问:
Variables are not initialized in if statement
I was trying the following code out.

```<code>    int index, use, comp;
    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
    }
    for (index = 0; index < 3; index++)
    {
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
    }
    int sum = comp + use;
</code>```

At the line int sum = comp + use;, I am getting an error saying that variables comp and use are not initialized. How can I store the values I had gotten during the execution of the loop in these variables?

答:
The compiler is telling you that it is possible that comp and use will not have been given values by the time you reach the line int sum = comp + use;. This is clearly true (from the compiler's point of view): There is no way to be certain that these variables will have had values placed in them.

A simple way to solve this is to initialize them at the start:

```<code>int comp = 0;
int use = 0;
</code>```

But be sure first that this will not mess up the functionality you want.

Body:
I was trying the following code out.

    int index, use, comp;
    for (index = 0; index < 3; index++)
    {
        if (user1.equalsIgnoreCase(options[index]))
        {
            use = index;
        }
    }
    for (index = 0; index < 3; index++)
    {
        if (opt.equalsIgnoreCase(options[index]))
        {
            comp = add + index;
        }
    }
    int sum = comp + use;

At the line int sum = comp + use;, I am getting an error saying that variables comp and use are not initialized. How can I store the values I had gotten during the execution of the loop in these variables?

Body:
The compiler is telling you that it is possible that comp and use will not have been given values by the time you reach the line int sum = comp + use;. This is clearly true (from the compiler's point of view): There is no way to be certain that these variables will have had values placed in them.

A simple way to solve this is to initialize them at the start:

int comp = 0;
int use = 0;

But be sure first that this will not mess up the functionality you want.


问:
Using $filter with Microsoft Graph Excel APIs
With Microsoft Graph I can access rows from a table like this:

```<code>/v1.0/drives/..../workbook/worksheets/Sheet4/tables/2/rows
</code>```

The documentation states:

This method supports the OData Query Parameters to help customize the response.

I am able to use the $select query parameter:

```<code>/v1.0/drives/..../workbook/worksheets/Sheet4/tables/2/rows?$select=values.
</code>```

But how can I use $search or $filter query parameters? For example, I want to search the rows where column 'employeeName' contains the string "John".

答:
In order to filter data from Excel you should get a workbook session id first:

```<code>POST https://graph.microsoft.com/v1.0/drives/.../workbook/createSession

BODY => {persistChanges:false}
</code>```

You may change the value of persistChanges to true if you want to keep any changes you make to the worksheet. This will return an id which you will be using it as part of the headers when applying the filter:

```<code>POST https://graph.microsoft.com/v1.0/drives/.../workbook/worksheets('Sheet4')/tables(id='4')/columns('employeeName')/filter/apply

HEADER => workbook-session-id: session_Id

BODY => {  criteria: {  filterOn: "Custom",  criterion1: "=John", operator: "Or", criterion2: null }
</code>```

Finally you can retrieve the rows by using:

```<code>GET https://graph.microsoft.com/v1.0/drives/.../workbook/worksheets('Sheet4')/tables('4')/range/visibleView/rows?$select=values

HEADER => workbook-session-id: session_Id
</code>```

Here is some reference on how to setup the criteria

And a general reference about Excel and the Graph API

Body:
With Microsoft Graph I can access rows from a table like this:

/v1.0/drives/..../workbook/worksheets/Sheet4/tables/2/rows

The documentation states:

This method supports the OData Query Parameters to help customize the response.

I am able to use the $select query parameter:

/v1.0/drives/..../workbook/worksheets/Sheet4/tables/2/rows?$select=values.

But how can I use $search or $filter query parameters? For example, I want to search the rows where column 'employeeName' contains the string "John".

Body:
In order to filter data from Excel you should get a workbook session id first:

POST https://graph.microsoft.com/v1.0/drives/.../workbook/createSession

BODY => {persistChanges:false}

You may change the value of persistChanges to true if you want to keep any changes you make to the worksheet. This will return an id which you will be using it as part of the headers when applying the filter:

POST https://graph.microsoft.com/v1.0/drives/.../workbook/worksheets('Sheet4')/tables(id='4')/columns('employeeName')/filter/apply

HEADER => workbook-session-id: session_Id

BODY => {  criteria: {  filterOn: "Custom",  criterion1: "=John", operator: "Or", criterion2: null }

Finally you can retrieve the rows by using:

GET https://graph.microsoft.com/v1.0/drives/.../workbook/worksheets('Sheet4')/tables('4')/range/visibleView/rows?$select=values

HEADER => workbook-session-id: session_Id

Here is some reference on how to setup the criteria

And a general reference about Excel and the Graph API


问:
Is there a way to stop TypeScript from creating JavaScript with 'require'
In my TypeScript, I'm importing a module as follows:

```<code>import swal from "sweetalert2";
</code>```

When I compile the file to JavaScript, it outputs:

```<code>const sweetalert2_1 = require("sweetalert2");
</code>```

Then I get a browser message:

```<code>'require is not defined'
</code>```

Is there a way to get the JavaScript to compile without 'require'?

答:
You can change this using the compiler option --module to target ES6 or later:

```<code>tsc --module ES6
</code>```

You can also do this in your .tsconfig file

```<code>"module": "ES6",
</code>```

The result of this is that your import statement will transform from the TypeScript:

```<code>import { go } from './mod';
</code>```

Into the JavaScript:

```<code>import { go } from './mod';
</code>```

If you are using the browser native module loader, you may find that it expects the file extension:

```<code>import { go } from './mod.js';
</code>```

Body:
In my TypeScript, I'm importing a module as follows:

import swal from "sweetalert2";

When I compile the file to JavaScript, it outputs:

const sweetalert2_1 = require("sweetalert2");

Then I get a browser message:

'require is not defined'

Is there a way to get the JavaScript to compile without 'require'?

Body:
You can change this using the compiler option --module to target ES6 or later:

tsc --module ES6

You can also do this in your .tsconfig file

"module": "ES6",

The result of this is that your import statement will transform from the TypeScript:

import { go } from './mod';

Into the JavaScript:

import { go } from './mod';

If you are using the browser native module loader, you may find that it expects the file extension:

import { go } from './mod.js';


问:
How do we cross reference to multiple items in Xtext?
I have a grammar which looks like below:

```<code>Module: MOD mid=ModId ;

Stmt: CALL nam=ModName ';';

ModName: (idn1=[ModId|ID] | ('"' idn2=[ModId|ID] '"') | (idn3=ID idn4=ID));
</code>```

Basically, I have a statement where module name is mentioned. So when I try to call the module later, it should prompt me the module names defined (with or without quotes) and also allow me to enter a new variable name (which is not a module name) also.

How do I achieve this? I am able to achieve either referencing to the module name or defining a name, not both.

Example program:

```<code>Module add

Module subtract

Module divide

call add;    //referencing module name

call "subtract";  // referencing module name in quotes

call operation;   // without reference
</code>```

Regards,

Anitha

答:
Thanks Christian. I was making a silly mistake by not assigning ModId to name. Now the content assist works fine.

The grammar looks like below now:

```<code>Module: 'MOD' mid=ModuleName;
ModuleName: name = identifier;

Var: d=DataType v=VarName;
VarName:  name=identifier;

Stmt:  'Call' ((idn1=[Names|ID] 'Mod.')| (idn3=[Names|ID] idn4=ID '.'));

Names: id = ModuleName| id2 = VarName;
</code>```

I made changes in Scoping to merge lists to be able to provide both ModuleName and VarName for content assist. This works fine.

However once I enter the value, it throws error saying - "Couldn't resolve reference to Names"

What am i doing wrong here?

Body:
I have a grammar which looks like below:

Module: MOD mid=ModId ;

Stmt: CALL nam=ModName ';';

ModName: (idn1=[ModId|ID] | ('"' idn2=[ModId|ID] '"') | (idn3=ID idn4=ID));

Basically, I have a statement where module name is mentioned. So when I try to call the module later, it should prompt me the module names defined (with or without quotes) and also allow me to enter a new variable name (which is not a module name) also.

How do I achieve this? I am able to achieve either referencing to the module name or defining a name, not both.

Example program:

Module add

Module subtract

Module divide

call add;    //referencing module name

call "subtract";  // referencing module name in quotes

call operation;   // without reference

Regards,

Anitha

Body:
Thanks Christian. I was making a silly mistake by not assigning ModId to name. Now the content assist works fine.

The grammar looks like below now:

Module: 'MOD' mid=ModuleName;
ModuleName: name = identifier;

Var: d=DataType v=VarName;
VarName:  name=identifier;

Stmt:  'Call' ((idn1=[Names|ID] 'Mod.')| (idn3=[Names|ID] idn4=ID '.'));

Names: id = ModuleName| id2 = VarName;

I made changes in Scoping to merge lists to be able to provide both ModuleName and VarName for content assist. This works fine.

However once I enter the value, it throws error saying - "Couldn't resolve reference to Names"

What am i doing wrong here?


问:
JSF RichFaces componenents on Tomcat
I am trying to run simple Richfaces component on Tomcat 7.0.5. But client side, page will be blank and the components are not getting translated. Here is the code

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:a4j="http://richfaces.org/a4j"
    xmlns:rich="http://richfaces.org/rich">
    <rich:panel style="width:220px;">
        <f:facet name="header">
            <h:outputText value="Form built with inplaces"></h:outputText>
        </f:facet>
        <h:panelGrid columns="1">
            <rich:inplaceInput defaultLabel="click to enter your name" />
            <rich:inplaceSelect defaultLabel="click to choose your country" showControls="true">
                <f:selectItem itemLabel="USA" itemValue="0"/>
                <f:selectItem itemLabel="Canada" itemValue="0"/>
                <f:selectItem itemLabel="UK" itemValue="0"/>
            </rich:inplaceSelect>
        </h:panelGrid>
    </rich:panel>
</html>
</code>```

This translates to blank page and the html source code is:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich">
    <rich:panel style="width:220px;">
        <table>
            <tbody>
                <tr>
                    <td>
                        <rich:inplaceInput defaultLabel="click to enter your name"></rich:inplaceInput>
                        <rich:inplaceSelect defaultLabel="click to choose your country" showControls="true">
                    </td>
                </tr>
                <tr>
                    <td></td>
                </tr>
                <tr>
                    <td></td>
                </tr>
                <tr>
                    <td></td>
                </tr>
                <tr>
                    <td></rich:inplaceSelect></td>
                </tr>
            </tbody>
        </table>
    </rich:panel>
</html>
</code>```

I have richfaces-api-3.3.3.Final.jar and richfaces-impl-3.3.3.Final.jar in lib directory.

It asked commons-logging-1.1.1.jar and so on while running. I placed all required jar file in lib directory.

What do I need to run this on Tomcat?

答: How do you call the page? Make sure it's http://host/app/page.jsf (not .xhtml)</p>

Title: JSF RichFaces componenents on Tomcat

Body:
I am trying to run simple Richfaces component on Tomcat 7.0.5. But client side, page will be blank and the components are not getting translated. Here is the code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <rich:panel style="width:220px;">
        <f:facet name="header">
            <h:outputText value="Form built with inplaces"></h:outputText>
        </f:facet>
        <h:panelGrid columns="1">
            <rich:inplaceInput defaultLabel="click to enter your name" />
            <rich:inplaceSelect defaultLabel="click to choose your country" showControls="true">
                <f:selectItem itemLabel="USA" itemValue="0"/>
                <f:selectItem itemLabel="Canada" itemValue="0"/>
                <f:selectItem itemLabel="UK" itemValue="0"/>
            </rich:inplaceSelect>
        </h:panelGrid>
    </rich:panel>

This translates to blank page and the html source code is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <rich:panel style="width:220px;">

                        <rich:inplaceInput defaultLabel="click to enter your name"></rich:inplaceInput>
                        <rich:inplaceSelect defaultLabel="click to choose your country" showControls="true">

                    </rich:inplaceSelect>

    </rich:panel>

I have richfaces-api-3.3.3.Final.jar and richfaces-impl-3.3.3.Final.jar in lib directory.

It asked commons-logging-1.1.1.jar and so on while running. I placed all required jar file in lib directory.

What do I need to run this on Tomcat?


问:
lazily building up an enumerable with breaks in between
I have a collection of objects IEnumerable<object> obs.
I have another collection of objects IEnumerable<object> data.

For each ob in obs I need to find the first item in data that has the same value in a certain property as ob. For example I could be looking for the first item in data that has the same ToString() value as ob. When the first item where the property values match is found, I do something with the found data item and then I check the next ob in obs. If none is found, I throw an error.

Here is a naive approach:

```<code>foreach (object ob in obs)
{
    foreach (object dataOb in data)
        if (ob.ToString() == dataOb.ToString())
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}
</code>```

The disadvantage is that I calculate dataOb.ToString() every time, which is unnecessary.
I could cache it:

```<code>IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
foreach (object dataObj in data) // collect all ToString values in advance
    dataToDataStr.Add(dataObj, dataObj.ToString());

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}
</code>```

The disadvantage is that I calculate all ToString() values even though it might not be necessary. I might find all matching data objects in the first half of the data collection.

How can I build up the dataToDataStr dictionary (or any other enumerable data structure that lets me retrieve both the object and its only-once-calculated ToString value) lazily?

Here is code (mixed with pseudocode) of what I have in mind:

```<code>IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
object lastProcessedDataOb = null;

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }

    foreach (object dataOb in data STARTING AFTER lastProcessedDataOb)
    // if lastProcessedDataOb == null, start with the first entry of data
    {
        dataToDataStr.Add(dataOb, dataOb.ToString();
        lastProcessedDataOb = dataOb;

        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}
</code>```

I know it is easy if data was a LinkedList or any collection with indexed access (then I could store a linked list node or an index as lastProcessedDataOb), but it isn't - it is an IEnumerable. Maybe yield return can be used here?

答:
If your collections are really large and you really don't want to evaluate ToString for each item of data, you could use the following approach:

Create cache of already calculated items

If certain item is found i cache - that's great, we have a match.

Otherwise - continue populating cache by iterating over data collection until we find a match. This can be efficiently be done with manually controlling **Enumerator** of data collection (instead of using foreach).

```<code>IEnumerable<object> obs;
IEnumerable<object> data;
Dictionary<string, object> dataCache = new Dictionary<string, object>();

var dataIterator = data.GetEnumerator();
foreach (var ob in obs)
{
    var obText = ob.ToString();
    object matchingDataItem = null;
    if (!dataCache.TryGetValue(obText, out matchingDataItem))
    {
        while (dataIterator.MoveNext())
        {
            var currentData = dataIterator.Current;
            var currentDataText = currentData.ToString();
            if (!dataCache.ContainsKey(currentDataText)) // Handle the case when data collection contains duplicates
            {
                dataCache.Add(currentDataText, currentData);
                if (currentDataText == obText)
                {
                    matchingDataItem = currentData;
                    break;
                }
            }
        }
    }
    if (matchingDataItem != null)
    {
        Console.WriteLine("Matching item found for " + obText);
    }
    else
    {
        throw new Exception("No matching data found.");
    }
}
</code>```

This way you can guarantee to iterate over data collection only to the point when all obs items are found and you won't evaluate ToString for each item more then once.

PS: I hope "ToString" is just for example and you have some complex calculations there, which is worth such complexities...

Body:
I have a collection of objects IEnumerable<object> obs.
I have another collection of objects IEnumerable<object> data.

For each ob in obs I need to find the first item in data that has the same value in a certain property as ob. For example I could be looking for the first item in data that has the same ToString() value as ob. When the first item where the property values match is found, I do something with the found data item and then I check the next ob in obs. If none is found, I throw an error.

Here is a naive approach:

foreach (object ob in obs)
{
    foreach (object dataOb in data)
        if (ob.ToString() == dataOb.ToString())
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}

The disadvantage is that I calculate dataOb.ToString() every time, which is unnecessary.
I could cache it:

IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
foreach (object dataObj in data) // collect all ToString values in advance
    dataToDataStr.Add(dataObj, dataObj.ToString());

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}

The disadvantage is that I calculate all ToString() values even though it might not be necessary. I might find all matching data objects in the first half of the data collection.

How can I build up the dataToDataStr dictionary (or any other enumerable data structure that lets me retrieve both the object and its only-once-calculated ToString value) lazily?

Here is code (mixed with pseudocode) of what I have in mind:

IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
object lastProcessedDataOb = null;

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }

    foreach (object dataOb in data STARTING AFTER lastProcessedDataOb)
    // if lastProcessedDataOb == null, start with the first entry of data
    {
        dataToDataStr.Add(dataOb, dataOb.ToString();
        lastProcessedDataOb = dataOb;

        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}

I know it is easy if data was a LinkedList or any collection with indexed access (then I could store a linked list node or an index as lastProcessedDataOb), but it isn't - it is an IEnumerable. Maybe yield return can be used here?

Body:
If your collections are really large and you really don't want to evaluate ToString for each item of data, you could use the following approach:

Create cache of already calculated items

If certain item is found i cache - that's great, we have a match.

Otherwise - continue populating cache by iterating over data collection until we find a match. This can be efficiently be done with manually controlling **Enumerator** of data collection (instead of using foreach).

IEnumerable<object> obs;
IEnumerable<object> data;
Dictionary<string, object> dataCache = new Dictionary<string, object>();

var dataIterator = data.GetEnumerator();
foreach (var ob in obs)
{
    var obText = ob.ToString();
    object matchingDataItem = null;
    if (!dataCache.TryGetValue(obText, out matchingDataItem))
    {
        while (dataIterator.MoveNext())
        {
            var currentData = dataIterator.Current;
            var currentDataText = currentData.ToString();
            if (!dataCache.ContainsKey(currentDataText)) // Handle the case when data collection contains duplicates
            {
                dataCache.Add(currentDataText, currentData);
                if (currentDataText == obText)
                {
                    matchingDataItem = currentData;
                    break;
                }
            }
        }
    }
    if (matchingDataItem != null)
    {
        Console.WriteLine("Matching item found for " + obText);
    }
    else
    {
        throw new Exception("No matching data found.");
    }
}

This way you can guarantee to iterate over data collection only to the point when all obs items are found and you won't evaluate ToString for each item more then once.

PS: I hope "ToString" is just for example and you have some complex calculations there, which is worth such complexities...


答:
I really don't know what is the best practice for this, but you could add hidden element which would have fixed position, no opacity and z-index just below the dropdown menus.

That element could have click handler to remove your active classes.

Title: Close menus when clicking outside

Body:
I am working on a navbar for a website. It contains 3 dropdowns (and a bunch of other stuff I removed to keep the code concise). I want to be able to close the dropdowns by clicking outside of them. I have found many solutions which dealt with this (including the ones on this site), but all of them only accounted for having one such dropdown and I was unable to adapt them to my situation. What I want to achieve is:

If you click one of the buttons, it gets a is-active class (which makes its dropdown visible via a sibling selector in CSS) and removes it from all other buttons in the menu.

If you click on an open dropdown window, nothing happens.

If you click outside of any dropdown buttons and windows, the is-active class gets removed from all the nav buttons that have it.

No matter which recommended solution I tried, one or more of these stopped working as expected. Could anyone help me figure it out?

$('[data-toggle]').click(function() {
    var params = $(this).data('toggle');
    $(params['target']).toggleClass(params['class']);
})

            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"books\"","class":"is-active"}' data-toggle-target="books">Knihy</button>

                // Dropdown contents

            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"info\"","class":"is-active"}' data-toggle-target="info">Informácie</button>

                // Dropdown contents

            <button class="main-nav__button" data-toggle='{"target":"[data-toggle-target=\"profile\"","class":"is-active"}' data-toggle-target="profile">

            </button>

                // Dropdown contents

This code just toggles the dropdowns. My attempts at autoclosing functionality were in separate functions, but I no longer have them, since none of them worked - sorry.

A bonus question: Is there a way of putting the self keyword into an HTML data-attribute?