text:
Q: ASP.Net MVC vs. HTML + KnockoutJS + WebAPI I'm wondering why not just have static HTML files in an ASP.Net MVC 4 Web Project that use jQuery+jQuery Templates+KnockoutJS combination consuming REST based (ASP.Net MVC 4 WEB API hosted on Azure & secured using ACS).  The Web API can use Entity Framework and return JSON serialized objects that can be retrieved using $.ajax() and bound using KnockoutJS.
What is it that ASP.Net MVC (for the Web pages) provides that adds value to this architecture?
On top of my head, I can think of:

*

*Multi device support (device detection and template replacement)

*Server-side validations of submitted data (not sure as I can also put the validations on WEB API?)

*I can still rewrite my URLs even if I'm using static html files (since I'm using ASP.Net MVC anyway).

Can someone help me understand this better?  Thanks in advance.

A: Great question. I'm certainly finding that my MVC / Razor code is becoming less and less as I progress with my Knockout project, but I think I'll always have some aspects of the views which I want to be determined server-side.
Fundamental contextual stuff like whether to render a logged in / logged out panel in a layout page, role related decisions as to what should be accessible, etc. I guess if you were careful enough with your security and implement sufficient guard code on the server when someone actually tries to do something then you could achieve most of that in Knockout, but you'd probably end up with a huge amount of bloat, catering for every possible part of the view.
It probably depends on your application but I think for most web apps there's a fairly common sense division between what should be determined at server render time and what should be done on the client.
If nothing else, you may want links etc in your views to be indexed by search engines. If you pass down, say, your "latest 10 products" in JSON and render them with hyperlinks in a Knockout template, you'd lose out on that.

A: It is really a question of using the right tool for the job.
From what I can tell after doing development with knockout, it's real power comes from  observables and the real time DOM updates.  This makes a rich interface in client side applications quicker to create, and easier to manage.  However, it is still more time consuming and difficult to implement than working with straight Razor pages.  So Knockout JS is an advantage for certain applications where lots of data driven UI updates need to happen "ajaxically", but will be overkill for others.

A: If a client didn't have Javascript enabled in this scenario your site would be useless, and you would have no way to provide them a suitable alternative.
Using the MVC Framework and Razor syntax you could still build dynamically generated, data-driven content without the use of jQuery or AJAX.  MVC will provide you the clean separation of concerns between your Model and your View regardless of whether or not you have Javascript enabled.

A: Security is probably the number 1 advantage I see. You still have the structure ASP.NET behind it. Yes its true, in your views, you can certainly use razor syntax and have your view model rendered with Knockout, and JSON.NET makes data-binding easier than ever. Ultimately in the future, maybe MVC won't be part of the equation in the future? (check out Meteor js too, its wicked cool, and that type of dynamic model binding is just not possible with anything else other than javascript atm.)
Also if you want to see it in action, I found a good Codeproject with MVC and knockout. http://www.codeproject.com/Articles/424642/Customer-KnockoutJS-and-MVC-demo-using-JSON

A: Here, read this. A quote from it:

It's no longer good enough to build web apps around full page loads
  and then "progressively enhance" them to behave more dynamically.
  Building apps which are fast, responsive and modern require you to
  completely rethink your approach.

As to your question, what does MVC offer that adds value to an MVVM architecture? Catering custom content to different devices can be an advantage, but you can do this to a degree with CSS media queries too. The decision comes down to how many bytes you want to send from the server to the device.
You can do server-side validations without using MVC or WebAPI as well, and you don't need to use a ModelBinder or ModelState.IsValid to do it. Look into something like FluentValidation.NET, which allows you to do highly complex input validations on the server, even one layer below your Web/HTTP layer. Of course you would also want to validate client-side with something like jQuery validate.
I agree with other answers here that doing some security-level stuff at the server (controller action or razor) level is a little easier and a little more "trustworthy". But no one else here as mentioned the testability of MVVM. It's very easy to write unit tests around controller actions or other server-side code. That's not to say you can't unit/integration/UAT test MVVM apps, just that it requires more effort IMO.


text:
Q: jqGrid cascading drop down change event does not fire With Oleg and many websites help I have been working on getting cascading data bound drop downs functioning in jqGrid
I have three drop downs: Customer > Project > Task. Changing Customer should reload Project with that Customers Projects. Changing Projects should reload Tasks with that Projects Tasks.
I have actually got Project to reload with that Customers tasks by creating a change event handler in Customer which in turn calls getJson against a URL and then replaces the contents of the Project drop down with the new options. It works great.
I then applied this same logic to the Project drop down, but the Project event does not appear to fire. I have observed the following when changing the Project drop down:

*

*The Task drop down does not change

*The Task Json controller event is not called (it is meant to be called by getJSON in the Project change event)

*In Firebug, in the Network monitor, the call and response to the Task Json controller event does not appear.

*In Firebug it does not hit a breakpoint that I set in the Project change event handler

The Customer event handler however works perfectly, and performs all of the above 4 points as expected when I change the Customer.
I am fairly certain it is not firing the change event against the Project drop down.
If I run the web page and edit and change the Project drop down value as my very first action, it does not fire the project event handler, so I don't think it is the Customer event resetting the Project event handler.
So, does anyone know why my Customer change event is called but my Project one is not?
Is there a way I can inspect the DOM or something and see if my event has been attached at runtime? is that the way it works?
I am using jqGrid 4.4.1
My jqGrid is setup this way:

*

*Uses inline editing

*click to select dblclick to edit

*A datepicker is attached the date column

*Upon edit I get the select db key value out of hidden fields but I'm hoping I can remove that.

*I have three selects next to each other

Here is the my jqGrid definition
$(document).ready(
    function () {
        // This is executed as soon as the DOM is loaded and before the page contents are loaded
        var lastsel;
        // $ is short for JQuery which is in turn a super overloaded function that does lots of things.
        // # means select an element by its ID name, i.e. below we have <table id="ts"
        // .jqGrid means attach a jqGrid 'thing' to all elements that have ts as their element name (there's only one)
        // jqGrid is a thing defined in the jqGrid javascript file
        $("#ts").jqGrid({
            //=============
            // Grid Setup
            url: 'Timesheet/GridData/',
            datatype: 'json',
            mtype: 'GET',
            pager: $('#pager'),
            rowNum: 30,
            rowList: [10, 20, 30, 40, 80],
            viewrecords: true,
            caption: 'Timesheet',
            height: 450,
            // Column definition
            colNames: ['hCustomer_ID', 'hProject_ID', 'hTask_ID', 'Date', 'Customer', 'Project', 'Task', 'Description', 'Hours', '$'],
            colModel: [
              { name: 'hCustomer_ID', index: 'hCustomer_ID', editable: false, hidden: true },
              { name: 'hProject_ID', index: 'hProject_ID', editable: false, hidden: true },
              { name: 'hTask_ID', index: 'hTask_ID', editable: false, hidden: true },
              { name: 'tsdate', index: 'tsdate', width: 80, editable: true, datefmt: 'yyyy-mm-dd' },
            // Defintion for customer column
              {name: 'Customer', index: 'Customer', width: 250, align: 'left', editable: true, edittype: "select",
              editoptions: {
                  // Default URL used to populate drop down when the column goes into edit mode
                  dataUrl: 'Timesheet/CustomerList',
                  dataEvents: [
                      {
                          // this is the change handler. This is called when the customer is changed
                          type: 'change',
                          fn: function (e) {
                              // get a reference to the project and task drop downs on this same row
                              var eProject = '#' + $(this).attr("id").replace("_Customer", "_Project");
                              var eTask = '#' + $(this).attr("id").replace("_Customer", "_Task");
                              // Call getJSON to get data from a URL and process it with a callback function
                              $.getJSON(
                              // the URL to call
                                'Timesheet/ProjectListJSON',
                              // the parameter(s) to pass to the URL
                                {Customer_ID: this.value },
                              // The callback function. The results of the JSON call are passed into jData
                                function (jData) {
                                    var selectHtml = ""
                                    // Repopulate the project drop down with the results of the JSON call
                                    $.each(
                                        jData,
                                        function (jdIndex, jdData) {
                                            selectHtml = selectHtml + "<option value='" + jdData.Value + "'>" + jdData.Text + "</option>";
                                        });
                                    // dont use innerHTML as it is not supported properly by IE
                                    // insted use jQuery html to change the select list options
                                    $(eProject).html(selectHtml);
                                    // blank out tasks
                                    $(eTask).html("");
                                } // END getJSON callback function definition
                              ); // END getJSON function call
                          } // END change event definition
                      }] // END dataEvents definition
              } // END editoptions list
          }, // END Customer jqGrid field definition
            // Definition for Project drop down
          {name: 'Project', index: 'Project', width: 250, align: 'left', editable: true, edittype: "select",
          editoptions: {
              dataUrl: 'Timesheet/ProjectList',
              dataEvents: [
                      {
                          type: 'change',
                          fn: function (e) {
                              var eTask = '#' + $(this).attr("id").replace("_Project", "_Task");
                              $.getJSON(
                                'Timesheet/TaskListJSON',
                                { CustomerProject_ID: this.value },
                                function (jData) {
                                    var selectHtml = "";
                                    $.each(
                                        jData,
                                        function (jdIndex, jdData) {
                                            selectHtml = selectHtml + "<option value='" + jdData.Value + "'>" + jdData.Text + "</option>";
                                        });
                                        $(eTask).html(selectHtml);
                                } // END getJSON callback function definition
                              ); // END getJSON function call
                          } // END change event handler definition
                      }] // END dataevents definition
          } // END editoptions list
      }, // END Project jqGrid field definition
              {name: 'Task', index: 'Task', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/TaskList'} },
              { name: 'Desc', index: 'Desc', width: 300, align: 'left', editable: true },
              { name: 'Hours', index: 'Hours', width: 50, align: 'left', editable: true },
              { name: 'Charge', index: 'Charge', edittype: 'checkbox', width: 18, align: 'center', editoptions: { value: "0:1" }, formatter: "checkbox", formatoptions: { disabled: false }, editable: true }
            ],
            //=============
            // Grid Events
            // when selecting, undo anything else
            onSelectRow: function (rowid, iRow, iCol, e) {
                if (rowid && rowid !== lastsel) {
                    // $(this).jqGrid('restoreRow', lastsel);
                    lastsel = rowid;
                }
            },
            // double click to edit
            ondblClickRow: function (rowid, iRow, iCol, e) {
                // browser independent stuff
                if (!e) e = window.event;
                var element = e.target || e.srcElement

                // When editing, change the drop down datasources to filter on the current parent
                $(this).jqGrid('setColProp', 'Project', { editoptions: { dataUrl: 'Timesheet/ProjectList?Customer_ID=' + $(this).jqGrid('getCell', rowid, 'hCustomer_ID')} });
                $(this).jqGrid('setColProp', 'Task', { editoptions: { dataUrl: 'Timesheet/TaskList?CustomerProject_ID=' + $(this).jqGrid('getCell', rowid, 'hProject_ID')} });

                // Go into edit mode (automatically moves focus to first field)
                // Use setTimout to apply the focus and datepicker after the first field gets the focus
                $(this).jqGrid(
                    'editRow',
                    rowid,
                    {
                        keys: true,
                        oneditfunc: function (rowId) {
                            setTimeout(function () {
                                $("input, select", element).focus();
                                $("#" + rowId + "_tsdate").datepicker({ dateFormat: 'yy-mm-dd' });
                            }, 50);
                        }
                    }
                );

            },  // end ondblClickRow event handler
            postData:
                {
                    startDate: function () { return $('#startDate').val(); }
                }
        }); // END jQuery("#ts").jqGrid

        $("#ts").jqGrid('navGrid', '#pager', { view: false, edit: false, add: false, del: false, search: false });
        $("#ts").jqGrid('inlineNav', "#pager");

    });                                       // END jQuery(document).ready(function () {

FIXED CODE HERE
I moved the change event handler definition out of the column definition and into the dblclick event handler. It's still not perfect. I'm sure there is some overhead in attaching the event handler every time, and when Customer is changed, it updates and selects the first Project but clears the Tasks.
$(document).ready(
    function () {
        // This is executed as soon as the DOM is loaded and before the page contents are loaded
        var lastsel;
        // $ is short for JQuery which is in turn a super overloaded function that does lots of things.
        // # means select an element by its ID name, i.e. below we have <table id="ts"
        // .jqGrid means attach a jqGrid 'thing' to all elements that have ts as their element name (there's only one)
        // jqGrid is a thing defined in the jqGrid javascript file
        $("#ts").jqGrid({
            //=============
            // Grid Setup
            url: 'Timesheet/GridData/',
            datatype: 'json',
            mtype: 'GET',
            pager: $('#pager'),
            rowNum: 30,
            rowList: [10, 20, 30, 40, 80],
            viewrecords: true,
            caption: 'Timesheet',
            height: 450,
            // Column definition
            colNames: ['hCustomer_ID', 'hProject_ID', 'hTask_ID', 'Date', 'Customer', 'Project', 'Task', 'Description', 'Hours', '$'],
            colModel: [
              { name: 'hCustomer_ID', index: 'hCustomer_ID', editable: false, hidden: true },
              { name: 'hProject_ID', index: 'hProject_ID', editable: false, hidden: true },
              { name: 'hTask_ID', index: 'hTask_ID', editable: false, hidden: true },
              { name: 'tsdate', index: 'tsdate', width: 80, editable: true, datefmt: 'yyyy-mm-dd' },
            // Defintion for customer column
              {name: 'Customer', index: 'Customer', width: 250, align: 'left', editable: true, edittype: "select",
              editoptions: {
                  // Default URL used to populate drop down when the column goes into edit mode
                  dataUrl: 'Timesheet/CustomerList',
                  dataEvents: [
                      {
                          // this is the change handler. This is called when the customer is changed
                          type: 'change',
                          fn: function (e) {
                              // get a reference to the project and task drop downs on this same row
                              var eProject = '#' + $(this).attr("id").replace("_Customer", "_Project");
                              var eTask = '#' + $(this).attr("id").replace("_Customer", "_Task");
                              // Call getJSON to get data from a URL and process it with a callback function
                              $.getJSON(
                              // the URL to call
                                'Timesheet/ProjectListJSON',
                              // the parameter(s) to pass to the URL
                                {Customer_ID: this.value },
                              // The callback function. The results of the JSON call are passed into jData
                                function (jData) {
                                    var selectHtml = ""
                                    // Repopulate the project drop down with the results of the JSON call
                                    $.each(
                                        jData,
                                        function (jdIndex, jdData) {
                                            selectHtml = selectHtml + "<option value='" + jdData.Value + "'>" + jdData.Text + "</option>";
                                        });
                                    // dont use innerHTML as it is not supported properly by IE
                                    // insted use jQuery html to change the select list options
                                    $(eProject).html(selectHtml);
                                    // clear task list
                                    $(eTask).html("");
                                } // END getJSON callback function definition
                              ); // END getJSON function call
                          } // END change event definition
                      }] // END dataEvents definition
              } // END editoptions list
          }, // END Customer jqGrid field definition
            // Definition for Project drop down
              {name: 'Project', index: 'Project', width: 250, align: 'left', editable: true,
              edittype: "select", editoptions: { dataUrl: 'Timesheet/ProjectList'}
          }, // END Project jqGrid field definition
              {name: 'Task', index: 'Task', width: 250, align: 'left', editable: true, edittype: "select", editoptions: { dataUrl: 'Timesheet/TaskList'} },
              { name: 'Desc', index: 'Desc', width: 300, align: 'left', editable: true },
              { name: 'Hours', index: 'Hours', width: 50, align: 'left', editable: true },
              { name: 'Charge', index: 'Charge', edittype: 'checkbox', width: 18, align: 'center', editoptions: { value: "0:1" }, formatter: "checkbox", formatoptions: { disabled: false }, editable: true }
            ],
            //=============
            // Grid Events
            // when selecting, undo anything else
            onSelectRow: function (rowid, iRow, iCol, e) {
                if (rowid && rowid !== lastsel) {
                    // $(this).jqGrid('restoreRow', lastsel);
                    lastsel = rowid;
                }
            },
            // double click to edit
            ondblClickRow: function (rowid, iRow, iCol, e) {
                // browser independent stuff
                if (!e) e = window.event;
                var element = e.target || e.srcElement

                // When editing, change the drop down datasources to filter on the current parent
                // By default tasks are limited to the current project
                $(this).jqGrid('setColProp', 'Task', { editoptions: { dataUrl: 'Timesheet/TaskList?CustomerProject_ID=' + $(this).jqGrid('getCell', rowid, 'hProject_ID')} });

                // By default projects are limited to the current Customer (dataUrl)
                // Also attach event handler to autopopulate tasks (dataEvents)
                $(this).jqGrid('setColProp', 'Project', {
                    //                    editoptions: { dataUrl: 'Timesheet/ProjectList?Customer_ID=' + $(this).jqGrid('getCell', rowid, 'hCustomer_ID')} });
                    editoptions: {
                        dataUrl: 'Timesheet/ProjectList?Customer_ID=' + $(this).jqGrid('getCell', rowid, 'hCustomer_ID'),
                        dataEvents: [
                              {
                                  type: 'change',
                                  fn: function (e) {
                                      var eTask = '#' + $(this).attr("id").replace("_Project", "_Task");
                                      $.getJSON(
                                        'Timesheet/TaskListJSON',
                                        { CustomerProject_ID: this.value },
                                        function (jData) {
                                            var selectHtml = "";
                                            $.each(
                                                jData,
                                                function (jdIndex, jdData) {
                                                    selectHtml = selectHtml + "<option value='" + jdData.Value + "'>" + jdData.Text + "</option>";
                                                });
                                            $(eTask).html(selectHtml);
                                        } // END getJSON callback function definition
                                      ); // END getJSON function call
                                  } // END change event handler definition
                              }] // END dataevents definition
                    } // END editoptions list
                } // END data to be applied to setColProp
                ); // END jqGrid setColProp

                // Go into edit mode (automatically moves focus to first field)
                // Use setTimout to apply the focus and datepicker after the first field gets the focus
                $(this).jqGrid(
                    'editRow',
                    rowid,
                    {
                        keys: true,
                        oneditfunc: function (rowId) {
                            setTimeout(function () {
                                $("input, select", element).focus();
                                $("#" + rowId + "_tsdate").datepicker({ dateFormat: 'yy-mm-dd' });
                            }, 50);
                        }
                    }
                );

            },  // end ondblClickRow event handler
            postData:
                {
                    startDate: function () { return $('#startDate').val(); }
                }
        }); // END jQuery("#ts").jqGrid

        $("#ts").jqGrid('navGrid', '#pager', { view: false, edit: false, add: false, del: false, search: false });
        $("#ts").jqGrid('inlineNav', "#pager");

    });                                         // END jQuery(document).ready(function () {

A: I suppose that the reason of the problem which you have is the usage of jQuery.empty (see the lines eTask.empty(); and eProject.empty();). If you examine the description of jQuery.empty you will find the following:

To avoid memory leaks, jQuery removes other constructs such as data
  and event handlers from the child elements before removing the
  elements themselves.
If you want to remove elements without destroying their data or event
  handlers (so they can be re-added later), use .detach() instead.

It seems to me that in your case can can just construct the string which is concatenation of all <option> elements. Then you can use jQuery.html to replace all old options to the new one. You can not only solve your main problem, but have some performance advantage. The problem which you should understand, that if you change some element on the page web browser have to recalculate position or style of all existing elements on the page. So if you call jQuery.append in the loop then every call will follow at least to reflow which is expansive. So you should better write your program so that the number of changes on the page will be reduced. If you construct the innerHTML of the <select> elements first as HTML string and use one call of jQuery.html (or set just innerHTML property of the DOM element) you will have performance improvement.
Another problem which I see in your program is initializing of the selects from 'Project' and 'Task'. If the user start editing of the row the select elements will be filled with dataUrl: 'Timesheet/TaskList' and dataUrl: 'Timesheet/ProjectList'. So you will have all Project and Tasks and not only the Projects of the 'Customer' and the tasks based on the 'Customer' and 'Project' values. I think you will have to set row dependent initial values of dataUrl before the editing will be started. In case of form editing you could do this inside of onInitializeForm callback for example. If you use inline editing you should do the same before calling of editRow.
I recommend you to examine carefully the code of the demo from the answer. It uses no dataUrl but it change value property multiple times. Changing of value property will corresponds in your case the setting of dataUrl.

A: OK, the issue was that in the ondblClickRow event handler I was setting the editoptions / dataUrl property. As I was not also specifying the editoptions / dataEvents property at this point it was basically overwriting the static event handler with nothing.
in the ondblClickRow event handler I was only overwriting Project and Tasks drop down, which explains why the Project handler was being removed and not the Customer one.
Apologies to Oleg: I did not post the full code at the start, so I did not include the double click event.
Anyway Oleg if you can suggest how I can preserve the event handler I can award you the answer. Otherwise I will award this as the answer, even though your help has been invaluable. I'm guessing I might need to move the event handler definition down to the dblclick event handler rather than in the column definition?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get content from other database table based on an ID and rewrite URL I am currently using WordPress with SEO friendly permalinks.
One page of my website is a special one though, let's call it http://example.org/locales.
It is using a custom page template that loads values from a database table called "locales" and echoes the content to a html table.
Database columns:
id, location, address, type, guid
Example content:
3, Yale, Burberry street 21, Apartment, 40VIEOUKK2VA07F2
I have currently configured my PHP code in the custom page template so that the location column contains a link to the guid for each item like this:
echo "" . $row['address'] . "	";

This gives me a link that looks like this:
http://example.org/locales/?guid=40VIEOUKK2VA07F2

Now I have two questions:

*

*How do I proceed to actually load the details from a locale with a specific guid if they are stored in a different database table?

*How do I make an URL rewrite for /?guid=40VIEOUKK2VA07F2 so that it becomes something like http://example.org/locales/burberry-street-21
?

A: *

*Just because it is under wordpress doesn't make this special in any way, just use any php sample code that connects and retrieves data from a DB.

*The way you describe things it is impossible. If the DB is outside of WordPress how can wordress know that burberry-street-21 should be converted to 40VIEOUKK2VA07F2 before accessing the external DB?


text:
Q: Laravel Eloquent: keeping all interactions with a model in sync in two different databases I am working on a standard Laravel project (with a single MySQL database).
Now I need to keep in sync only one of my tables with another remote database. Thus, every change: creation, update, deletion, etc. in that specific table should be propagated / reproduced to the remote one in real time.
I have Googled before asking, but I haven't found a smart way to do it in Laravel apart from the obvious method which implies making every DB transaction to that model / table on both database connections.
By the way, I have seen the connection protected property of Eloquent ORM which sets a default DB connection for a specific model, but I am looking for something like having an array of values in that connection property.
No luck so far.
Any thoughts? Thanks in advance.

A: If you are making all queries on eloquent models, then you could utilise eloquent events.
Inside your event listener/observer, you could clone the model and change the connection on the cloned model so that you can execute the query on the second database.


text:
Q: retrieve data from database and insert those values to another table in database c# I'm getting error in connection open like "The connection is already opened". It is telling to close the opened connection of while loop(reading data from table). But any way the data's have to inserted to data base while reading. How to solve?
private bool iscompanyExist(string comname)
{
    string query = "select * from Ageingrpt where Companyname='" + comname + "' group by Companyname having sum(current)>0 or sum('a1-30')>0 or sum('a31-60')>0 or sum('a61-90')>0 or sum('a90g')>0 ;";
    MySqlCommand cmd = new MySqlCommand(query, cnn);
    MySqlDataReader reader1;
    cnn.Open();
    reader1 = cmd.ExecuteReader();
    if (reader1.HasRows)
    {
        cnn.Close();
        return true;
    }
    else
    {
        cnn.Close();
        return false;
    }
}

private void Ageingcalc()
{
    string duedate = null;
    string compname = null, outstanding = null;
    //90<
    string query = "select c.address1,sum(p.OutstandingAmt) from invoice i,payment p,customer c where p.invoiceNo=i.invoiceNo and i.cid=c.cid and p.OutstandingAmt>0 and i.dueDate<'" + DateTime.Now + "'   group by c.address1 ;";
    MySqlCommand cmd = new MySqlCommand(query, cnn);
    MySqlDataReader reader;
    cnn.Open(); //open1
    reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        compname = reader[0].ToString();
        outstanding = reader[1].ToString();
        if (iscompanyExist(compname) == true)
        {
            cnn.Open();
            query = "update Ageingrpt set a90g='" + outstanding + "';";
            cmd = new MySqlCommand(query, cnn);
            MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
            cnn.Close();
        }
        else
        {
            cnn.Open();
            query = "insert into Ageingrpt  values('" + compname + "',0,0,0,0,'" + outstanding + "',0); ";
            cmd = new MySqlCommand(query, cnn);
            cmd.ExecuteReader(); // query will be executed and data saved to the db
            cnn.Close();
        }
    }

    cnn.Close();
}

A:     private void Ageingcalc()
            {
                string duedate = null;
                string compname = null, outstanding = null;

                //90<
                string query = "select c.address1,sum(p.OutstandingAmt) from invoice i,payment p,customer c where p.invoiceNo=i.invoiceNo and i.cid=c.cid and p.OutstandingAmt>0 and i.dueDate<'" + DateTime.Now + "'   group by c.address1 ;";
                MySqlCommand cmd = new MySqlCommand(query, cnn);
                MySqlDataReader reader;
                cnn.Open();         //open1
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    compname = reader[0].ToString();
                    outstanding = reader[1].ToString();
                    if (iscompanyExist(compname) == true)
                    {
                        query = "update Ageingrpt set a90g='" + outstanding + "';";
                        cmd = new MySqlCommand(query, cnn);
                        MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }
                    else
                    {
                        query = "insert into Ageingrpt  values('" + compname + "',0,0,0,0,'" + outstanding + "',0); ";
                        cmd = new MySqlCommand(query, cnn);
                        cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }

                }
                cnn.Close();
            }

once connection is open and need to close it..we should not open again..

A: This is worked for me.I have used DataTable to store the retrieved data.
 private void Ageingcalc()
            {
                string duedate = null;
                string compname = null, outstanding = null;

                //90<
                string query = "select c.address1,sum(p.OutstandingAmt) as outstanding from invoice i,payment p,customer c where p.invoiceNo=i.invoiceNo and i.cid=c.cid and p.OutstandingAmt>0 and i.dueDate<'" + DateTime.Now + "'   group by c.address1 ;";
                MySqlCommand cmd = new MySqlCommand(query, cnn);
                MySqlDataReader reader;
                cnn.Open();
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cnn.Close();

                foreach (DataRow row in dt.Rows)
                {

                    if (iscompanyExist(row["address1"].ToString()) == true)
                    {
                        cnn.Open();
                        MessageBox.Show(row["address1"].ToString());
                        query = "update Ageingrpt set a90g='" + row["outstanding"].ToString() + "';";
                        cmd = new MySqlCommand(query, cnn);
                        MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }
                    else
                    {
                        cnn.Open();
                        MessageBox.Show(row["address1"].ToString());
                        query = "insert into Ageingrpt  values('" + row["address1"].ToString() + "',0,0,0,0,'" + row["outstanding"].ToString() + "',0); ";
                        cmd = new MySqlCommand(query, cnn);
                        MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }

                }

            }


text:
Q: XAML Button Hover Effect I have a button that uses a template. In my template, I have everything working correctly. My button shows correctly, with all images and text. But I would like to have a hover effect on my button. I've tried a style and a style trigger mouse over and neither worked. Can someone tell me how to get a hover effect on my button template below?
<Button Command="{Binding AppToolbarViewModel.RunToolAction, Source={StaticResource ViewModelLocator}}" CommandParameter="{Binding XamlURI}" ToolTip="{Binding ToolToolTip}"
Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Cursor="Hand">
    <Button.Template>
    <ControlTemplate>
        <StackPanel Orientation="Horizontal">
             <Grid>
                 <Label Content="" Style="{StaticResource FontAwesomeLabel}" />
                 <Label Content="{Binding ImageURI}" Style="{StaticResource FontAwesomeLabel}" FontSize="20" Margin="10,10,0,0" Foreground="GhostWhite" />
             </Grid>
             <Label Content="{Binding ToolName}" Style="{StaticResource ButtonLabel}" />
        </StackPanel>
    </ControlTemplate>
    </Button.Template>
</Button>

A: Sorry I can't comment (Don't have 50 reputation yet), but could you clarify what you mean by hover effect? Do you want a tooltip or do you want the style to change?
Regardless, if you want a tooltip you can refer to http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868199.aspx
You can also add images as a tooltip if that is what you are trying to do.
If you want the style to change when you hover over, you can implement the "PointerEntered" and "PointerExited" event handler's and modify the style in the code-behind or using some other command.


text:
Q: Convenient Way to Load Multiple Databases in Code Igniter I've added the appropriate configuration arrays to database.php and they work, however, I would like an easier way to access the different databases. Right now I have to do something like this in every controller method:
function index(){
    $BILLING = $this->load->database('billing', TRUE);
    $INVENTORY = $this->load->database('inventory', TRUE);

    $data['billing'] = $BILLING->get('stuff');
    $data['inventory'] = $INVENTORY->get('stuff');
}

I'd like to be able to put those first two lines in some sort of before filter or pre_controller hook.

A: You could simply load the database instances globally in your constructor, then they would be available to all controller methods...
example controller
class Example extends CI_Controller {

    //declare them globally in your controller
    private $billing_db;
    private $inventory_db;

    function __construct() {
        parent::__construct();

        //Load them in the constructor
        $this->billing_db = $this->load->database('billing', TRUE);
        $this->inventory_db = $this->load->database('inventory', TRUE);
    }

    function index() {

        //Then use them in any controller like this
        $data['billing'] = $this->inventory_db->get('stuff');
        $data['inventory'] = $this->billing_db->get('stuff');

    }

}

And if these same databases are used across multiple controllers, you might consider extending the base controller to include these global variables and load them in the constructor of your base controller in MY_Controller.php
example MY_Controller.php
class DB_Controller extends CI_Controller {

    //declare them globally in your controller
    private $billing_db;
    private $inventory_db;

    function __construct() {
        parent::__construct();

        //Load them in the constructor
        $this->billing_db = $this->load->database('billing', TRUE);
        $this->inventory_db = $this->load->database('inventory', TRUE);
    }

}

Then you'd use it like this...
class Example extends DB_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {

        //Then use them in any controller like this
        $data['billing'] = $this->inventory_db->get('stuff');
        $data['inventory'] = $this->billing_db->get('stuff');

    }

}


text:
Q: C++ sorting a vector of structs I am new to C++ and am trying to sort a vector based on values in another vector. I am trying to implement this by creating a vector of structs and sorting the vector of stucts using the STL. The structs have 2 data items, one a CustomType and the other an int. I want this sorted in decreasing order of the int field, and have therefore included a boolean operator overloading to be able to use the STL sort (algorithm).
The struct is constructed in the function using references to the CustomType vector and an initially uninitialised int vector, and combining them into a vector of structs. The values for the ints are obtained by calling a separate member function of SomeClass (SomeFunc) on each item of the CustomType vector and another u_int8_t param (this function works fine by itself).
In the end, I want to replace the sorted CustomType objects based on the sorted struct sequence.
The implementation file (.cpp) has the following function:
void SomeClass::orderFunc(std::vector<CustomType>& x, std::vector<int>& y, u_int8_t param){
    std::vector<CustomStruct> xy_vec;
    y.assign(x.size(), 0);
    int count  = int(x.size());

    for(int i=0; i != count; ++i){
        y[i] = SomeFunc(x[i], param);
    }

    for(int i = 0; i != count; ++i){
        xy_vec[i].var1 = x[i];
        xy_vec[i].var2 = y[i];
    }
    std::sort(xy_vec.begin(), xy_vec.end());
    for(int i = 0; i != count; ++i){
        x[i] = xy_vec[i].var2;
    }
}

The struct is defined in the SomeClass header file as below:
struct CustomStruct{
        CustomType var1;
        int var2;
        bool operator>(const CustomStruct& a) const{
            return (this->var2 > a.var2);
        }
    };

When this function is called,  I get the following error:

invalid operands to binary expression
bool operator()(const _T1& __x, const _T1& __y) const {return __x < __y;}

I can't understand why the bool operator overloading is invalid given that this is being defined for the int field of the struct.
What am I missing? Any help would be appreciated. Also, any suggestions for a more elegant way to do this would be great as well.

A: You need to overload operator< and not operator>
bool operator<(const CustomStruct& a) const
{
    return (this->var2 < a.var2);
}

EDIT: For sorting in reverse order, you need to call std::sort with rbegin() and rend() (reverse) iterators:
std::sort(xy_vec.rbegin(), xy_vec.rend());

EDIT (again, as the question is too long, has 2 problems):
The vector xy_vec is empty, you need to call resize:
std::vector<CustomStruct> xy_vec;
// Resize here
xy_vec.resize(count);
for(int i = 0; i != count; ++i){
    xy_vec[i].var1 = x[i];
    xy_vec[i].var2 = y[i];

Or you can call push_back - I am not telling you all that. Please find!

A: std::sort has two main overloads, one without a sort predicate that defaults to using operator < and one with a sort predicate (details here).
So you could write something like
struct CustomStructCmp {
    bool operator()(const CustomStruct& a, const CustomStruct& b) const
    {
        return a.var2 > b.var2;
    }
};

std::sort(xy_vec.begin(), xy_vec.end(), CustomStructCmp());

(if you are using C++11 then you could use a lambda instead).
Alternatively you could write
std::sort(xy_vec.begin(), xy_vec.end(), std::greater<CustomStruct>());

but I feel that it is more natural to directly use a functor/lambda rather than define operator> and use the std::greater functor.


text:
Q: How do I set an onClickListener for a bitmap? android java Is it possible to set an onClickListener for a bitmap while programming an Android app in java?  I tried using the same code as a button but eclipse displayed an error that a bitmap was not valid.  Please provide example code with your answer if it is possible.
Thanks!

A: You can create an ImageButton and set it the bitmap with setImageBitmap. Then just set a listener to the ImageButton object.
ImageButton imgButton = (ImageButton) findViewById(R.id.imgButton);
imgButton.setImageBitmap(myBitmapObject);
imgButton.setOnClickListener(new View.OnClickListener(){
     @Override
        public void onClick(View v) {
        Toast.makeText(yourActivity.this, "ImageButton Pressed",
                       Toast.LENGTH_LONG).show();
         }
        });


text:
Q: How is this done? $2i+((1/2)-i)^2=((1/2)+i)^2$ Can someone please explain me how this is done?
$$\ 2i+\left(\frac{1}{2}-i\right)^2=\left(\frac{1}{2}+i\right)^2$$

A: $$\ 2i+\left(\frac{1}{2}-i\right)^2=2i+\frac{1}{4}-i+i^2=\frac{1}{4}+i+i^2=\left(\frac{1}{2}+i\right)^2$$
No need to use $i^2=-1$.

A: Hint: Note that $${ i }^{ 2 }=-1\\ { \left( a+b \right)  }^{ 2 }={ a }^{ 2 }+2ab+{ b }^{ 2 }$$

A: $$2i+(\tfrac12-i)^2=2i+(\tfrac12)^2-2(\tfrac12)(i) +(i)^2$$
$$=2i+\tfrac14-i+(-1)$$
$$=-\tfrac34+i$$
On the other hand,
$$(\tfrac12+i)^2=(\tfrac12)^2+2(\tfrac12)(i) +(i)^2$$
$$=\tfrac14+i+(-1)$$
$$=-\tfrac34+i$$
which is the same as the first value.


text:
Q: Is the Gromov conjecture still open? Today I read about Gromov's definition of minimal volume for smooth manifolds.
$$\min {\rm Vol}(M):=\inf_{|K_g|\leq1}\{{\rm Vol}(M,g)\}.$$
Gromov's conjecture states that for every closed simply connected odd-dimensional manifold $\min {\rm Vol}(M)=0$. Is the Gromov conjecture still open? Can anybody give an example for this conjecture?
Update: My teacher told to me that this conjecture can be solved by the Ricci flow method but I don't know how to use it. Can anybody give me an explanation to this? and how it works?
Thanks.

A: This response is unfortunately not about simply-connected manifolds, I overlooked that assumption by the author of the question. So, this is not an answer. See my comment below.
Gromov writes in this paper (see Section 0.4) an example of an odd dimensional (not simply-connected) manifold with non-vanishing minimal volume, by constructing a lower bound involving the so-called simplicial volume (and a corresponding metric $g$).

A: According to wikipedia, the conjecture is still open. I do not see at all how RF can help here. (Apart from dimension 3 when the statement is of course a corollary of Perelman's geometrization theorem.) There is no positivity assumption on curvature(s) of $M$ in this conjecture and the Ricci Flow  in higher dimensions is mostly a mystery without some positivity assumptions. From what you wrote, it sounds like your teacher has no idea how to approach this problem via Ricci Flow either; I suggest you work on something else, more doable.
One more thing: The conjecture is only in odd-dimensional case. For even dimensional manifolds Gromov noted in his paper that there is a bound $MinVol(M^n)\ge c_n|\chi(M)|$, $c_n>0$. Hence, all even-dimensional spheres have positive minimal volume.
Edited: (4 September 2017)
An Example of vanishing minimal volume which is due to Gromov is three-sphere. (see Gromove paper,section 0.4)


text:
Q: How to add the webp format in the mod_expires part of the .htaccess file? I add this line but it is not taken into account because the browser inspector tells me that the cache is 2 days for webp images:
ExpiresByType image/webp "access plus 1 month"

I use Plesk with Varnish.
<IfModule mod_expires.c>

    ExpiresActive On
    ExpiresDefault "access plus 2 days"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/webp "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 month"

</IfModule>

A: I just found the solution, we must add:
AddType image/webp .webp

Into .htaccess :
############################################
## Prevent character encoding issues from server overrides
## If you still have problems, use the second line instead

    AddDefaultCharset Off
    #AddDefaultCharset UTF-8
    AddType 'text/html; charset=UTF-8' html
    AddType image/webp .webp

<IfModule mod_expires.c>

    ExpiresActive On
    ExpiresDefault "access plus 2 days"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/webp "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/x-javascript "access plus 1 month"
    ExpiresByType application/x-shockwave-flash "access plus 1 month"
    ExpiresByType image/x-icon "access plus 1 month"

</IfModule>


text:
Q: Permission denied with django migrations in docker I'm using docker compose with django - postgres - rabbitmq
All is going good even django container is up and running to the point I want to makemigrations it stops with django-celery-beat
Migrations for 'django_celery_beat':
django_1        |   /usr/local/lib/python2.7/site-packages/django_celery_beat/migrations/0005_auto_20190512_1531.py
django_1        |     - Alter field event on solarschedule
django_1        | Traceback (most recent call last):
django_1        |   File "/app/manage.py", line 10, in <module>
django_1        |     execute_from_command_line(sys.argv)
django_1        |   File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
django_1        |     utility.execute()
django_1        |   File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 356, in execute
django_1        |     self.fetch_command(subcommand).run_from_argv(self.argv)
django_1        |   File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
django_1        |     self.execute(*args, **cmd_options)
django_1        |   File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
django_1        |     output = self.handle(*args, **options)
django_1        |   File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 193, in handle
django_1        |     self.write_migration_files(changes)
django_1        |   File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/makemigrations.py", line 232, in write_migration_files
django_1        |     with io.open(writer.path, "w", encoding='utf-8') as fh:
django_1        | IOError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site-packages/django_celery_beat/migrations/0005_auto_20190512_1531.py

while user model is written down at migrations and it supposed to be inherited from AbstractUser at django itself but no permission error raised there
django_1        | Migrations for 'users':
django_1        |   users/migrations/0001_initial.py
django_1        |     - Create model UserAccount
django_1        |     - Create model Branch
django_1        |     - Create model Organization
django_1        |     - Add field organization to branch
django_1        |     - Add field bills_groups to useraccount
django_1        |     - Add field branch to useraccount
django_1        |     - Add field groups to useraccount
django_1        |     - Add field user_permissions to useraccount

so I tried to add sudo user to the python-2.7 alpine but actually I failed to run this command with sudo permission
So what should I do, should I run the image using virtualenv inside docker or is there any tweak to fix this one
Dockerfile
FROM python:2.7-alpine

ENV PYTHONUNBUFFERED 1
RUN addgroup -S django \
    && adduser -S -G django django

RUN apk update \
  && apk add sudo \
  # psycopg2 dependencies
  && apk add --virtual build-deps gcc python-dev musl-dev \
  && apk add postgresql-dev \
  # CFFI dependencies
  && apk add libffi-dev py-cffi \
  # Translations dependencies
  && apk add gettext \
  # https://docs.djangoproject.com/en/dev/ref/django-admin/#dbshell
  && apk add postgresql-client

# Requirements are installed here to ensure they will be cached.
COPY ./requirements.txt /requirements.txt
RUN pip install --no-cache-dir --default-timeout=100 -r /requirements.txt \
        && rm -rf /requirements

COPY ./compose/testing/django/entrypoint /entrypoint
RUN sed -i 's/\r//' /entrypoint
RUN chmod +x /entrypoint
RUN chown django /entrypoint

COPY ./compose/testing/django/start /start
RUN sed -i 's/\r//' /start
RUN chmod +x /start
RUN chown django /start

COPY . /app

RUN chown -R django /app

USER django

WORKDIR /app

ENTRYPOINT ["/entrypoint"]

docker-compose.yml
version: '3'

volumes:
  production_postgres_data: {}
  production_postgres_data_backups: {}

services:
  django: &django
    build:
      context: .
      dockerfile: ./compose/testing/django/Dockerfile
    image: panel_testing_django
    depends_on:
      - postgres
      - rabbitmq
    env_file:
      - ./.envs/.production/.django
      - ./.envs/.production/.postgres
    command: /start
    ports:
      - "8000"
    expose:
      - "8000"

  postgres:
    build:
      context: .
      dockerfile: ./compose/staging/postgres/Dockerfile
    image: panel_testing_postgres
    env_file:
      - ./.envs/.production/.postgres
    volumes:
      - production_postgres_data:/var/lib/postgresql/data
      - production_postgres_data_backups:/backups
    ports:
     - "5432"

  rabbitmq:
    hostname: rabbit
    image: rabbitmq:3-management
    environment:
      - RABBITMQ_DEFAULT_USER=admin
      - RABBITMQ_DEFAULT_PASS=mypass
    ports:
      - "5672:5672"
      - "15672:15672"

  celeryworker:
    <<: *django
    image: panel_testing_celeryworker
    command: /start-celeryworker

  celerybeat:
    <<: *django
    image: panel_testing_celerybeat
    command: /start-celerybeat

  flower:
    <<: *django
    image: panel_testing_flower
    ports:
      - "5555:5555"
    command: /start-flower

A: Had more less the same issue today. I created a project using docker and when tried to run makemigrations for the first time, got this error:
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.7/site-packages/django/contrib/admin/migrations/0004_auto_20190515_1649.py'

I solved it by running the makemigrations especifying the app name(core is the app name), like this:
docker-compose run web_app sh -c "python manage.py makemigrations core"

A: I'm on Linux and in my case it was simply a case of going to the folder where the migrations are stored and giving sufficient permissions to the folder itself.
For example:
chmod . 666

A: I've just used virtualenv inside docker and gives ownership to my user over the environment site-packages dir
RUN pip install virtualenv && virtualenv -p python /app/venv
RUN /app/venv/bin/pip install -r req.txt
RUN /app/venv/bin/python /app/code/manage.py makemigrations

and DONE


text:
Q: How to get birthdate, city, mobile number, state, country from FacebookSdk in swift 3 I am trying to fetch data from FacebookSDK , like user infromation name, last_name. first_name, email i am getting this details but i want more detials of user from there account like birthdate, city, mobile number, .. etc , i have added all parameters to SDK but i am not able to fetch other details of user  can anyone help me please, thank you , here is my code`
     let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
     fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
     fbLoginManager.logIn(withReadPermissions:
     ["public_profile","email"], from: self) { (result, error) ->
     Void   in
     if error != nil {
      print(error!.localizedDescription)
      self.dismiss(animated: true, completion: nil)
      } else if (result?.isCancelled)! {
      print("Cancelled")
      self.dismiss(animated: true, completion: nil)
       } else {
       }
    }
    //id,name,birthday,email,last_name,location
     FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id,
       name, first_name, birthday, email ,
     location"]).start(completionHandler:
       { (connection, result, error) -> Void in
        if (error == nil){
            let fbDetails = result as! NSDictionary

            print("fb details\(fbDetails)")

        }
    })

`

A: you can get as follows
let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"])

            graphRequest.start(completionHandler: { (connection, result, error) -> Void in

                if ((error) != nil)
                {
                    print("Error: \(error)")
                }
                else
                {
                    let data:[String:AnyObject] = result as! [String : AnyObject]
                    print(data)

                }
            })


text:
Q: M Language (Power Query) Salesforce Web API - Passing Collections? I am trying to query a Salesforce Datasource using the Salesforce API in Power BI.
The issue I am having is that the Salesforce API requires the SOQL to either contain a WHERE clause on the specific query being performed, by using an explicit value "=" or a IN operator.
If I use something like the following
each ([Column] = "value")

It works, however if I try and pass a list like the following:
each List.Contains(myList, [Column])

It fails with an error because the SOQL query being executed in the background clearly does a filtering AFTER all the data has been returned (i.e being filtered in Power BI after its been retrieved and not at source) and the Web API is expecting a IN operating with a list of values.
With regards to the first query, this works because the SOQL in the background is WHERE (MyField = 'someValue')
Does anyone have any ways around this? Can Power BI pass a collection into a where clause some way?
If not, I thought about querying the records by a single value and looping through this but it will have performance issues and not the best way of doing such query!
I have also tried joining the tables on the field I need but it also looks like the joins are performed after the data is retrived and not before (using SOQL).
I cannot modify the Web API to support other queries.
Thank you!


text:
Q: retrieving related field in controller index function gives error but ok in show function I define the relation in Company table (where I added the plural):
protected $table = 'companies';

public function country() {
    return $this->belongsTo(Country::class, "country_id")->withDefault(['country' => 'unknown']);
}

I also did the same in the Country model.
When I use the following code in the controller show function it works:
public function show (Company $company) {
    $company->country = $company->country()->pluck('country');

But if I use the same code in the index function in a loop, I get an error "Call to undefined method stdClass::country()":
public function index (Company $company) {
    if (request('tag')) {
        $companies = Tag::where('name',request('tag'))->firstOrFail()->companies;
        $companies->page_title = "Businesses matching tag '".request('tag')."'";
    } else {
        $companies = DB::table('companies')
           ->where([['is_active', '=', '1']])
           ->orderBy('company')
           ->get();
    }
    foreach($companies as $key => $thisCompany) {
        ...
        $thisCompany->country = $company->country()->pluck('country');
    }

I guess it is due to the fact that $company is created in the loop and not passed through the function like in show(Company $company)... but I could not find how to solve this issue... so help will be appreciated.
I have added the model in the argument of the function and change the name of the $company variable in the loop by $thisCompany to avoid confusion with the $company model.
No error but the field $country->country does not contain the name of the country but "Illuminate\Support\Collection {#443 …1}"
Why is it so complicated?  Please help...

A: Paul, sorry, I think I didn't explain myself well in the comments.
What I meant by "What about if you change DB::table('companies') by Company?", is to stop using DB Query Builder to use the Eloquent Company model.
Specifically in this segment of code:
$companies = DB::table('companies')
    ->where([['is_active', '=', '1']])
    ->orderBy('company')
    ->get();

So, it could be:
$companies = Company::where([['is_active', '=', '1']])
    ->orderBy('company')
    ->get();

The explanation is that in the first way (with DB Query Builder), the query will return a collection of generic objects (the PHP stdClass object) that do not know anything about the Company and its relationships.
On the other hand, if you use the Eloquent model Company, it will return a collection of Company objects, which do know about relationships, and specifically the relationship that you have defined as country.
Then, when you loop over the collection, you will be able to access the country relation of each Company object:
foreach($companies as $key => $company) {
    //...
    $company->country = $company->country()->pluck('country');
}

Finally, your code could looks like:
public function index () {
    if (request('tag')) {
        $companies = Tag::where('name',request('tag'))->firstOrFail()->companies;
        $companies->page_title = "Businesses matching tag '".request('tag')."'";
    } else {
        $companies = Company::where([['is_active', '=', '1']])
           ->orderBy('company')
           ->get();
    }
    foreach($companies as $key => $company) {
        //...
        $company->country = $company->country()->pluck('country');
    }
    //...
}


text:
Q: How to attach attributes of a directive template to other elements than the parent in AngularJS? I'd like to implement a directive that converts
<specialInput></specialInput> into something like

    <input></input>

However, all attributes that the user provides by putting them into the specialInput-tag like <specialInput id="test" class="test2" ... required></specialInput> are currently attached to the div element myDiv.
Rather than that, I would like to attach all attributes to the input-tag.
Note: One solution would be manually attaching every possible attribute to the label tag by adding the variable (e.g. type="' + atts.type + '") to the template and then remove these attributes from the parent by using the linkfunction. This is not what I want to achieve though. There are way too many possible attributes to consider this solution.

// special-input Angular

(function () {
  'use strict';

  function specialInputDirective($compile) {

    function templateFunction(element, attrs) {
      var template = [
       '
'+
       '' + attrs.label + '' +
       '
' +
       '  <input id="' + attrs.id + '" type="' + attrs.type + '" ' +
       '       ng-model="' + attrs.name + '" ' +
       (attrs.ngTrueValue ? 'ng-true-value="' + attrs.ngTrueValue + '" ' : '') +
       (attrs.ngFalseValue ? 'ng-false-value="' + attrs.ngFalseValue + '"' : '') +
       ' " placeholder="' + attrs.placeholder + '"' + ' ' +
       attrs.required + ' ' + attrs.disabled + ' ' + attrs.readonly  +
       ' name="' + attrs.name + '"' +
       ' required>' +
       '
' +
       '
'
      ].join('');
      return template;
    }

    return {
      link: linkFunction,
      restrict: 'E',
      replace: true,
      transclude: true,
      template: templateFunction
    };

    //////////

    function linkFunction(scope, inputElement, attrs, ctrl, transcludeFn) {
      // Removes user defined attributes from 'control-group'.
      // These are added to the <input> element instead (Defined in: Template)
      // BUT: there are many, many more attributes than this! So this is not the solution I'm aiming for.
      inputElement.removeAttr('id');
      inputElement.removeAttr('type');
      inputElement.removeAttr('label');
      inputElement.removeAttr('placeholder');
      inputElement.removeAttr('required');
      inputElement.removeAttr('disabled');
      inputElement.removeAttr('readonly');
      inputElement.removeAttr('name');
    }
  }

  //////////

  function initModule(angular) {
    ...
  }

}());
<form name="myForm" class="form-horizontal" style="max-width: 700px;">

Horizontal Label

    <special-input name="myName" type="email" label="Email" placeholder="Email"></special-input>
    <special-validation for="myForm.myName" message="required" type="error">This message box represents an error</special-validation>
    <special-validation for="myForm.myName" message="minlength" type="warning">This message box represents a warning</special-validation>
    <special-validation for="myForm.myName" message="maxlength">This message box represents an error</special-validation>
    <special-validation for="myForm.myName" message="email">Invalid email address</special-validation>

    <special-input type="text" label="Text" placeholder="Required input" name="myName2" ng-minlength="5" ng-maxlength="20" required></special-input>

    <special-input type="password" label="Password" placeholder="Password"></special-input>
</form>

A: You definitely don't want to create binding in scope for each attribute. Instead, the simplest and probably the most effective way to solve it, is to find an input element and then copy all attributes to it in compile function.
Here is simplified version of your directive:
.directive('specialInput', function() {

    function linkFunction(scope, element, attrs) {
        // Do something else, bind events, etc ...
    }

    return {
        transclude: true,
        template: function(element, attrs) {
            return '' +
            '
' +
            '    ' + attrs.label + '' +
            '    <input>' +
            '
';
        },
        compile: function(element, attrs) {

            var input = element.find('input');

            // Copy attrbutes
            angular.forEach(attrs.$attr, function(val, key) {
                input.attr(val, attrs[key]);
            });

            element.replaceWith(element.children()[0]);

            return linkFunction;
        }
    };
});

Demo: http://plnkr.co/edit/sQRFzDN0nZJBinu8atOH?p=preview

A: You have to use the compile feature of the directive to achieve what you want.
As long as you only want to move PLAIN ATTRIBUTES from parent element to inner, you are basically ok. If you want to move DIRECTIVES attributes from parent to children, this is way more complicated.
The example the for first option ( only plain/html attribute, not moving stuff that will need to be compiled/linked on the child element ) would be :
/**
 * Input wrapper directive, used to copy all attributes to the underneath input element.
 *
 * To keep a property on the wrapper, prefix it with "wrapper-*"
 * In example, "wrapper-class" will create the "class" property on the wrapper, where "class" will be copied to the input.
 */
module.directive("tlInputWrapper", function($compile) {
    // TODO : keep ngShow, ngIf... and other logic directive on the wrapper.
    return {
        restrict : "A",
        compile  : function($el, $attrs) {

            var input = $el.find("input"); // here, you find the child element you wanna move attributes to

            $attrs.$set("tlInputWrapper", null);
            var attributesToKeep = {};

            _.each($attrs.$attr, function(domAttributeName, normalizedAttributeName) {
                if(domAttributeName.indexOf("wrapper-") === 0) { // I allow keeping attributes on the wrapper. Ex : 'wrapper-class' will stay on the wrapper and be renamed 'class'
                    attributesToKeep[domAttributeName.substring(8)] = $attrs[normalizedAttributeName];
                    $attrs.$set(normalizedAttributeName, null);
                } else {
                    input.attr(domAttributeName, $attrs[normalizedAttributeName]);
                    $attrs.$set(normalizedAttributeName, null);
                }
            });

            _.each(attributesToKeep, function(attrValue, attrName) {
                $attrs.$set(attrName, attrValue);
            });

            return angular.noop;
        }
    };
});


text:
Q: PHP-FPM 7.4 sometimes hangs for a few requests Hello all fellow devs,
I have a problem in a production site (laravel). Sometimes(like 4-8 request an hour) the most simple requests are causing this kind of errors:
[13-Dec-2020 18:07:07] WARNING: [pool www] child 514732, script '/home/****/****/public/index.php' (request: "GET /index.php") execution timed out (71.782847 sec), terminating

When i check my access log i see that it is the most simple request. It even happens with request where there is no mysql query executed. When i look at memory usage there is 1GB available when it happens. CPU is running at 10% tops.

*

*I use digitalocean load balancer to redirect traffic to server.

*There are about 60-120 requests a minute per server

*It is happening on all my servers (i have 4)

*php using opcache

*mysql hosted on separate servers

*redis hosted on separate servers

*I have tried to lower and raise the fpm childs

PHP fpm settings
pm = dynamic
pm.max_children = 40
pm.start_servers = 15
pm.min_spare_servers = 15
pm.max_spare_servers = 25
;pm.process_idle_timeout = 10s;
pm.max_requests = 500

I hope you guys can help me, i have searched all over the internet but nothing works. Thank you so much.
Timo

A: So it was an issue of the redis connection.
Solution was to use tls1.2.
https://github.com/phpredis/phpredis/issues/1726

A: The problem come from Redis connection with TLS 1.3 (https://bugs.php.net/bug.php?id=79501)
Redis connection with TLS 1.3 is not stable.
If you connect to Redis with tls protocol, for example your Redis host is tls://your-redis-domain-here, PHP will use TLS 1.3 by default. To resolve this issue you have to specify tlsv1.2 in your connection, for example: tlsv1.2://your-redis-domain-here


text:
Q: Can't use std::apply on std::array I am trying to apply a lambda to the elements of an std::array.
    std::array<int, 4> fixIndices = {1, 60, 127, 187};

    std::apply(
        [](int id) {
            std::cout << id;
        },
        fixIndices);

However, this simple code doesn't compile
/usr/lib/gcc/x86_64-pc-linux-gnu/10.3.0/include/c++/tuple:1727:27: error: no matching function for call to '__invoke(****)::<lambda(int)>, int&, int&, int&, int&)'
 1727 |       return std::__invoke(std::forward<_Fn>(__f),
      |              ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~
 1728 |       std::get<_Idx>(std::forward<_Tuple>(__t))...);

What am I missing?

A: std::apply is to call a callable with parameters given as a tuple. For example you can call some
auto f = [](int a,double b,char c) {}

with a std::tuple<int,double,char>. Note that std::array is tuple-like, ie you could use your array to call a callable that expects 4 parameters.
However, here you do not need std::apply. You can use a loop:
std::array<int, 4> fixIndices = {1, 60, 127, 187};
auto f = [](int id) { std::cout << id;};
for (const auto& id : fixIndices) f(id);

Or closer to your code via for_each:
std::for_each(fixIndices.begin(),fixIndices.end(), [](int id) { std::cout << id; });

A: std::apply forwards the arguments contained in the tuple(-like) to the callable f, so your lambda should be
std::array<int, 4> fixIndices = {1, 60, 127, 187};
std::apply(
  [](auto... ids) {
     ((std::cout << ids << " "), ...);
  },
  fixIndices);

But for std::array, if you want to iterate over its elements, a range-based for loop is an easier option.


text:
Q: \textit sets text to slanted I'm having some problems with equations in my bachelor thesis. I want to have the equation numbered and underneath in the same style written what the Letters stand for. So this is what i came up with:
\begin{equation}
     S_T = G \cdot I_T [Nmm^2]
\end{equation}
\begin{center}
     \textit{I_T = Torsionsflächenmoment}\\
     \textit{G=Schubmodul}
\end{center}
\begin{equation}
    G = \frac{E}{2 \cdot (1+\nu)} [MPa]
\end{equation}
\begin{center}
    \textit{E=E-Modul}
\end{center}
\begin{equation}
    I_T= \frac{\pi}{32} \cdot (D^4-d^4) [mm^4]
\end{equation}

However, when i generate the thesis file, the 5th line is itlaic (the way I want it to be), but the other two are just slanted. The thing is, if I try it in a file with just this text in the document it works fine.

I just find it really strange, how it's slanted but not italic.
I'm not very good with latex, so if anyone has an idea where the error might come from, that would be really helpful.
Luisa
P.S: English is not my first language, so don't come for me ;)


text:
Q: Visual Studio 2013 CodeLens Authors not Showing Up I am using Visual Studio 2013 Ultimate with Git, and I have CodeLens enabled so that I can see references, authors, changes.. etc. The problem is that the only thing that is showing up is the references.

I went to Tools > Options > Text Editor > All Languages > CodeLens and found all the textboxes checked.

Any ideas how I can Show Authors?


text:
Q: Not able to unmarshall XML file that contains tabs with JAXB correctly? I have an xml file as follows:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<billFile fileName=".dat" hasHeader="false" fieldDelimiter="    "/>

The fieldDelimiter contains a tab. When I call Unmarshaller.unmarshal to convert this xml file to an object, the tab gets replaced by a space. I want it to stay as a tab. Here is the java code I have:
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;

public class XMLToConfig
{
  public static void main(String[] args) throws JAXBException
  {
    String input                  = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>    <billFile fileName=\".dat\" hasHeader=\"false\" fieldDelimiter=\" \"/>";
    JAXBContext jaxbContext       = JAXBContext.newInstance(BillFile.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    BillFile bf                 = (BillFile)jaxbUnmarshaller.unmarshal(new StreamSource(new StringReader(input), "UTF8"));
  }
}

A: You have to use the Unicode of tab instead of a real tab:
unicode for tab and sapce


text:
Q: Ternary operator not updating alert dialog UI in Flutter I have an alert dialog that contains a Camera Preview from the camera package, and after I take a picture, I want the alert dialog to instead show a loading screen.  I was hoping to accomplish this by using a ternary operator in the dialog.  Below is the dialog I call when I press a button, where isCalculating is a bool that is originally set to false, _initializeControllerFuture initializes the camera, Loading() is the loading screen, and Stack() has the Camera Preview as well as some other things.
cameraDialog(context) async {
    await showDialog(
      barrierDismissible: false,
      context: context,
      builder: (_) => AlertDialog(
        insetPadding: EdgeInsets.all(5.0),
        contentPadding: EdgeInsets.all(3.0),
        content: FutureBuilder<void>(
          future: _initializeControllerFuture,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return isCalculating
                  ? Loading()
                  : Stack(

In the cameraDialog I have a button that takes a picture, sets the bool isCalculating to true, runs some other code, and sets the bool isCalculating back to false.  During this time I want the alert dialog to update its UI and show the Loading() widget. Below is the on pressed event for the button in the cameraDialog:
onPressed: () async {
                  originalFile = await controller.takePicture();
                  setState(() {
                    isCalculating = true;
                  });
                  ... other code is run here ...
                  Navigator.of(context).pop();
                  setState(() {
                    isCalculating = false;
                  });
                },

A: As you can see  cameraDialog is a function which is triggered by also a function like onPress or onTap . When you call setState its really call  Widget build(BuildContext context) method and rebuilt the widget tree but it never handle the state of a function or inside a function's content. So calling setState where you use it has no usefulness. So what you can do? you can create a StatefullWidget ex- MyAlertDialog and show it like
onTap: ()=> showDialog(context: context, builder: (ctx) => MyAlertDialog()),

and inside MyAlertDialog you can handle your state just like you did here.


text:
Q: how to use composer in opencart 2.2.0 So, based on Opencart 2.2.0 installation guide :

From version 2.2 composer has been added to aid developers who want to
  use composer libraries. 2 versions of OpenCart will become available,
  one compiled and one non-compiled (composer.json only - no files in
  vendor folder). We STRONGLY advise leaving the vendor folder outside
  of the webroot - so files cannot be accessed directly.

I have this directory structure under /srv/www/mywebsite.com on my VPS.
.
├── composer.json
├── nbproject
├── public_html
│   ├── admin
│   ├── catalog
│   ├── image
│   ├── index.php
│   ├── libraries
│   │   ├── exec.php
│   │   ├── InterfaceREST.php
│   │   ├── kurir
│   │   ├── RestGuzzle5.php
│   │   └── Test.php
│   ├── system
│   │   ├── startup.php
│   └── vqmod
├── tests
└── vendor
    ├── guzzlehttp
    ├── psr

And this is my composer.json :
{
    "name": "opencart",
    "type": "project",
    "description": "online store",
    "keywords": ["opencart", "ecommerce", "framework", "opensource"],
    "homepage": "http://www.mywebsite.com",
    "license": "MIT",
    "authors": [
        {
            "name": "fatimah",
            "email": "fatimah@mywebsite.com"
        }
    ],
    "autoload": {
        "psr-4": {
            "GodFather\\": "libraries"
        }
    },
    "require": {
        "cardinity/cardinity-sdk-php": "^1.0",
        "braintree/braintree_php": "3.2.0",
        "leafo/scssphp": "0.0.12",
        "php": ">=5.4.0"
    }
}

I've create some classes under directory libraries.
Test.php (example)
<?php

namespace GodFather;

use GodFather\InterfaceREST;

class Test
{

    public function __construct() {

    }

    public function test_rest(InterfaceREST $rest) {
        $rest->request('get', '/kontak-kami');
        var_dump($rest->get_status_code());
    }

}

And I'm trying to use guzzle by running exec.php from cli. php -f exec.php
<?php

require_once('../index.php');

use GuzzleHttp\Client;

$rest = new Client(['base_url' => 'http://zuwaily.blogspot.co.id']);
$req = $rest->createRequest('get', '/p/hubungi-zuwaily.html');
$res = $rest->send($req);
echo $res->getStatusCode();

I don't get status code.
How to exactly use composer in Opencart? And how to use psr-4? am I doing correct? I need your advise.
Thanks.


text:
Q: Upload Image from Iphone to WCF Service : stream or REST? I google a lot this question and I'm a bit confused.
I need to upload an image from Iphone to a WCF service.
I've already a working WCF which receive an image in 'stream' mode.
But I read somewhere a must use a REST WCF in order to work whit iphone.
What should I do?
Thank you

A: If you're uploading a image "as is" from the iPhone, I imagine that you're already using the REST mode in WCF to do that. If your service endpoint uses the webHttpBinding and has a webHttpBehavior added to it, then you're already in the "WCF REST" realm (the official name is "WCF WebHTTP Endpoints", but it's more known as WCF REST endpoints).
Even if you're not using WCF REST, if what you have is working for you, then you're fine.


text:
Q: Is there a way to show per selected filter a specific description above the catalog in wooncommerce I am building a webshop with WooCommerce and want to show the selected filter description, as sample:
If selected filter 'color' than show the description above the catalog. BUT if you select 'size' than show only the description from the selected size as sample; selected filters: color, size, length, type, material. than only show the description from material.
this code below is working fine but only for one filter, not for all/multiple, how can i set multiple filters? like pa_brand and pa_size and pa_color etc.
and then also showing always the last selected one.
already thanks!
add_action( 'woocommerce_before_shop_loop', 'desc_before', 75 ); function desc_before() {
if (is_filtered()) {
    $brands = WC_Query::get_layered_nav_chosen_attributes() ['pa_brand'];
    if ( isset($brands) ) {
        foreach ($brands['terms'] as $term ) {
            $term_obj  = get_term_by('slug', $term, 'pa_brand');

            echo '
'.
                 '
' . $term_obj ->name . '
'.
                 $term_obj->description.
                 '
';
        }
    }
}}


text:
Q: Creating data.frame with descriptives I'd like to create a data.frame with the descriptives of my 107 items in the columns. When I do the order like that, it only gives me the descriptives for my first item. Maybe somebody can help me out and knows what is wrong in the function.
variables <- names(srsi)
names.items <- c(grep("SRSI_", variables, value = TRUE))

item.diff <- data.frame(matrix(NA, ncol=8, nrow=length(names.items)))
names(item.diff) <- c("Item", "n", "mean", "sd", "min", "max", "range", "se")
length(names.items)

for(i in 1:length(names.items)){

  item <- names.items[i]

  par <- describe(srsi[,-1], skew = F)

  item.diff[i, c("n", "mean", "sd", "min", "max", "range", "se")]

}


text:
Q: how to redirect connections to IPs behind the NAT to NATted (public ) IPs at the source? I have an application that relies on IP addresses for communication (Domain names simply does not work. :(... )
Its function is to connect to its peer on the other machine and send data over after establishing trust. During the "trust establishing" phase they both exchange their IPs for future communication. They both are behind the two different firewalls and are NATted. One is in our NATted office network and other is in the cloud NATted behind their firewall. The applications knows their respective private IPs and exchange that (the 10.x.xxx.xxx range), when they try to connect back to each other (using the private IPs with range 10.x.xxx.xxx) for transferring data they fail. The connection is TCP and the port range is pretty varied.
I am curious if there is anyway I can hard code (for this one time) a rule (at may be firewall level or some place outside my application) that says if there is a connection being initiated for IP address 10.x.xxx.xxx then redirect it to 205.x.xxx.xxx?

A: Private IP address ranges like 10.x.y.z are, by their very nature, private.
You can't do any meaningful resolution unless each node in between the endpoints has rules in place to translate these.
Translation is tricky, all the main tools you would use cater for static translation (port forwarding, e.g. where a particular port is forwarded to a particular IP). This is one avenue, but it is a hacky one (it requires you to open lots of ports, procedurally update your router and probably have some sort of broker server to maintain mappings).
Alternatively, you could run the isolated networks over a VPN, which would give your endpoints mutual private IPs which you can use to connect to eachother. It would simply be a case of binding to this new address and communicating across the VPN. This would also potentially encrypt your communication over the internet.
Other possibilities are to use NAT/TCP punchthrough techniques which can allow traversal, but these are really a patch to a broken network topology (Read up on IPv6 to see how this can be alleviated).
Alternatively, you could route all the connections over a proxy, but this will complicate matters compared to a VPN.

To answer the question about hardcoding a rule, port forwarding is the solution here. It will obviously depend on your router configuration for the peer accepting the connection, but this client should have the port target port forwarded to the machine. This will obviously not scale very well and is really shifting to a server/client architecture for one connection!
Depending on your hardware, you may be able to forward a range of ports (if a single port cannot be established) and limit the port forwarding to certain incoming connections (the external IPs).
Information on port forwarding can be found at http://portforward.com/

A: This sounds a lot like what you'd want out of a VPN.  Is there anyway that you could set one up?  Basically the Site-To-Site VPN between you and the cloud would say 'oh hey, here is an ip located on the remote network, go ahead and connect through the link'.  Would this kind of solution work in your case?
Something along these lines:  http://i.msdn.microsoft.com/dynimg/IC589512.jpg


text:
Q: Scala Regex ReplaceAll: How to Replace All Groups? The following regex replace works beautifully:
var line = "PRIMARY INDEX XPKDLRSRC_PMT_CLMPMT ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );"
println(line.replaceAll("""[UNIQUE\s]{0,1}PRIMARY INDEX [^\s]* \(""", "PRIMARY KEY ("))

It returns: PRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );
The point of the first group [UNIQUE\s] was to take care of the following as well
line = "UNIQUE PRIMARY INDEX XPKDLRSRC_PMT_CLMPMT ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );"
println(line.replaceAll("""[UNIQUE\s]{0,1}PRIMARY INDEX [^\s]* \(""", "PRIMARY KEY ("))

But the word UNIQUE does not get replaced and I end up with
UNIQUEPRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );
When I expected
PRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );
How to I get all groups in the regex replaced by a string?

A: [UNIQUE\s] represents a single character consisting of any of the enclosed characters.  For what you need, replacing it with (?:UNIQUE\s+)? should do.
val line = "UNIQUE PRIMARY INDEX XPKDLRSRC_PMT_CLMPMT ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );"

line.replaceAll("""(?:UNIQUE\s+)?PRIMARY INDEX [^\s]* \(""", "PRIMARY KEY (")
// res1: String = PRIMARY KEY ( DLRSRC_PMT_ID ,DLRSRC_PMT_CLMPMT_ID );

(?:regex) represents a non-capturing group and appending the group with a ? makes it an optional match.


text:
Q: View intents meant for browser vs external app in Android I'm building a basic web browser with the android webview component and recently added support for opening links in relevant external apps e.g. if you're on a page and click a youtube link, the youtube app is opened instead of navigating to the web page.
This works fine accept for when an app is freshly installed and you click on a link for the first time (I suspect my app isn't the default browser at this point). Then it always prompts if you want to open it in another app, even if the only other relevant apps are other browsers, which isn't a great user experience as the user is already in the browser they want to open the link in otherwise they wouldn't be using it.
So I need to be able to distinguish between a link that has a dedicated installed app (e.g. it's found a wikipedia app for wikipedia links) vs a link that there are no dedicated apps for and is suitable for any browser to open.
Here's the relevant code in MyWebViewClient.shouldOverrideUrlLoading()...
Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
if(intent!=null){
    PackageManager packageManager = context.getPackageManager();
    ResolveInfo info = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY);
    if (info != null) {
        String suggestedPackageName = info.activityInfo.applicationInfo.packageName;
        String intentAction = intent.getAction();
        final boolean packageMatchesThisBrowser = (MY_PACKAGE_NAME).equals(suggestedPackageName);
        final boolean isUrlAttempt = UrlHelper.isUrlAttempt(url);
        final boolean areSuggestedAppsOnlyBrowsers = false; // ????
        final boolean canItBeOpenedInThisBrowser = isUrlAttempt;
        if(canItBeOpenedInThisBrowser && (packageMatchesThisBrowser || areSuggestedAppsOnlyBrowsers)){
            return false; // allow the url to load normally in the current web view
        }else {
            // Else we have a dedicated app link (e.g. tel://, whatsapp://, intent://) or app supported links like (e.g. https://youtube.com/...)
            context.startActivity(intent);
            return true; // Launched the activity successfully so block webview from loading
        }
    } else {
        // ...
    }
}

A: I came up with this, let me know if it works I'm not able to test it currently.
/**
 * Assumes that a browser is identified by having a IntentFilter match all http and https
 * protocols without matching either a host or path in the url.
 */
public boolean checkIfOtherBrowser(Context context, ResolveInfo info, Intent intent) {
    if (!intent.getScheme().equals("http") || !intent.getScheme().equals("https")) {
        return false;
    }

    IntentFilter filter = info.filter;
    if (filter != null) {
        int result = filter.match(
                context.getContentResolver(),
                intent,
                true,
                "somelogtag"
        );

        return (result & IntentFilter.MATCH_CATEGORY_SCHEME) > 0 && // Scheme was matched
                (result & IntentFilter.MATCH_CATEGORY_HOST) == 0 &&
                (result & IntentFilter.MATCH_CATEGORY_PATH) == 0; // But not for a specific host or path
    }

    return false;
}

Research resources used:

*

*https://github.com/mozilla-mobile/reference-browser/blob/master/app/src/main/AndroidManifest.xml#L108-L114

*https://developer.android.com/reference/android/content/IntentFilter#match(android.content.ContentResolver,%20android.content.Intent,%20boolean,%20java.lang.String)

*https://developer.android.com/training/app-links/deep-linking

A: Thanks to JensV I think I came up with a working solution. At least it seems to be able to distinguish between dedicated apps for links (Instagram, wikipedia etc) vs general purpose apps like other browsers.
public boolean areResolvedActivitiesOnlyBrowsers(Context context, Intent uriIntent) {
    PackageManager packageManager = context.getPackageManager();
    List<ResolveInfo> resolvedActivityList;

    final String scheme = uriIntent.getScheme();
    if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
        return false;
    }

    // Find all activities that could open the URI intent
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        resolvedActivityList = packageManager.queryIntentActivities(uriIntent, PackageManager.MATCH_ALL);
    }else{
        resolvedActivityList = packageManager.queryIntentActivities(uriIntent, 0);
    }

    // Check each activity for a match with the path part of the URI, if
    for (ResolveInfo activityResolveInfo : resolvedActivityList) {
        final int match = activityResolveInfo.match;
        boolean matchesPath = (match & IntentFilter.MATCH_CATEGORY_PATH) > 0;
        if(matchesPath){
            return false;
        }
    }
    return true;
}


text:
Q: Laravel Validation: grouped validation I am attempting to add validation to my request validator for a group of fields to make sure that the group of fields does not exceed a certain amount.  Once a user submits their form, they can view it in pdf form and my objective is to make sure that the collection of f_name, m_name and l_name does not run into another group of text on the pdf (thus making it illegible).
Essentially, I want something like this:
public function rules()
{
  return [
    'f_name' + 'm_name' + 'l_name' => 'max:50',
    ...
  ];
}

I have searched all over but the only questions I can find related are simply how to do validation.  If anyone knows how to group values in validation or links to previously asked questions, please let me know.  Thanks mates.

A: Laravel does not support multifields validation with one rules stack. Try write custom validator or reinvent the wheel:
public function rules()
{
    $fields = [
        "max: 50" => ["f_name", "m_name", "l_name"]
    ];
    $rules = [];

    foreach($fields as $rule => $fieldArray){
        if(is_array($fieldArray)){
            foreach($fieldArray as $field){
                $rules[$field] = $rule;
            }
        }
    }
  return $rules;
}

A: You need a custom validator so you can add several fields.
In your AppServiceProvider, something like this:
class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('groupedFieldsLongerThan50', function($attribute, $value, $parameters, $validator) {
            $f_name = array_get($this->data, $parameters[0]);
            $m_name = array_get($this->data, $parameters[1]);
            $l_name = array_get($this->data, $parameters[2]);

            if((strlen($f_name)+strlen($m_name)+strlen($l_name))<=50)
                  return true;

            return false;
        });
    }

    ...

Where you are declaring your rules add:
'f_name' => 'groupedFieldsLongerThan50:f_name,m_name,l_name'


text:
Q: how to translate ServletException to status code in jax-rs / jersey One of the controller resolution failed because of a dependency creation failure. That dependency is met with 403 from aws.  (I am assuming controllers are request scope and thus gets instantiated on every request)
Because of this a ServletException is thrown and results in 500. Is there a way to map the servletexception to a specific status code if the cause is of a certain exception and for some error message?
Error 500 javax.servlet.ServletException: A MultiException has 6 exceptions.  They are:
1. c.d.c.e.UserException: (Status Code: 403, Request ID:x, Extended Request ID: null)]
2. java.lang.IllegalStateException: Unable to perform operation: create on c.d.d.h.Home
3. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of c.d.d.s.c.Helper errors were found
4. java.lang.IllegalStateException: Unable to perform operation: resolve on c.d.d.s.c.Helper
5. java.lang.IllegalArgumentException: While attempting to resolve the dependencies of c.d.d.a.Resource errors were found
6. java.lang.IllegalStateException: Unable to perform operation: resolve on c.d.d.a.Resource