Migration: Office 2003 > 2010 | Windows XP > 7

Question: My company will be migrating from Windows XP/MS Office 2003 to Windows 7/MS Office 2010.
We will have a set of Excel and Access files and we should be sure that all works perfectly after the migration.
What I'm looking for, is a knowledge base where I can learn what issues I can encounter and their solutions.
Where can I find this? Of course, I'm expecting answers more precise than "MSDN" or "GOOGLE" ;)
Comment: There really is no answer to this, other than "test it, then test it some more". When you encounter a problem, sites like [su] and Googling around will help.
Answer: Well, Microsoft provides some instructions for transitioning from Windows XP to Windows 7, though they are mostly oriented towards end users.
The best way to learn about the issues that you might encounter during any migration, is to perform it on a sandbox/testing environment and resolve them there, before performing the task on live systems.
When you manage chaos for a living, there aren't any checklists with things that can go wrong. And even if they are, it's almost definite that you may encounter additional problems due to the unique characteristics of your installation.
Answer: The website for Microsoft documentation about performing Windows 7 upgrades (videos and whitepapers) is at the springboard site Windows XP to Windows 7 Migration Guide.  The migration guide for Office 2010 is located in the Office 2010 Resource Kit.  I would also note that this late in upgrade cycle you might also consider Office 365 and/or Google Apps to replace Office.
Additionally take a look at the MAP toolkit as a means to identify potential issues.
Answer: Download the Microsoft Deployment Toolkit 2010 and read the documentation that comes with it.  It's very thorough and covers migrations using the MDT alone, Windows Deployment Services, and integration with SCCM.  What you're trying to accomplish is pretty straightforward and MDT should have all of the answers you need and the preparation steps you need to take.
Comment: While MDT makes it pretty easy to deploy, really not sure how it helps to ensure his custom Excel and Access files will work in the new environment.
Comment: That's where the testing comes in.  If there's an issue with compatibility you have to sort that out before you do any migration.


Explain why any composite three-digit number is divisible by at least one of the primes 2,3,5,7,11,13,17,19,23,29,31.

Question: I am not really sure where to begin here. First idea that came to mind was proof by contradiction but I am not even sure if that is the right route.
Comment: Note: $\sqrt{1000} = 31.6$.  This is relevant!  How?
Comment: Hint:  if $n$ is composite, it has a nontrivial factor $≤\sqrt n$.
Answer: Let the composite number be $n$. Let it be factorized as $$n=ab$$ where $a,b\gt1$. This is possible because $n$ is composite.
Now, suppose the above is not true. Then, $a\gt31$ and $b\gt31$. Then,
$a\ge32$ and $b\ge32$. Then,
$$n=ab\ge32^2=1024$$
But $n\lt1000$. Thus, this is a contradiction. Every three digit composite number must be divisible by at least one prime $\lt32$. And the list mentions all such primes.
Comment: @bunsbun12 it does matter, all three-digit numbers are smaller than $1000$, that's where the contradiction is at
Comment: Okay thank you! So essentially I could use contradiction but it not using contradiction be valid as well?

Suppose n is a three digit composite number
since n is composite there are integers a ,b such that ab=n
and n has a prime divisor less than or equal to n^(1/2).
Therefore a or b must be primes greater than or equal to 31 because
sqrt(1000)=31.6

is this valid

OR am I better off going the contradiction route
Comment: So the fact that n is 3-digit doesn't matter? That's what's throwing me off about this proof
Comment: @bunsbun12 $n$ is 3 digit that's why $n\lt1000$
Comment: @bunsbun12 Your idea is correct. You just would need to show that at least one prime factor must be greater than $\sqrt{1000}$.
Answer: Let $n=a\cdot b\leq999$ with $1<a\leq b$. Then $a^2\leq a\cdot b\leq 999$, hence $1<a\leq31$. It follows that $a$, and therefore $n$, is divisible by a prime $\leq31$.


Is it possible to solve the equation $\cos{x}=\frac{2}{\pi}\int_{0}^{\infty}\frac{\cos{(xy)}}{y^2+1}dy$?

Question: Can one solve for $x$ the integral equation
$$\cos{x}=\frac{2}{\pi}\int_{0}^{\infty}\frac{\cos{(xy)}}{y^2+1}dy$$
The only thing I can think of is Taylor-expanding the cosine functions on both sides. If we do that, we find
integrability problems for the integral on the right near $\infty$.
Comment: In fact, the integral is very well-known and its value is $\frac{\pi e^{-|x|}}{2}$. So the equation becomes $\cos{x}=e^{-|x|}$ or i.e $\cos{x}e^{|x|}=1$. Clearly, $x=0$ is a solution, and if $x=x_0$ is a root so $x=-x_0$ is also a root. Then assume $x>0$. Now, i cant do anything.
Comment: Note that $$\cos x= \frac2\pi \int_{0}^{\infty}\frac{\cos{(xy)}}{y^2+1}dy= e^{-x}$$
Comment: @OnTheWay,  also $\cos x e^{x} = 1$ has a root on each segment of length $2\pi$ because of the intermediate value theorem.
Answer: As said in comments and answers, you have to find the zeros of
$$f(x)=\cos(x)\,e^x-1$$ Discarding the trivial $x=0$, the roots will be close to $(2n+1)\frac \pi 2$.
Expanding as series
$$f(x)=-1+\sum_{k=1}^\infty \frac{2^{k/2} e^{\pi  \left(n+\frac{1}{2}\right)} \sin
   \left(\frac{\pi  k}{4}\right) \cos (\pi  (n+1))}{k!}\,\,\left(x-  (2 n+1)\frac \pi 2\right)^k$$
Truncating to some order and using series reversion
$$x_{(n)}= (2 n+1)\frac \pi 2 -(-1)^n e^{-(2 n+1)\frac \pi 2 }-e^{-(2 n+1)\pi}-(-1)^n \frac 53e^{-(2 n+1)\frac {3\pi} 2 }+\cdots$$
Using the above and, on purpose, a ridiculous number of decimal places
$$\left(
\begin{array}{ccc}
n & \text{estimate} & \text{solution} \\
 0 & \color{red}{1.}30473068047848008109384008145 &
                 1.29269571937339838116818912162 \\
 1 & \color{red}{4.7212927}8013366831230740888289 &
                 4.72129275884768621662192954770 \\
 2 &  \color{red}{7.853593279971}32396845634670331 &
                  7.85359327997124820007989934704 \\
 3 &  \color{red}{10.99559106306438158}32499112601 &
                  10.9955910630643815829859174825 \\
 4 &  \color{red}{14.13716621620629242513549}21542 &
                  14.1371662162062924251354912335 \\
 5 &  \color{red}{17.2787596260716731062494426607} &
                  17.2787596260716731062494426607 \\
\end{array}
\right)$$
Edit
We could do better building the simple $[2,2]$ Padé approximant of $\cos(x)\, e^x$ around  $(2n+1)\frac \pi 2$. Letting
$$x=(2n+1)\frac \pi 2-t$$ it just remains to solve the quadratic equation
$$\left(1+3 (-1)^n e^{\pi  \left(n+\frac{1}{2}\right)}\right) t^2+3 \left(1-2 (-1)^n e^{\pi  \left(n+\frac{1}{2}\right)}\right) t+6=0$$
Repeating the same calculations as above with the same ridiculous number of decimal places
$$\left(
\begin{array}{ccc}
n & \text{estimate} & \text{solution} \\
 0 & \color{red}{1.2926}3854652920246811113073673 &
                 1.29269571937339838116818912159 \\
 1 & \color{red}{4.72129275884}891607435040801353 &
                 4.72129275884768621662192954770 \\
 2 & \color{red}{7.853593279971248}19988350123943 &
                 7.85359327997124820007989934704 \\
 3 & \color{red}{10.995591063064381582985917}5120 &
                 10.9955910630643815829859174825 \\
 4 & \color{red}{14.1371662162062924251354912335} &
                 14.1371662162062924251354912335 \\
\end{array}
\right)$$
Doing the same with the $[3,3]$ and $[4,4]$ Padé approximants, we face a cubic and a quartic polynomial in $t$ giving respectively (with nasty radicals) for the first root  $\color{red}{1.292695}978$ and $\color{red}{1.2926957}201$.
Comment: Did  you write all these numbers? Omg.
Comment: This is great. Can we show that the zero must be close to $(2n+1)\pi/2$ ?
Comment: @Medo You are looking for $x>0$ such that $\cos(x)=e^{-x}$. Now $e^{-x} \approx 0$ if $x\gg 0$, so the roots must be closer and closer to the roots of $\cos(x)=0$, i.e., $(2n+1)\pi/2$.
Answer: Absolutely possible. It is solved for general case $\cos{tx}$ here using Laplace transform in section "2021". Basically, I found hundreds of such integrals in that web alints.com.


Making some Views Exposed Filters auto-submit but not others

Question: Background
I'm using Views and Better Exposed Filters and Search API. I have my filters set to 'autosubmit' so when a user makes a change to a filter it auto-updates the search result.
What I want to accomplish
This is cool but I only want the results to auto-update when CERTAIN selections are made. Otherwise I want the user to have to click the 'search button'.
Example
For example, I want the user to have to click the 'search button' for some things such as the text boxes and some of the radio buttons, but for SOME of the checkboxes I want the search results to auto-update when a new selection is made.
Question
Is this possible programmatically (or I suppose in Views itself) and if so, how?
Answer: Gonna add my 2 cents too on the topic, since I recently did my reading-into this topic (autosubmit for exposed filters).
Related:
This answer here answers a very similar problem => https://drupal.stackexchange.com/a/198274/57183.
Usefull things to know
The most important piece of relevant documentation lies inside the ctools/js/auto-submit.js file of CTools, at the top of that file.
Form API programming
Following that documentation, you should use the FAPI to programmatically do one of the following:

Exclude the specific filters that you don't want to be trigger an autosubmit (if you have autosubmit active, like in your case):

If you want to exclude a field from the ctool-auto-submit-full-form
  auto submission, add the class ctools-auto-submit-exclude to the form
  element. With FAPI, add:
'#attributes' => array('class' =>
  array('ctools-auto-submit-exclude')),

Include the filters that you want to trigger an autosubmit (if you have autosubmit deactivated, not your case)

On gadgets you want to auto-submit when changed, add the
  ctools-auto-submit class. With FAPI, add:
'#attributes' => array('class' => array('ctools-auto-submit')),

After that, you already have the functionality you need.
Example to the Example
Following your example here is some example code (with inline comments):
function somemodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // Assumption: Auto-submit is activated via the Views/BEF configuration for all filters
  // Therefore, we will exclude "the text boxes and some of the radio buttons..."

  $exposed_filters_to_deactivate = array(
    'full_text_search', // a text field
    'field_categories', // a radio button
  );

  foreach($exposed_filters_to_deactivate as $exposed_filter_name) {

    // This will disable auto-submitting the form for our filter element
    $form[$exposed_filter_name]['#attributes'] = array('class' => array('ctools-auto-submit-exclude'));

  }

}

This should do it, now the exposed filters full_text_search' and 'field_categories' will not trigger an autosubmit event, all other filters will.
Hope this helps!
Addendum (follow-up question):
To get specific checkboxes from a BEF-checkbox group to trigger a form submit, you need to do the following:
Modify you form_alter implementation:
function somemodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // Assumption: Auto-submit is activated via the Views/BEF configuration for all filters
  // Therefore, we will exclude "the text boxes and some of the radio buttons..."

  $exposed_filters_to_deactivate = array(
    'full_text_search', // a text field
    'field_categories', // a radio button
    'field_areas_of_interest_checkbox', // a BEF-checkboxes widget
  );

  foreach($exposed_filters_to_deactivate as $exposed_filter_name) {

    // This will disable auto-submitting the form for our filter element
    $form[$exposed_filter_name]['#attributes'] = array('class' => array('ctools-auto-submit-exclude'));

  }

  // This is the name of the select values and their target url
  $bef_checkboxes_autosubmit = array(
    '#area_of_interest_checkbox_1',
    '#area_of_interest_checkbox_3',
  );

  // This will attach a javascript to the checkboxes element
  $form['field_areas_of_interest_checkbox']['#attached']['js'][] = drupal_get_path('module', 'somemodule') . '/somemodule.js';
  $form['field_areas_of_interest_checkbox']['#attached']['js'][] = array(
    'data' => array(
      'bef_checkboxes_autosubmit' => array(
        'form_id' => $form['#id'],
        'checkboxes_ids' => $bef_checkboxes_autosubmit,
      )
    ),
    'type' => 'setting'
  );
}

Now, you also need a javascript file (somemodule.js) that will look sth like this:
(function($){

Drupal.behaviors.BEFCustomRedirect = {
  attach: function(context, settings) {
    $(settings.bef_checkboxes_autosubmit.checkboxes_ids).each( function( idx ) {
      $('.ctools-auto-submit-exclude.form-checkboxes input' + this).change(function() {
        $('#' + settings.bef_checkboxes_autosubmit.form_id).submit();
      });
    });
  }
}

})(jQuery);

Comment: This worked great, thank you! Follow up question: I have an exposed filter called 'field_areas_of_interest_checkbox' and it has (not surprisingly) a bunch of checkboxes. I want SOME of them (but not all) to have the same functionality...do you have a suggestion for how I'd target a specific checkbox within an exposed filter using your code? I notice they all have different ID attributes in the HTML.
Comment: Hey @Sage, I edited my answer, give it a try.
Comment: See the answer by @vector_ray for an example that works in 2024. Also be sure to wrap all the code inside the function with an if statement on `$form['#id']` such as `if ($form['#id'] === 'views-exposed-form-central-event-calendar-page-1') {`. The code as written will run for every view on your site. You will want to limit this to only the exposed form for your particular view. For whatever reason `$form_id` is not the same as `$form['#id']`, so don't compare to that.
Answer: Slight modification to existing accepted answer due to changes in BEF.
function somemodule_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

  // Assumption: Auto-submit is activated via the Views/BEF configuration for all filters
  // Therefore, we will exclude "the text boxes and some of the radio buttons..."

  $exposed_filters_to_deactivate = array(
    'full_text_search', // a text field
    'field_categories', // a radio button
  );

  foreach($exposed_filters_to_deactivate as $exposed_filter_name) {

    // This will disable auto-submitting the form for our filter element
    $form[$exposed_filter_name]['#attributes'] = array('data-bef-auto-submit-exclude' => '');

  }

}

Comment: Thanks! This is still the correct answer. Also be sure to wrap all the code inside the function with an if statement on `$form['#id']` such as `if ($form['#id'] === 'views-exposed-form-central-event-calendar-page-1') {`. The code as written will run for every view on your site. You will want to limit this to only the exposed form for your particular view. For whatever reason `$form_id` is not the same as `$form['#id']`, so don't compare to that.
Answer: For selected exposed filter auto-submit, you can use jQuery for those filters something like :
// Wait until document fully loaded
jQuery(document).ready(function($) {
    // Check if the filter exists
    if($('.views-exposed-form select').length){
        // Your change function
        $('.views-exposed-form select').change(function() {
            // Submit the form
            $(this).parents('form').submit();
        });
    }
});

Answer: You can use jQuery to automatically click something (in your case the submit button) when you click a certain div class or id.
For Example:
(function($) {
  $( "#clickme, #clickme2" ).click(function() {
     $('.submit-form')[0].click();
  });
})(jQuery);

JS Fiddle Example


How to format the date from dropdown list?

Question: I would like to ask how to change the format of month for selectmonth into "September" instead of 09
function myFunction() {
var d = new Date();
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var x = month[d.document.getElementById("selectmonth").value];
var y = document.getElementById("selectyear").value;
document.getElementById("demo").innerHTML = "Quick summary for " + x + y ;
}

Comment: Do you mean you want the drop-down itself to display "January", "February", etc., or you just want to change the selected value within the function shown?
Comment: @nnnnnn I jus want to change the selected value within the function shown
Comment: @nnnnnn  my dropdown itself ady display "January", "February", etc.
Comment: @nnnnnn  but when i got the value "09" instead of "September"
Comment: Does the code that you just edited in not do what you want?
Comment: @nnnnnn  I meant I wan to format the date I got from dropdown list
Comment: So why did you edit your question to add what looks like code copy/pasted from the first answer below, except with changes to make it not work? Anyway, you said before that the dropdown already displays the month names, presumably like `October`, so in that case you can get the text directly from the option element as in [my answer](http://stackoverflow.com/a/40167751/615754).
Answer: I think you should change the value
of his own from the html tag selectmonth.

window.onload = function(){
    document.getElementById("select").onchange = function () {
        var get={};
        get.x=function () {
            return document.getElementById("selectmonth").value;
        }
        get.y=function () {
            return document.getElementById("selectyear").value;
        }
        document.getElementById("demo").innerHTML =
                "Quick summary for " + get.x() + get.y();
    }
}

    <select id="selectmonth">
        <option name="month" value="">Select...</option>
        <option name="month" value="January">January</option>
        <option name="month" value="February">February</option>
        <option name="month" value="March">March</option>
        <option name="month" value="April">April</option>
        <option name="month" value="May">May</option>
        <option name="month" value="June">June</option>
        <option name="month" value="July">July</option>
        <option name="month" value="August">August</option>
        <option name="month" value="September">September</option>
        <option name="month" value="October">October</option>
        <option name="month" value="November">November</option>
        <option name="month" value="December">December</option>
    </select>
    <select id="selectyear">
        <option name="year" value="2016" selected>2016</option>
        <option name="year" value="2017">2017</option>
        <option name="year" value="2018">2018</option>
    </select>

Want to help you.
Answer: You said in a comment that your select option displays the month names, so presumably that means your options are like:
<option value="09">September</option>

If so, then you can get the selected item's value and display name like this:
var monthDropdown = document.getElementById("selectmonth");
var x = monthDropdown.value
var monthName = monthDropdown.options[monthDropdown.selectedIndex].textContent;

In context:

function myFunction() {
  var monthDropdown = document.getElementById("selectmonth");
  var x = monthDropdown.value
  var monthName = monthDropdown.options[monthDropdown.selectedIndex].textContent;
  var y = document.getElementById("selectyear").value;
  document.getElementById("demo").innerHTML = "Quick summary for " + monthName + " " + y + " (the month number was " + x + ")";
}
document.querySelector("button").addEventListener("click", myFunction);
<select id="selectmonth">
  <option value="01">January</option>
  <option value="02">February</option>
  <option value="03">March</option>
  <option value="04">April</option>
  <option value="05">May</option>
  <option value="06">June</option>
  <option value="07">July</option>
  <option value="08">August</option>
  <option value="09">September</option>
  <option value="10">October</option>
  <option value="11">November</option>
  <option value="12">December</option>
</select>
<input id="selectyear" value="2016">
<button>Test</button>

Answer: function myFunction() {
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var x = month[parseInt(document.getElementById("selectmonth").value,10)];
var y = document.getElementById("selectyear").value;
document.getElementById("demo").innerHTML = "Quick summary for " + x + y ;
}

Comment: instead of getMonth i get the month from dropdown list
Comment: you must parseInt your month value because it's contain value like '09'. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Answer: Just create an array that contains all the months and reference the array by index.

function myFunction() {

  var month = ["January",
               "February",
               "March",
               "April",
               "May",
               "June",
               "July",
               "August",
               "September",
               "October",
               "November",
               "December"]

  var x = document.getElementById("selectmonth").value;
  var y = document.getElementById("selectyear").value;

  document.getElementById("demo").innerHTML = "Quick summary for " + month[x - 1] + y ;
}
<input type="text" id="selectmonth" value="9"/>
<input type="text" id="selectyear" value="2016"/>

<input type="button" onclick="myFunction()" value="TestMe" />


FPR (false positive rate) vs FDR (false discovery rate)

Question: The following quote comes from the famous research paper Statistical significance for genome wide studies by Storey & Tibshirani (2003):

For example, a false positive rate of 5% means that on average 5% of
  the truly null features in the study will be called significant. A FDR (False Discovery rate) of 5% means that among all features called significant, 5% of these
  are truly null on average.

Can somebody explain what that means  using a simple numerical or visual example? I am having hard time understanding what it means. I've found various posts on FDR or FPR alone, but haven't found any where a specific comparison was made.
It would be especially good if someone expert in this area could illustrate situations where one is better than the other, or both are good or bad.
Answer: I'm going to explain these in a few different ways because it helped me understand it.
Let's take a specific example. You are doing a test for a disease on a group of people. Now let's define some terms. For each of the following, I am referring to an individual who has been tested:
True positive (TP): Has the disease, identified as having the disease
False positive (FP): Does not have the disease, identified as having the disease
True negative (TN): Does not have the disease, identified as not having the disease
False negative (FN): Has the disease, identified as not having the disease
Visually, this is typically shown using the confusion matrix:

The false positive rate (FPR) is the number of people who do not have the disease but are identified as having the disease (all FPs), divided by the total number of people who do not have the disease (includes all FPs and TNs).
$$
FPR = \frac{FP}{FP + TN}
$$
The false discovery rate (FDR) is the number of people who do not have the disease but are identified as having the disease (all FPs), divided by the total number of people who are identified as having the disease (includes all FPs and TPs).
$$
FDR = \frac{FP}{FP + TP}
$$

So, the difference is in the denominator i.e. what are you comparing the number of false positives to?
The FPR is telling you the proportion of all the people who do not have the disease who will be identified as having the disease.
The FDR is telling you the proportion of all the people identified as having the disease who do not have the disease.
Both are therefore useful, distinct measures of failure. Depending on the situation and the proportions of TPs, FPs, TNs and FNs, you may care more about one that the other.

Let's now put some numbers to this. You have measured 100 people for the disease and you get the following:
True positives (TPs): 12
False positives (FPs): 4
True negatives (TNs): 76
False negatives (FNs): 8
To show this using the confusion matrix:

Then,
$$
FPR = \frac{FP}{FP + TN} = \frac{4}{4 + 76} = \frac{4}{80} = 0.05 = 5\%
$$
$$
FDR = \frac{FP}{FP + TP} = \frac{4}{4 + 12} = \frac{4}{16} = 0.25 = 25\%
$$
In other words,
The FPR tells you that 5% of people of people who did not have the disease were identified as having the disease. The FDR tells you that
25% of people who were identified as having the disease actually did not have the disease.

EDIT based on @amoeba's comment (also the numbers in the example above):
Why is the distinction so important? In the paper you link to, Storey & Tibhshirani are pointing out that there was a strong focus on the FPR (or type I error rate) in genomewide studies, and that this was leading people to make flawed inferences. This is because once you find $n$ significant results by fixing the FPR, you really, really need to consider how many of your significant results are incorrect. In the above example, 25% of the 'significant results' would have been wrong!
[Side note: Wikipedia points out that though the FPR is mathematically equivalent to the type I error rate, it is considered conceptually distinct because one is typically set a priori while the other is typically used to measure the performance of a test afterwards. This is important but I will not discuss that here].

And for a bit more completeness:
Obviously, FPR and FDR are not the only relevant metrics you can calculate with the four quantities in the confusion matrix. Of the many possible metrics that may be useful in different contexts, two relatively common ones that you are likely to encounter are:
True Positive Rate (TPR), also known as sensitivity, is the proportion of people who have the disease who are identified as having the disease.
$$
TPR = \frac{TP}{TP + FN}
$$
True Negative Rate (TNR), also known as specificity, is the proportion of people who do not have the disease who are identified as not having the disease.
$$
TNR = \frac{TN}{TN + FP}
$$
Comment: +1. It could make sense to adjust the numerical example so that FPR = 5% because that's what you are going to have if you use p<0.05 as  criterion (assuming the test has correct size). Or 1% if p<0.01, whatever. Pointing out this connection might be helpful for some readers.
Comment: Writing this 2 years ago, I really did not expect these concepts to become familiar to the public in just a short while...
Comment: @amoeba Thank you, this is a good idea. I will try to do that later.
Comment: Just to add a little bit to the question of why the distinction is important: suppose you got a positive test result from your doctor, then in the given example, with 25% chance this result is wrong and you don't have actually have that disease. So, the FDR is what really matters to the individual undergoing some test, not the FPR...
Answer: You should examine the table in https://en.wikipedia.org/wiki/Confusion_matrix. Please note FPR is vertically placed while FDR is horizontal.

FP happens if your null hypothesis is true but you reject it
FD happens if you predict something significant but you shouldn't
Comment: I know that but I am specifically interested in comparison like if you could help explain that concept with some numbers and visualization to support your numbers that would be very interesting.


Gains in running a docker container on the same OS type?

Question: Are there significant gains in running a docker container based on a certain OS, on the same OS type and version?! For example, running a container based on a certain version of Ubuntu, on an Ubuntu server (of the same version), v.s. a Debian/CentOS/CoreOS server?
Notwithstanding, that upgrading the servers' and containers' OS in lockstep, might not be how ops always tend to go on in reality.
Answer: There shouldn't be.
Docker and other linux container technologies share access to the kernel and have their own, entirely separate filesystems from the host. Therefore, running an arbitrary container on the same hardware and kernel but two different distros should not in theory make any difference. That is what makes containers so powerful, they are reliably identical across a wide variety of hosts.
Comment: For different OSes between the container and the host there is no difference, but there is a memory advantage in running many containers from the same image (or with many layers in common), with AUFS. Then shared libraries pages will be reused across containers and if you start having hundreds of Apache containers that could become noticeable.
Source: https://groups.google.com/forum/#!topic/docker-dev/NOeA2YHl1sU


Shapiro test and transformation

Question: I am playing with shapiro.test from R and checking for non-normality of error variance.
> shapiro.test(residuals(fit))

        Shapiro-Wilk normality test

data:  residuals(fit)
W = 0.9525, p-value = 0.0003303

> shapiro.test(residuals( lm( sqrt(V1)~V2 ,data=market) ) )

        Shapiro-Wilk normality test

data:  residuals(lm(sqrt(V1) ~ V2, data = market))
W = 0.8895, p-value = 5.89e-08

> shapiro.test(residuals( lm( log(V1)~V2 ,data=market) ) )

        Shapiro-Wilk normality test

data:  residuals(lm(log(V1) ~ V2, data = market))
W = 0.7698, p-value = 1.95e-12

> shapiro.test(residuals( lm( 1/(V1) ~ V2 ,data=market) ) )

        Shapiro-Wilk normality test

data:  residuals(lm(1/(V1) ~ V2, data = market))
W = 0.3954, p-value < 2.2e-16

The p-value for normality test is <0.001. So I did a transformation on V1, log(Y), inverse(Y) and sqrt(Y) but their p-values gets even smaller. Does this mean that these transformations don't work? I also did a boxcox transformation, and I get p-value of 0.3. So in that case, boxcox is the best remedy only in this case? Or should I just use boxcox in the future for remedy of non-normality? The rest of the usual transformation methods are useless?
Answer: 1) Why are you transforming the residuals?
2) why are you testing them for normality?
3) what do you mean by 'did a boxcar'? [Resolved]
4) what do the data look like? e.g. what does a  QQ plot show?
--
Log, inverse and sqrt are all Box-Cox transformations (up to linear rescaling). Transformation may not be the best idea, but taking transformation as a given, rather than just throw transformations and data and hoping one sticks, find out what your data look like!
Comment: To clarify one of my earlier points, if your residuals are non-normal, and for whatever reason you decide that transformation is called for, it will be the data, not the residuals that you transform.
Comment: hi, 1) because there's a non-normal behaviour. 2) just an exercise. 3) boxcar transformation. 4) because this is just a simple exercise, what I need to do is just do my own "analysis". There is no "right or wrong" answers.
Comment: What's a boxcar transformation? Are you talking about some form of [PIT](http://en.wikipedia.org/wiki/Probability_integral_transform)? [Rank transformation](http://en.wikipedia.org/wiki/Ranking#Ranking_in_statistics)? Something else? You may be doing 'just an exercise' - and you might test for the practice whether it makes sense or not, but it still may be worth pondering whether it makes sense to test it. Can you give some kind of idea for (4) above?
Comment: hi thanks for replying. sorry i mistyped, its boxcox transformation . http://pareonline.net/pdf/v15n12.pdf

Shapiro test and transformation


Prove $L$ is context free if $L_1$, $L_2$, $L_3$ are regular by building a suitable grammar

Question: Given $L_1$, $L_2$, $L_3$ are regular, prove that:
$$L=\{w_1w_2w_3\space|\space w_i\in L_i\space \land\space|w_1|+|w_2|=|w_3| \}$$
is context free by building a suitable context free grammar. I know that each $L_i$ has Gi- a linear right or linear left grammar that creates it, and i thought of using it like so(it'll be a bit informal):
We'll define a set of deriving rules like so:
$P_{i,k}=\{P\in Gi\space|\space $there exist a chain of derivations starting is Si and ending with $w :|w|=k\}$
And define a set of deriving rules for G, that grammar that creates L:
$$P=\{P_{1,|w1|},P_{2,|w2|},P_{3,|w3|}| \exists wi\in L(Gi):|w1|+|w2|=|w3|\}\bigcup \{S->S_1S_2S_3\}$$
where Si are the starting variables of Gi and S of G. Will this work? or am i missing something?
Answer: As far as I understand the solution you propose, I think it will not work. Already with the rule $S\rightarrow S_1S_2S_3$ you loose any chance to use the three regular grammars in a coordinated kind of way.
A possible solution is this: from the point between $w_2$ and $w_3$ you generate $w_3$ from right to left and $w_1w_2$ from left to right. So you want a left-linear grammar for $L_3$, right-linear grammars for the other two. In every step you generate exactly one terminal of $w_3$ and one of $w_1w_2$. Thus in the end the two parts are of equal length.
Formally, let $G_i := [N_i,T_i,P_i,S_i]$ be the regular grammars for the three languages, where $G_3$ is left-linear, the other two right linear. Further, every production generates exactly one terminal, and the sets of non-terminals are disjoint.
The new grammar is $$[(N_1\times N_3) \cup (N_2 \times N_3), T_1\cup T_2 \cup T_3, P, [S_1S_3]]$$ where $$P:= \{[XY]\rightarrow u[ZW]v :  X\rightarrow uZ\in P_1\cup P_2 \wedge Y\rightarrow Wv \in P_3\}\} \cup$$
$$ \{ [XY]\rightarrow u[S_2W]v :  X\rightarrow u\in P_1 \wedge Y\rightarrow Wv \in P_3 \} \cup $$
$$\{ [XY]\rightarrow uv :  X\rightarrow u\in P_2 \wedge Y\rightarrow v \in P_3 \}.$$
The second component of the rule set switches from $G_1$ to $G_2$ when a terminating rule (without further non-terminal) from $G_1$ is applied. The last component terminates the derivation. $u$ and $v$ are always single terminals.
Comment: I don't understand how should i know what terminals they generate? All i know is their starting variables and that's it. So i couldn't write something like: S->aAbBCc, and also, why does it have to be a left linear grammar for L3?
Comment: To generate $w_3$ from right to left, the non-terminal has to move from the right end to the left one; so the grammar has to be left-linear. I add some details on the rule set.


JAXB "rename" property from a parent class in a child class

Question: If I have parent class A
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
class A {
    private int id;
}

and a child class B
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
class B extends A {
    private int x;
    private int y;
    private int z;
}

In the system there are also many classes C, D, X, Y, Z which extend class A.
I would like to "rename" the property A#id to B#somethingId only for instances of B.
My idea was to redeclare field id and to use XmlTransient but it is not working, I still have "id" in when marshalling B:
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
class B extends a {
    private int x;
    private int y;
    private int z;

    public Long getSomethingId() {
        return id;
    }

    @XmlElement
    public void setSomethingId(Long id) {
        super.setId(id);
    }

    public Long getId() {
        return super.getId();
    }

    @XmlTransient
    public void setId(Long id) {
        super.setId(id);
    }

}

The output is

          <id>
          <somethingId>
          ...

Any ideas?
Answer: Try this:
@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlRootElement(name= "B")
public class B extends A {
    private int x;
    private int y;
    private int z;

    @Override
    public int getId() {
        return super.getId();
    }

    @Override
    @XmlElement(name = "somethingId")
    public void setId(int id) {
        super.setId(id);
    }

}

and
@XmlType
@XmlAccessorType(XmlAccessType.PROPERTY)
public class A {
    private int id;

    public int getId() {
        return id;
    }

    @XmlTransient
    public void setId(int id) {
        this.id = id;
    }
}

Notice the @XmlAccessorType is set to XmlAccessType.PROPERTY.
Or you could also do it with XmlAccessType.FIELD, like this:
@XmlType
@XmlAccessorType(XmlAccessType.FIELD)
public class A {
    @XmlTransient
    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

and
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name= "B")
public class B extends A {
    private int x;
    private int y;
    private int z;

    @Override
    public int getId() {
        return super.getId();
    }

    @Override
    @XmlElement(name = "somethingId")
    public void setId(int id) {
        super.setId(id);
    }

}

Edit to reply to the comment:
You can of course keep the id in the classes you want. For example, following the second approach, adding a class like:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name= "C")
public class C extends A {
    private int j;
    private int k;

    @Override
    public int getId() {
        return super.getId();
    }

    @Override
    @XmlElement(name = "id")
    public void setId(int id) {
        super.setId(id);
    }

}

would work just fine. If I use a simple main to demo it:
public static void main(String[] args) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(B.class, C.class);
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            B b = new B();
            b.setId(1);
            marshaller.marshal(b, System.out);

            System.out.println();

            C c = new C();
            c.setId(2);
            marshaller.marshal(c, System.out);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

Would give you the following result:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

    <x>0</x>
    <y>0</y>
    <z>0</z>
    <somethingId>1</somethingId>

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<C>
    <j>0</j>
    <k>0</k>
    <id>2</id>
</C>

Or is it something you don't like in this approach?
Comment: Hi @RockyMM, yes I got the feeling that you may didn't like the repetition. Tried to find a way to avoid it, but didn't make it yet.
Comment: Thank you for this. I've thought of this, but the issue is that I have 10 or so more subclasses of `A` where I do need the property with the name `id`.
Comment: I will reply in the post, for convenience
Comment: Hey @mart, that works. But the trouble with it is that any developer creating a new subclass of `A` would have to take care and implement `id`. I feel that the default value should be specified in `A`.

What I'm looking for is something along `com.fasterxml.jackson.annotation.JsonIgnoreProperties` equivalent in JAXB.


Set text in TextView in custom dialog

Question: I want to set the text in a TextView contained in a custom dialog programmatically, so that I can use Html.fromHtml. In what function should I call setText? I've tried doing it in onCreateDialog, but this does not actually change the text.
public class InfoDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(R.layout.infodialog, null));

        TextView textView = (TextView) getActivity().findViewById(R.id.info);
        textView.setText(Html.fromHtml("
Text has been correctly set
"));
        ...

Answer: Try this:
View content =  inflater.inflate(R.layout.infodialog, null);
builder.setView(content);
TextView textView = (TextView) content.findViewById(R.id.info);

Comment: Kind of late but you could also use `TextView tv = myDialog.findViewById(R.id.myDialogsTextView)`
Comment: Thanks! So I guess the issue is that `Activity.findViewById()` only looks in the layout passed to the activity's `setContentView()` method, which in my case did not include the View used by the dialog.
Comment: @Smitty-Werben-Jager-Manjenson kind of late too but i feel like your answer is more intuitive to me and i am using that for a similar issue of mine. thanks!

Set text in TextView in custom dialog


Sight reading chords—pay attention to bass, treble, or none of the above?

Question: I am currently a very novice piano player trying to get by with Czerny's Op. 599 Practical Exercises for Beginners. As suggested, I'm playing the exercises by sight reading the notation, minimizing the amount of time I spend looking at the actual keys. I've found that the generally easiest way to do this for the mostly monophonic melodies (especially when transposing keys) is to keep track of the intervals between notes/scale degrees, forgoing any absolute identification of individual notes.
However, how am I supposed to adapt this method to full-blown chords? For example, in the following exercise, I can see that the featured chords are mostly just major and minor triads in various inversions.

I can more or less instantly put my hand in the desired shape when I see e.g. a first-inverted triad, but I don't know where to put it. When the chords are very similar in pitch or shape, I can usually manage. From bars 5 to 8 in the treble, I might read: 2nd inversion with C bass, to root position with C bass (just reshape hand), to root position with B bass (1 scale degree drop), to 2nd inversion with G bass (2 scale degree drop and reshape hand). However, this seems finnicky, artificial, and still quite hard to do in real time. It can also obscure quite obvious transformations, such as bar 1 to bar 2 being 1st degree to root position C major triads, rather than "1st inversion triad with E bass, to root position with C bass."
Experienced sightreaders, from what I hear, "just do it" without thinking. But what sort of mental activity should a beginner be undergoing when practicing this sort of thing?
Answer: It appears that you are focusing too much on the theory aspect of the chords, rather than executing it.
Let's take right hand in bar 5 to 7 as an example. Going from bottom to top, the second note has a distance of 4 above the note below, and the top note is 3. (They are perfect fourth and major third, but let's forget theory for now.) Going to bar 6, the bottom note stays the same, the middle note "descends" one step lower, and the top note also "descends" one step lower. For the next one (bar 7), transpose each note down one step.
Focus on the notes and the execution. I'd read it as "CFA" -> "CEG" -> "BDF", not "2nd inversion of F major" -> "root of C major" -> "root of subtonic".
Once you've identified the bottom note (C), you'll play the entire chord correctly. The choice of whether to start from the bottom or top is arbitrary, although you'd tend to start with a note you're familiar with, especially for chords with lots of extra staff lines (i.e. very high or very low for the clef).
Comment: I think you've just described the same thing I did, but avoided adding the specific names in post (as I did). I'm not actually thinking in my head "2nd inversion of F major," but rather "(chord shape I recognize) over (this bass note that's 2 lower than the previous chord's bass)." But I figured that would have been hard to describe. I'm not generally keeping track of any specific notes like "CFA" or "BDF" however, or even scale degrees. At any rate, it sounds like you're advocating for me to stick with the method I'm already trying, despite my current issues with it.
Answer: Looking purely at r.h (as the whole chord with all 6 notes will be called a different inversion), calling the first one '1st inv. with E in the bass' is tautological.
Since all the triads are in close position, and you can recognise which of the three 'inversions' each is, mainly by seeing where the third part of the chord is (on consecutive lines/spaces), then by choosing either the topmost or lowest note, the other two should automatically (after a while) slot into their appropriate places. I feel that looking at the lowest note, which also names the inversion, may be better, although if you're reading block chords under a melody, the highest note is the more important to be heard.
Another way may be to go from one triad to another, noting the common note between them.In bars 1 and 2 - E and G. In bars 5 and 6, just the C, heralding a change of chord.
Answer: I think what you are doing is already ok. You are reading the chord vertically.
What I would add is also looking for the horizontal lines. What you could do is only playing the top line but with the correct (!) finger of the right hand. You can also do it with the bass line and the correct finger of the left hand. Now you can play both these lines together (bass and melody) without any of the inner voices. You can also look at the bottom notes of the chord in the right hand and play those as a single line, the same with the top notes of the left hand, and so on. You can then combine the inner most voices... and so on and on.
Answer: Full disclosure up front: I'm just a beginner with sight reading too.
It seems to me you are basically on the right track, because you understand to focus on relative movement instead of trying to read each letter name of each chord.
I think you can dispense with mentally identifying inversion name, scale degrees, etc. if it distracts your concentration from reading the relative movement.
Personally I look for the common tones first and then step-wise movement. Along those lines I try to determine when a movement is simply an arpeggiation of a chord. Again, it seems like you are already doing this.
But this is what isn't clear yet. Are you being disciplined about your fingering? Are you thinking about/practicing good fingering especially regarding shifts of hand position?
Let's consider bars 2,3,4 in the right hand. Disregarding the true bass in the left hand those chords are: I V6/4 I6/3. Notice that the "G5" is repeated for all three chords.
Now this is what I think is an important distinction to make:
You could look at the bottom notes of the right hand chords - C5, D5, E5 - an see a nice smooth step-wise movement and then build root position, 2nd inversion, and 3rd inversion above those notes. That seems reasonable, but compare that with the following:
The G5 is shared by all three chords, but the finger that plays that repeated note changes for each chord. Instead of focusing on the C5, D5, E5, focus on G5 (finger 4) G5 (finger 3) G5 (finger 2) and then make the necessary chord shape relative to the finger playing G5.
What's the difference? Notice that the fingering for C5, D5, E5 is 1, 1, 1. Normally that small scale bit would be fingered 1, 2, 3. In this sense 1, 1, 1 is bit contrary to simple fundamental fingering. However, the repeated notes G5, G5, G5 changes the finger for each note. That finger change is a fundamental fingering. My personal feeling is that it is better to focus on that fundamental fingering.
If that kind of thinking is applied to other bars, we can see that in bars 1 and 2 it isn't a drop of a third E5 to C5 with the chord built above, but a repetition of E5+G5 and E5+G5 utilizing a fingering change.
At this point we can now ask an important question regarding our technique: are we comfortable playing repeated notes with finger changing? If not, start practicing that with single notes and double notes.
A similar point could be made regarding playing scales in thirds in one hand and bars 5-9. Notice the top two notes descend by thirds for the whole four bars. If playing scales in thirds is a technique you know, you could apply it to executing that passage.
If there is any validity to what I just described, then sight reading skill will be supported by good, disciplined fingering. Playing repeated notes with changing fingers, scales in thirds, "silent" finger changes on a key, etc. need to be practiced. When good fingering becomes automatic, sight reading movements should start to become automatic more easily.
Comment: Thanks; you've given me a lot to look into if I continue to have problems!
Comment: "It seems to me you are basically on the right track, because you understand to focus on relative movement instead of trying to read each letter name of each chord." I think you underestimate enormously the capacity of good sight readers to actually read the notes themselves at speed, even in chords.
Comment: @Tim, I didn't say good sight readers can't or don't read the note letters, but that the main focus is on relative movement and fingering.
Comment: @MichaelCurtis, I know :-), and what I try to say is that for good sight readers it's a lot more about a direct connection between the dot on the paper and the key on the piano than about going 'two notes higher, one note lower'.
Comment: @Tim, I recently tried reading Satie's 1st Saraband, the movements look so simple, but the spellings are a nightmare!
Answer: A:  All of the above and more.
Sight reading is a combination of four or five skills.  It is not something you can work on in isolation.
The first component which you should get out of the way is technique.  You need to have the technical facility to actually be able to play what you are reading.  Your technique must be thoughtless and effortless. If you have a twist or tension which gets in the way of your playing, it will affect your reading.  You want all your mental focus to go into reading and analyzing on the fly.
There is something to be said for rote or muscle memory.  Part of having an ergonomic technique is for your hands to just know where to go.  To know what the scales, chords and arpeggios feel like without having to think about them.  If you see a chord with a 1,3,5, your hands should just go there automatically.
Having a knowledge of theory is vital.  When you look at chords, scales and arpeggios in the score, you need to just know what they are so that again, you don't have to think about them.  You should be able to see a pattern coming up and just know what it is. You should see a note and just know that it is a fifth without thought.  Or, see that it is a G chord (I see numbers, not letters).
You need a good ear and knowing the composer would help.  Chord progressions tend to be predictive.  As you are reading, your ear will also hint at what is coming up and combined with everything else, sight reading will come easier.
Last, don't stop.  Don't train yourself to stop and lose your train of though.  If you miss something or make a mistake, keep going.  You are trying to train your mind to make music and make corrections on the fly. If you have ever played a B'way conductor's score, they are all the orchestra parts condensed into the grand staff.  It is impossible to play it all so you need to "just know" what to play, to pick and choose, not be a slave to the notation.
Sight reading is not one thing you can just study and it will happen.  It is a convergence, confluence, amalgamation, conglomeration which is distilled in the alembic of all your training.
As a baby, you didn't just learn to walk.  You first learned to turn your head, then roll over, then slither, then get on your hands and knees, then sit up, then stand, then fall, then fall, then fall, then run, then fall, then walk (walking is more advanced than running), then you intuitively learn how your hips/shoulders/knees/arms are used to minimize movement and work together for balance. The next thing you know you are taking out the trash every Wednesday.
Just study everything and the building blocks will take care of themselves.  However, I can't stress enough that mastering an ergonomic technique should be your highest priority.  Again, if you can't play what you are trying to read . . . Also, bad movement habits allowed to creep into your brain's muscle memory will most likely be there forever.  Attempting to play something you don't have the technical mastery over will surely invite improper movement into your arms (hands). I have spent my whole life trying to eradicate the bad habits my first teacher ignorantly allowed me to hard wire into my brain.  Her answer regarding my poor technique was "practice more." But, as we know, practice doesn't make perfect, perfect practice makes perfect. I needed a different teacher more than I needed more practice.


No Devices in VS Code - Flutter

Question: I'm new to flutter app devleopment. I've installed Flutter SDK and I'm using VS Code. I want to test my demo app in my android device, I've enabled Developer mode and USB debugging option in my android device. In the status bar, VS Code shows, No Device though I connected via USB cable. How to resolve this problem? Do we need Android SDK for this?
Screenshot
Comment: You need to do debug configuration on your mobile
Answer: connect your phone then you need to run adb devices on command line while your phone is unlocked it will show allow debug alert on phone accept and it will show
you can download command line tools and use sdk manager if you don't have android sdk
Comment: Thank you @Ahmed D. Sherif, Now I can see my device name.. But while executing **flutter run**  it throws error like this...
  Unable to locate a development device; please run 'flutter doctor' for information about installing additional components
Comment: But flutter doctor shows...
[X] Android toolchain - develop for Android devices
    X Unable to locate Android SDK.
      Install Android Studio from: https://developer.android.com/studio/index.html
      On first launch it will assist you in installing the Android SDK components.
      If the Android SDK has been installed to a custom location, set ANDROID_HOME to that location.
      You may also want to add it to your PATH environment variable.

[!] Android Studio (not installed)
[√] VS Code (version 1.44.2)
[√] Connected device (1 available)
Comment: the message is very clear you must have android studio from https://developer.android.com/studio/index.html installed and setup the sdk after install
Comment: Can we download Android sdk alone?
Comment: i edited my answer to show how but this method is hard
Answer: Run VS Code as administrator.
Check the result from terminal output: flutter doctor
Comment: naah. its still missing from my bottom bar. there's no device option

No Devices in VS Code - Flutter


How to get headers only with a http GET request similar to get_headers() in php

Question: In php you can retrive only headers without body
function UR_exists($url){
   $headers=get_headers($url);
   return stripos($headers[0],"200 OK")?true:false;
}

How I can do this in dart?
Maybe some of http.get() with anyone parameters in headers can help?
Answer: You could get the headers this way:
final response = await http.get(yourUri, headers: {'method': 'HEAD'});

print(response.headers);

If you want, you can of course wrap that in a function that only returns the headers, so it will be similar to the command you are used to. Something like this (you would have to make it more robust for handling errors, failed requests etc...):
Future<Map<String, String>> getHeaders(Uri uri) async {
  return (await http.get(uri, headers: {'method': 'HEAD'})).headers;
}

So running it like this:
print(await getHeaders(Uri.parse('http://www.google.com')));

Will print (in my case):

{set-cookie: AEC=datadatadata; expires=Wed, 10-May-2023 13:17:58 GMT;
path=/; domain=.google.com; Secure; HttpOnly; SameSite=lax,
cache-control: private, max-age=0, date: Fri, 11 Nov 2022 13:17:58
GMT, content-encoding: gzip, content-length: 6747, x-frame-options:
SAMEORIGIN, content-type: text/html; charset=ISO-8859-1,
x-xss-protection: 0, server: gws, expires: -1}
Comment: Note that you have to make the method more robust.. :)


Whether is my conclusion about euler gamma function correct? is it new conclusion $\Gamma (0)=i\pi$?

Question: I know that:
$$\int_0^\infty \frac{1}{(x^2+1)^{3/2}}\,dx=1$$
On the other hand
$$\int_0^\infty \frac{ dx}{({x^2+1^2)}^{3/2}}=\frac{(-1)^{3/2-1}\pi \Gamma (1/2)}{2\sin(\pi/2)(3/2-1)!\Gamma(1/2-3/2+1)}, \quad  0<3$$
This form of the equation is:
$$\frac{i\pi \sqrt \pi}{2\frac{\sqrt \pi}{2}\Gamma[0]}=1$$
Which implies that:
$$\frac {i\pi}{\Gamma(0)}=1$$
in another word! Euler gamma function over zero is imaginary number times by pi number:
$i\pi=\Gamma(0)$ which is a transcendental number.
Whether is my conclusion about Euler Gamma function correct? is it new conclusion?

$$\int_0^\infty \frac{x^m \, dx}{({x^n+a^n)}^r}=\frac{(-1)^{r-1}\pi a^{m+1-nr}\Gamma [(m+1)/n]}{n\sin[\pi (m+1)/n](r-1)!\Gamma[((m+1)/n)-r+1]}, \quad  0<m+1<nr$$
set $m=0$, $a=1$, $n=2$ and $r=3/2$
Comment: $\Gamma(0) = \tilde{\infty}$.
Comment: You must have made a mistake somewhere since the Gamma function "blows up" at the origin.
Comment: @Peter Tamaroff maybe this point that in terms of the Gamma Function is only valid for integer values
Comment: $(3/2-1)!$ is not defined.
Answer: Note that the formula for this integral (from your other question here):
$$\int_0^\infty \frac{x^m \, dx}{({x^n+a^n)}^r}=\frac{(-1)^{r-1}\pi a^{m+1-nr}\Gamma [(m+1)/n]}{n\sin[\pi (m+1)/n](r-1)!\Gamma[(m+1)/n-r+1]}, \quad  0<m+1<nr$$
In terms of the Gamma Function is only valid for integer values of $r$ (GEdgar points out the same thing in the comments).
Your conclusion is obviously contradictory anyway, $\Gamma(0) = \tilde{\infty} \neq i\pi$.
Comment: What is infinity with a tilde over it?
Comment: @GerryMyerson, Complex infinity (infinity in the complex plane with an undefined argument). I get my notation from [Wolfram Functions Site](http://functions.wolfram.com/GammaBetaErf/Gamma/03/02/).
Comment: Thanks. Never saw it before.


If $x+\frac{1}{y+\frac{1}{z+\frac13}}=\frac{118}{51}$ find $xyz$.

Question: I'm having a difficult time figuring out how to solve this algebra problem.

If $$x+\cfrac 1 {y+\cfrac 1 {z+\cfrac 1 3}}=\frac{118}{51}$$
find $xyz$.
Comment: Welcome to Math.SE! The community prefers/expects a question to include something of what the asker knows about the problem. (*What have you tried? Where did you get stuck?* etc) This helps answerers tailor their responses to best serve you, without wasting anyone's time explaining things you already know or using techniques beyond your skill level. (It also helps convince people that you aren't simply  trying to get them to do your homework for you. An isolated problem statement with no evidence of personal effort tends to give the wrong impression in this regard.)
Comment: This isn't my home work I'm just doing this for fun
Comment: Actually WA gives the answer. See the section for continued fraction: https://www.wolframalpha.com/input/?i=118%2F51
Comment: Note that if you divide $118$ by $51,$ the quotient is $2$ and the remainder is $16,$ so you have $$ \frac{118}{51} = 2 + \frac{16}{51}. $$
Comment: For the record, here is how the original poster expressed the question: https://i.stack.imgur.com/fVwz8.jpg
Answer: I will presume that $x,y,z$ are intended to be positive integers.
\begin{align}
\frac{118}{51} & = 2 + \frac{16}{51} = 2 + \frac 1 {\left( \frac{51}{16} \right)} = 2 + \cfrac 1 {3 + \cfrac 3 {16}} \\[15pt]
& = 2 + \cfrac 1 {3 + \cfrac 1 {\left( \frac{16} 3 \right)}} = 2 + \cfrac 1 {3 + \cfrac 1 {5 + \cfrac 1 3}}.
\end{align}
Comment: This is simply the simplest way of getting the values of $x, y $ and $z$ ! Fantastic approach... Keep it up, @Michael Hardy !
Comment: @SamRubenAbraham : Thank you.
Comment: You are always welcome... btw, would you mind helping m with this : https://math.stackexchange.com/questions/3757372/is-it-possible-to-make-a-statistical-classifier-using-the-inverse-square-law-in ?
Answer: It is convenient to rewrite the left hand side a bit. This leads us to:
$$x + \frac{3z+1}{y(3z+1)+3} = \frac{118}{51}$$
From this it follows that the denominator on the left must be a multiple of 51, therefore:
$$y(3z+1)+3 = 51N$$ where N is a natural number. For the numerator we then find the equation:
$$51Nx + 3z + 1 = 118N$$
Let us try $N = 1$. We can easily verify that $z = 5$, $y=3$, $x=2$ is a solution. It is possible that other solutions exist. This should be carefully checked.
Answer: Write:
$\begin{align*}
   x + \frac{1}{y + \frac{1}{z + \frac{1}{3}}} - \frac{118}{51}
     &= 0 \\
   \frac{((153 x - 354) y + 153) z + (51 x - 118) y + 153 x - 303}
        {153 y z + 51 y + 153}
     &= 0
\end{align*}$
If the denominator isn't zero, the numerator must be:
$\begin{align*}
  ((153 x - 354) y + 153) z + (51 x - 118) y + 153 x - 303
    &= 0 \\
  153 x y z - 354 y z + 153 z + 51 x y - 118 y + 153 x - 303
    &= 0
\end{align*}$
It is seen that this can't be written as a function only of $x y z$. You can e.g. set any pair of variables to zero and get a matching value for the third, and that doesn't always make the denominator zero.
This has no solution.
Comment: If you set any pair of variables to values of your choice and get a solution for the third, then that gives you a value of $xyz,$ and in most cases that makes your denominator $0.$ So by that reasoning one would conclude that there are infinitely many solutions.
Comment: By my calculation, we have $$ x+\cfrac 1 {y+\cfrac 1 {z+\cfrac 1 3}} = \frac{3xyz + xy + 3x + 3z + 1}{3yz + y + 3}. $$ Your denominator is just $51$ times mine:
$$
153xyz + 51y + 153 = 51\big( 3yz + y + 3 \big).
$$
But I wonder about the numerator that you got. $\qquad$


parallel event subscriber .net 4.5

Question: I am trying to create a parallel event subscriber. This is my first attempt:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using EventStore.ClientAPI;

namespace Sandbox
{
    public class SomeEventSubscriber
    {
        private Position? _latestPosition;
        private readonly Dictionary<Type, Action<object>> _eventHandlerMapping;
        private IEventStoreConnection _connection;

        public Dictionary<Type, Action<object>> EventHandlerMapping
        {
            get { return _eventHandlerMapping; }
        }

        public SomeEventSubscriber()
        {
            _eventHandlerMapping = CreateEventHandlerMapping();
            _latestPosition = Position.Start;
        }

        public void Start()
        {
            ConnectToEventstore();
        }

        private void ConnectToEventstore()
        {
            _connection = EventStoreConnectionWrapper.Connect();
            _connection.Connected +=
            (sender, args) => _connection.SubscribeToAllFrom(_latestPosition, false, EventOccured, LiveProcessingStarted, HandleSubscriptionDropped);
        }

        private Dictionary<Type, Action<object>> CreateEventHandlerMapping()
        {
            return new Dictionary<Type, Action<object>>
            {
                {typeof (FakeEvent1), o => Handle(o as FakeEvent1)},
                {typeof (FakeEvent2), o => Handle(o as FakeEvent2)},
            };
        }

        private async Task Handle(FakeEvent1 eventToHandle)
        {
            SomethingLongRunning(eventToHandle);
        }

        private async Task Handle(FakeEvent2 eventToHandle)
        {
            SomethingLongRunning(eventToHandle);
        }

        private async Task SomethingLongRunning(BaseFakeEvent eventToHandle)
        {
            Console.WriteLine("Start Handling: " + eventToHandle.GetType());
            var task = Task.Delay(10000);
            await task;
            Console.WriteLine("Finished Handling: " + eventToHandle.GetType());
        }

        private void EventOccured(EventStoreCatchUpSubscription eventStoreCatchUpSubscription,
            ResolvedEvent resolvedEvent)
        {
            if (resolvedEvent.OriginalEvent.EventType.StartsWith("$") || resolvedEvent.OriginalEvent.EventStreamId.StartsWith("$"))
                return;

            var @event = EventSerialization.DeserializeEvent(resolvedEvent.OriginalEvent);
            if (@event != null)
            {
                var eventType = @event.GetType();
                if (_eventHandlerMapping.ContainsKey(eventType))
                {
                    var task = Task.Factory.StartNew(() => _eventHandlerMapping[eventType](event));
                    Console.WriteLine("The task is running asynchronously...");
                }
            }
            if (resolvedEvent.OriginalPosition != null) _latestPosition = resolvedEvent.OriginalPosition.Value;
        }

        private void HandleSubscriptionDropped(EventStoreCatchUpSubscription subscription, SubscriptionDropReason dropReason, Exception ex)
        {
            if (dropReason == SubscriptionDropReason.ProcessingQueueOverflow)
            {
                //TODO: Wait and reconnect probably with back off
            }

            if (dropReason == SubscriptionDropReason.UserInitiated)
                return;

            if (SubscriptionDropMayBeRecoverable(dropReason))
            {
                Start();
            }
        }

        private static bool SubscriptionDropMayBeRecoverable(SubscriptionDropReason dropReason)
        {
            return dropReason == SubscriptionDropReason.Unknown || dropReason == SubscriptionDropReason.SubscribingError ||
                   dropReason == SubscriptionDropReason.ServerError || dropReason == SubscriptionDropReason.ConnectionClosed;
        }

        private static void LiveProcessingStarted(EventStoreCatchUpSubscription eventStoreCatchUpSubscription)
        {

        }
    }
}

In your expert opinion, is this a valid approach? Could you please suggest any improvements?
PS:
Maybe:
Task.Run(() => _eventHandlerMapping[eventType](@event));

would be better?
Comment: I did not made a full review, but my first criticism would be to avoid a variable named "@event". Even it's perfectly legal with the @ prefix, it's ugly. Only useful for example for generated code against a datasource (db, ws...), not in "regular" code. I know, this is not really helpful concerning the main topic, sorry.
Comment: There is no such thing as .NET 5. The current version is .NET 4.5.2, and the upcoming version (Visual Studio 2015) is .NET 4.6. Are you confusing .NET version numbers and C# versions?
Comment: Personally I find it hard to read the entire code, and figure out your intent. Can you please produce a smaller example, and be more specific about your question. Describe your current approach with few words, small example, and things you are wondering which could be improved / are issues.. etc..
Comment: Have you looked at Rx (https://rx.codeplex.com/). It may just be what you're looking for.
Comment: Somehow funny to see the calls for a merge to [Code Review](http://codereview.stackexchange.com/) deleted, for whatever reason ... These calls seem more than legit and a clear statement why they are not would clarify things dramatically!
Comment: Yes, that's what I meant - sorry.
Comment: @VikasGupta - it is fairly straightforward. If the subscriber's method is hit (EventOccured) I want to exploit the possibility of multiple cores via Task Parallelism. At the moment: Task.Run(() => _eventHandlerMapping[eventType](@event)); seems to be right.
Comment: @Onots - thanks for that. I have indeed started to look at RX but am not yet sure how it would help in this particular scenario.
Comment: Instead of creating parallel event subscriber (complications and overhead) why not use normal event and process event handlers in parallel? Imho, you get more mistakes identifying if its a parallel event handler or not, than if you would have all events *normal*, but will be able to see their handler run coder in parallel. Does creating of it worth it?
Comment: @Sinatr - thanks. I have to admit that I do not fully understand. Can you please provide an answer?
Comment: @Andreas Niedermair - sorry this has nothing to do with me. I think you have a point ...
Comment: @csetzkorn That is the reason why I did not ping you directly ;) I suppose an administrator did some cleanup, but did not leave a true  and comprehensible reason ...
Answer: I don't really see a point in creating parallel event subscriber (if I understand your intention correct - to be able to run event handlers in parallel, not one after another as with normal events).
It's much more clear to express intent to run in parallel if event handler itself shows it.
Something like (very primitive).
void SomeEventHandler(object sender, EventArgs e)
{
    Task.Run(() =>
    {
       ... // some code to run in parallel
    });
}

You may want to create sort of manager (honestly, I have no clue how to occupy all cores, but I don't think this is complicated, I just never have to do it), but please, keep normal events.
Comment: I guess your suggestions would exploit the cores if events come in very quickly for the particular eventhandler. This is in contrast to exploiting the cores at a higher level (i.e. in SomeEventSubscriber) as I have attempted. The question is what is more scalable ...
Answer: You have a single EventOccured delegate which is where you'd be notified for all events that occur in the EventStore
First consider running the pre code inside EventOccured in a different dispatcher than the one on which the events are fired.
Secondly, would it be possible for you change this to a abstract class with implementation for FakeEventBase and then extend it and create individual instances for each FakeEvent type.
That would be much cleaner solution.
Thirdly, consider have a custom ThreadScheduler for queuing and running these Handle tasks.
http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler(v=vs.110).aspx
EDIT:
I would have a broadcaster class like below which knows when the operation has completed and raises the finished event.
public class EventBroadcaster
{
    public event EventHandler SomeEventOccured;

    public async void DoLongRunningOperationAndRaiseFinishedEvent()
    {
        var waitingTask = Task.Delay(TimeSpan.FromSeconds(2));

        await waitingTask.ContinueWith(t => RaiseSomeEventOccured(), CancellationToken.None,
            TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current);
    }

    private void RaiseSomeEventOccured()
    {
        EventHandler handler = SomeEventOccured;
        if (handler != null) handler(this, EventArgs.Empty);
    }
}

and then an EventListener
public class EventListner
{
    private readonly string _id;

    public EventListner(string id)
    {
        _id = id;
    }

    public void ListenTo(EventBroadcaster broadcaster)
    {
        broadcaster.SomeEventOccured += OnSomeEventOccured;
    }

    private async void OnSomeEventOccured(object sender, EventArgs eventArgs)
    {
        var currentTime = DateTime.Now;
        Console.WriteLine("EventListner {0} received at {1}", _id,
            currentTime.ToString("dd-MM-yyyy HH:mm:ss.fffffff"));

        //Not required just to show this does not affect other instances.
        //await Task.Delay(TimeSpan.FromSeconds(5));
    }
}

then this would be the Program.cs for testing
public static class Program
{
    public static void Main(string[] args)
    {
        var broadcaster = new EventBroadcaster();

        var listners = new List<EventListner>();

        for (int i = 1; i < 10; i++)
        {
            var listner = new EventListner(i.ToString(CultureInfo.InvariantCulture));
            listner.ListenTo(broadcaster);
            listners.Add(listner);
        }

        broadcaster.DoLongRunningOperationAndRaiseFinishedEvent();

        Console.WriteLine("Waiting for operation to complete");

        Console.ReadLine();

    }
}

In this example the handler delegates are fired one by one in the order they were subscribed to.
Now modify the code in the Broadcaster to something like below
Note:I have changed method signature from EventHandler to Action for ease of coding.
    private void RaiseSomeEventOccured()
    {
        Action handler = SomeEventOccured;
        if (handler != null)
        {
            var parallelOption = new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount };
            Parallel.Invoke(parallelOption, Array.ConvertAll(handler.GetInvocationList(), ConvertToAction));
            handler();
        }
    }

    private Action ConvertToAction(Delegate del)
    {
        return (Action)del;
    }

Now you will see that the events are fired in random order.
I got better performance using option 1.
Note: always with TPL and Parallel programming you need to make sure there is a benefit before going for it.
Comment: Sorry your answer does not make sense. Why should SomeEventSubscriber implement FakeEventBase? Also not sure why I should implement a tailor made ThreadScheduler in such a simple scenario ...
Comment: you want events to be handled in parallel if you have multiple listeners the events can be processed in parallel.
Image a traffic signal, there are multiple cars waiting in the signal for the `green light` and then all cars make their decision to move depending on the traffic before them; In your case `EventOccured` is not broadcasted to all handlers at the same time rather `EventOccured` dispatches them one by one albeit asynchronously hope you get the difference.
Comment: Also I suggested having a separate `ThreadPool` because I though you didn't want the even processing to be done in the main ThreadPool which might cause delay if the other ThreadPool already has tasks queued.
Comment: Ok can you please suggest an improvement on exactly this subject? Thanks.
Comment: Can you please provide some alternative code to broadcast to all handlers at the same time?
Comment: Btw, I thought that async and await allow you to 'fire and forget events'. The async event handlers would then run in 'parallel' whilst exploiting the cores of the processor. Hence, firing of the next event is not delayed by handling the previously fired event ...
Comment: you are correct but there is a delay in firing in the control stack because there is only one handler and since you have not checked for thread integrity (`lock`) in your `EventOccured` method I assume firing happens one by one, if not you need to have a `lock` inside `EventOccured` in this implementation which would not give the parallel behavior you are expecting.
Comment: Thanks that looks interesting. Could you please clarify what option 1 is? Also, the LongRunningOperation is, in my scenario, run in the event handler not before the event is fired. Basically, the broadcaster should fire the events parallel as quickly as possible and the eventhandlers (i.e. workers) should execute some computationally expensive stuff. Sorry if this was not clear.
Comment: option one was firing events in the order they were subscribed to without the `Parallel.Inoke`

parallel event subscriber .net 4.5


If $f $ is a continuous function then $\exists a$ such that..

Question: Suppose $ f $ is a continuous function on the interval $[x,y]$; prove $\exists $ $a\in [x,y]$ such that $ f(a)=1/(y-x) \int^y_x fdx $.
I can't come up with a neat proof.
Theorem:
Let $ f $ be a continuous function on the interval $[x,y]$. If $ f(x)<f(y) $ and if $ b $ is a number such that $ f(x)<b<f(y) $ then $\exists a\in (x,y)$ such that $f(a)=b$.
Comment: Just to be clear are you asking how to use the theorem (intermediate value theorem) to prove the first statement?
Comment: Hint: if $m$ is the minimum of $f$ over $[x,y]$ and $M$ is the maximum, then $m\le{1\over y-x}\int_x^yf(s)\,ds\le M$.
Answer: EDIT (thanks to Tryss)
If $f$ is continuous on this interval, then its antiderivative is differentiable, and what you have written follows from Mean Value Theorem:
$$
\exists x<a<y  s.t. f(a) = \frac{F(y) -F(x)}{y-x}
$$
Comment: No need for $f$ differentiable, it's F that must be differentiable, and here, as $f$ is continous, $F$ is differentiable and $F'(x) = x$
Comment: You do not need for differentiability! continuity is enough!
Comment: Already fixed.Thanks.
Comment: thank you. how did you come up with this so fast?
Comment: It's just a definition of MVT for $F(x)$
Answer: Since $f$ is continuous on $[x,y]$, by the Fundamental Theorem of Calculus the function $F(s) = \int_{x}^{s}f(t)dt$ is differentiable with $F'(s) = f(s)$. Then applying the Mean Value Theorem to $F$, there exists $a \in [x, y]$ such that $\frac{1}{y-x}\int_{x}^{y}f(t)dt = \frac{F(y) - F(x)}{y - x} = F'(a) = f(a)$.


Is there anyway to know if the css of div is set in class or in id in javascript/ jquery ?

Question: Hello I am changing dynamically the css of a website:
Suppose we have a div:

with class fooclass and id fooid element and we get its background using:
var bgcolor = element.css( "background-color" );
My Problem is that I cannot tell of that bgcolor is set in the fooid css or in the fooclass is there anyway to find that out? thank you in advance
Comment: [The XY-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)
Comment: You could create an element with just one of the selectors and check the computed css value of that element.
Comment: I'm trying to understand the use case for this type of problem. What scenario would you need to derive an element's original source for a particular style? CSS is either pre-defined in a standard file, or is styled inline on-the-fly using javascript. In other words, you're usually supposed to know where and when a style is applied/used.
Comment: What are you actually trying to do? Get the value of `background-color` of a certain element?
Comment: I don't think that you can be enable of know which specific CSS rule is applied and where it come from on javascript. The CSS painting process doesn't have a way to indicate that information when is applied to an element. That's why the element doesn't know which rule is applied for background-color, the element only know what is the last specific rule valye
Comment: I do not want to use inline css but rather override the css or id in the class. @ kresimir I want to know if the background-color value is set in the class css or in the id css
Comment: you don't need to know from where it comes to override it, simply add another class and increase the specificity or use important, etc ...
Comment: @ Temani I know I can override it but I want to know where it is set.
Answer: One way to find out is to use chrome's developper tools. You can inspect your div and look of the background is set using the class or the id in your styles tab. The background will be set there and you can see by what.
Answer: Get the selectors from this answer :
Find all CSS rules that apply to an element
and then match the value with Window.getComputedStyle of background-color of your element.


Problema ao montar JSON com retorno do banco de dados

Question: Tudo se resume a essa imagem:

O problema está na montagem do JSON, ele não agrupa o primeiro resultado e atribui um array para as datas, como deveria ficar na imagem abaixo:

Existe algum plugin no mysql ou api no php que resolva esse problema, montar o json ou Gjson a partir de um data set com relação de 1-N:

Como fazer isso?
Segue as querys

Usei o php para exemplificar o que quero, no entanto pode ver que o php não faz nada demais, só exibe o resultado da query, quero fazer a manipulação de dados na consulta, mas se não for possível, a solução em php será bem vinda. :D
Comment: Não parece errado, há 2 *Milrak* por isso o array sobre as datas. Mostre sua query.
Comment: @PapaCharlie não existe dois Milrak na table Pessoa, e sim duas inscrições de milrak na table inscrição. Realmente a query retorna duas linhas dele, no entando eu gostaria que o json agrupasse em um só objeto milrak que teria duas datas entende?
Comment: Coloca o código `php` que estás a usar.
Comment: @Edilson Eu só estou usando Mysql, funções como JSON_ARRAY e JSON_OBJECT. Não conheço solução em php para o problema. :/
Comment: Edita a pergunta, e coloca a parte do código responsável por gerar essa sequência.
Comment: @Edilson não sei para qual título mudar, então continua o mesmo e acrescentei o código que faz a sequência.
Comment: Posta o código como texto, não como imagem.
Answer: Uma maneira simples de corrigir o problema, com a ajuda do MySQL é utilizar o GROUP_CONCAT() e depois utilizar o explode() do PHP.
Desta maneira ficaria:
SELECT nome, group_concat(data) FROM pessoa GROUP BY nome

Isso irá retornar todas as datas numa só linha, agrupado pelo nome. No final o resultado do MySQL será o seguinte, por exemplo:
+---------+-----------------------+
| Nome    | Data                  |
+---------+-----------------------+
| Ana     | 2016-01-01,2017-01-01 |
| Bob     | 2000-01-01            |
| Charlie | 2016-12-01,2017-01-03 |
+---------+-----------------------+

Dessa forma todas as datas estarão juntas, permitindo usar um explode(',', $Data) para quebrar as datas, que estão separadas por virgula.

Depois bastaria utilizar:
while($linha = mysqli_fetch_array($query)){

    $json_array[] = [
        'Nome' => $linha['nome'],
        'Data' => explode(',', $linha['data'])
    ];

}

echo json_encode($json_array);

Comment: desculpa minha ignorância, parece que você achou uma boa solução para o problema... Mas e quando o campo DATA for por exemplo um campo qualquer de texto, e nesse texto exista uma vírgula no meio, não teremos um pouco mais de problemas?
Comment: A documentação, do GROUP_CONCAT, especifica isto. Você pode mudar o "separador" usando `SEPARATOR str_val`. Por exemplo, `group_concat(data SEPARATOR '-- MEU SEPARADOR --')`, fazendo isso tudo ficará como `2016-01-01-- MEU SEPARADOR --2017-01-01`, você pode simplesmente fazer um `explode` do `-- MEU SEPARADOR --`.
Comment: achei essa a melhor das resposta, no entanto estou resolvendo o problema com array no php deu um trabalho danado, não está 100% mas vai sair, quando estiver pronto postarei aqui :)
Answer: Há uma pergunta similar no stackoverflow em inglês. Para conseguir o efeito desejado você pode usar algum ORM (dos frameworks laravel, cakePHP, ... ou algo standalone como o notorm).
Ao usar algum desses vai exigir uma relativa curva de aprendizado.
O link da pergunta acima sugere duas alternativa:
fazer a consulta na primeira tabela, percorrer os resultados com um foreach, criar um novo array para cada linha retornada. Depois fazer uma segunda consulta para cada linha retornada. Um outro foreach para iterar sobre cada linha da segunda consulta e criar um novo array, para colocar dentro do da primeira consulta.
a segunda possibilidade é fazer uma unica cosulta (como você fez), e montar com o array do fetchAll a hierarquia que você quer.


Android Studio 1.4: drawable-v21 ignored when using "File/New/Vector Asset" option

Question: This is my first SO question so please don't eat me alive... Here's my problem:
I've imported few icons via Android Studio 1.4's new option - New/Vector Asset. As you know it lets you easily import and use vector drawables and creates pngs for compatibility with APIs <21. It puts the pngs in folders app/build/generated/res/pngs/debug/drawable-<density> (mdpi, ldpi, hdpi etc). It also generates the -v21 versions of all the folders and puts the vector drawable .xmls there.
The problem started, when I wanted to add ripple effect to one of the icons. I've put the .... ripple-less version into my res/drawable folder. It looked like this:
drawable/ic_settings.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
<path
    android:fillColor="#FFFFFF"
    android:pathData="M12,15.5A3.5,3.5 ...blablabla notimportatnt"/>
</vector>

Then I wanted to add ripple to the icon in API >21. So to the folder res/drawable-v21 I added this drawable:
drawable-v21/ic_settings.xml
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
     android:color="?android:colorControlHighlight">
<item>
    <vector
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
        <path
            android:fillColor="#FFFFFF"
            android:pathData="M12,15.5A3.5,3.5 0,0....blah blah blah"/>
    </vector>
</item>
</ripple>

Now, when I run the app under API 21, instead of using resources from drawable-v21 it uses a drawable from app/build/generated/res/pngs/debug/drawable-xxhdpi-v21automatically generated based on the file in res/drawable. So no ripple.
When I tried to remove the ripple-less file from res/drawable/, the ripple comes back in API 21, but of course the app crashes in APIs<21
Then I tried to put ripple version of the icon to the res/drawable folder, hoping that gradle would automatically generate the pngs. Nope - <ripple> tag prevents gradle from generating pngs and the app crashes <21.
Anyone stumbled upon this kind of problem? Any idea how to add ripple to the icon?
Have a good day!
Comment: I was just about to ask the same question..
Answer: Ok, I kinda found the solution.
In folder res/drawable I left only the vectors that can and should be automatically converted to pngs - so only plain normal icons without ripple. Then in drawable_v21 I've put the ripple version of drawable and renamed it -  ic_settings_ripple.xml. I've created a new folder layout-v21and duplicated my layout, but instead of ic_settings.xml i used ic_settings_ripple.xml.
So now under API<21 the app uses ripple-less png generated by gradle, and at API>=21 there is an alternative layout, that uses ripple version of one of the icon.


Redirect remote desktop traffic with 2 WANs and 1 LAN

Question: Im configuring a linux centos sever for testings and the network configuration for it is:
WAN 1= 192.168.1.103/24 eth0
WAN 2= 172.16.1.249/16 eth1
LAN = 192.168.10.1 eth2
server is configured to be a non transparent proxy without authentication, every client has configured the proxy and IP port on the browsers. Internet access is working fine from the client computers; computers are in the 192.168.10.x/24 range and also the default gateway for the computers is 192.168.10.1
We need to redirect windows Remote Desktop traffic from the LAN from eth2 to eth1 only. this because the WAN2 link is more stable and that fits our needs to keep the RDP session alive. The final destination server which has the RDP enabled so we can work has the IP 184.108.40.206/24 and access is provided by a router from the ISP.
How can I configure this in the server so RDP protocol (port 3389) can be redirected to eth1 and the rest of the traffic keeps using the eth0 link?
Im lost about what approach to take, i dont know for sure if this can be accomplished using iptables or if else it has to use iproute2.
Thanks in advance.
Answer: 2 strategies I use to address this challenge:
Method

I identify my eth0 and eth1 by binding them with static ip address individually.
I then establish port forwarding protocols, and it'd forward the traffic via ip address & ports at my choices.

Strategy A
Method but done by router on my system (I flashed my router with new "BIOS".  Thanks goodness for DD-WRT.  Google it)
Strategy B
Method but done by iptables.  The machine that controls iptables needs to be local DNS resolver (DNSMasq-ing) [in other words, 'gateway'].
I always opted for Strategy A.  It's dirty fast.  But Strategy B is far better in terms of enhanced security if multi-users are involved.


How to identify the source of growing blocked processes on a system container (LXC/OpenVZ)

Question: When the number of blocked processes grow indefinitely, how to identify exactly what are these processes.

Since I'm inside a system container (LXC/OpenVZ), I can't modify the hosts' kernel modules to use tools like perf-tools or bcc-tools/bpfcc-tools

The question How to track newly created processes in Linux? doesn't cover the scenario of system containers, and most of the answers rely on tools like perf-tools and bcc-tools.
Comment: you can start from IOWAIT
Comment: It is completely on 0% both before and after the reboot.
Comment: active sysstat and check
Answer: 1. Check CONFIG_PROC_EVENTS
First check if CONFIG_PROC_EVENTS is enable. Depending on your distro, you can run:
grep CONFIG_PROC_EVENTS= /boot/config-`uname -r`

If it's enabled, you will get the following result:
CONFIG_PROC_EVENTS=y

2. If it's enabled, create the monitor
Create a file proc_events.c with the content:
static volatile bool need_exit = false;

static int nl_connect()
{
    int rc;
    int nl_sock;
    struct sockaddr_nl sa_nl;

    nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
    if (nl_sock == -1) {
        perror("socket");
        return -1;
    }
    sa_nl.nl_family = AF_NETLINK;
    sa_nl.nl_groups = CN_IDX_PROC;
    sa_nl.nl_pid = getpid();
    rc = bind(nl_sock, (struct sockaddr *)&sa_nl, sizeof(sa_nl));
    if (rc == -1) {
        perror("bind");
        close(nl_sock);
        return -1;
    }
    return nl_sock;
}

static int set_proc_ev_listen(int nl_sock, bool enable)
{
    int rc;
    struct __attribute__ ((aligned(NLMSG_ALIGNTO))) {
        struct nlmsghdr nl_hdr;
        struct __attribute__ ((__packed__)) {
            struct cn_msg cn_msg;
            enum proc_cn_mcast_op cn_mcast;
        };
    } nlcn_msg;

    memset(&nlcn_msg, 0, sizeof(nlcn_msg));
    nlcn_msg.nl_hdr.nlmsg_len = sizeof(nlcn_msg);
    nlcn_msg.nl_hdr.nlmsg_pid = getpid();
    nlcn_msg.nl_hdr.nlmsg_type = NLMSG_DONE;

    nlcn_msg.cn_msg.id.idx = CN_IDX_PROC;
    nlcn_msg.cn_msg.id.val = CN_VAL_PROC;
    nlcn_msg.cn_msg.len = sizeof(enum proc_cn_mcast_op);

    nlcn_msg.cn_mcast = enable ? PROC_CN_MCAST_LISTEN : PROC_CN_MCAST_IGNORE;

    rc = send(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
    if (rc == -1) {
        perror("netlink send");
        return -1;
    }

    return 0;
}

static int handle_proc_ev(int nl_sock)
{
    int rc;
    struct __attribute__ ((aligned(NLMSG_ALIGNTO))) {
        struct nlmsghdr nl_hdr;
        struct __attribute__ ((__packed__)) {
            struct cn_msg cn_msg;
            struct proc_event proc_ev;
        };
    } nlcn_msg;
    while (!need_exit) {
        rc = recv(nl_sock, &nlcn_msg, sizeof(nlcn_msg), 0);
        if (rc == 0) {
            /* shutdown? */
            return 0;
        } else if (rc == -1) {
            if (errno == EINTR) continue;
            perror("netlink recv");
            return -1;
        }
        switch (nlcn_msg.proc_ev.what) {
            case PROC_EVENT_NONE:
                printf("set mcast listen ok\n");
                break;
            case PROC_EVENT_FORK:
                printf("fork: parent tid=%d pid=%d -> child tid=%d pid=%d\n",
                        nlcn_msg.proc_ev.event_data.fork.parent_pid,
                        nlcn_msg.proc_ev.event_data.fork.parent_tgid,
                        nlcn_msg.proc_ev.event_data.fork.child_pid,
                        nlcn_msg.proc_ev.event_data.fork.child_tgid);
                break;
            case PROC_EVENT_EXEC:
                printf("exec: tid=%d pid=%d\n",
                        nlcn_msg.proc_ev.event_data.exec.process_pid,
                        nlcn_msg.proc_ev.event_data.exec.process_tgid);
                break;
            case PROC_EVENT_UID:
                printf("uid change: tid=%d pid=%d from %d to %d\n",
                        nlcn_msg.proc_ev.event_data.id.process_pid,
                        nlcn_msg.proc_ev.event_data.id.process_tgid,
                        nlcn_msg.proc_ev.event_data.id.r.ruid,
                        nlcn_msg.proc_ev.event_data.id.e.euid);
                break;
            case PROC_EVENT_GID:
                printf("gid change: tid=%d pid=%d from %d to %d\n",
                        nlcn_msg.proc_ev.event_data.id.process_pid,
                        nlcn_msg.proc_ev.event_data.id.process_tgid,
                        nlcn_msg.proc_ev.event_data.id.r.rgid,
                        nlcn_msg.proc_ev.event_data.id.e.egid);
                break;
            case PROC_EVENT_EXIT:
                printf("exit: tid=%d pid=%d exit_code=%d\n",
                        nlcn_msg.proc_ev.event_data.exit.process_pid,
                        nlcn_msg.proc_ev.event_data.exit.process_tgid,
                        nlcn_msg.proc_ev.event_data.exit.exit_code);
                break;
            default:
                printf("unhandled proc event\n");
                break;
        }
    }

    return 0;
}

static void on_sigint(__attribute__ ((unused)) int unused)
{
    need_exit = true;
}

int main()
{
    int nl_sock;
    int rc = EXIT_SUCCESS;

    signal(SIGINT, &on_sigint);
    siginterrupt(SIGINT, true);
    nl_sock = nl_connect();
    if (nl_sock == -1)
        exit(EXIT_FAILURE);
    rc = set_proc_ev_listen(nl_sock, true);
    if (rc == -1) {
        rc = EXIT_FAILURE;
        goto out;
    }
    rc = handle_proc_ev(nl_sock);
    if (rc == -1) {
        rc = EXIT_FAILURE;
        goto out;
    }
    set_proc_ev_listen(nl_sock, false);
out:
    close(nl_sock);
    exit(rc);
}

Ensure that you can compile C programs. On Debian or Debian-based distros, like Ubuntu, run:
sudo apt-get install build-essential

And compile it with:
gcc proc_events.c -o proc_events

3. Run it for a few seconds
Running it this way will output directly on terminal:
./proc_events

But you can also redirect it and run for a few seconds, in order to save its output on a file:
./proc_events > results_file

4. Analise the results
The output will be in the following format:
fork: parent tid=48 pid=48 -> child tid=56 pid=56
fork: parent tid=48 pid=48 -> child tid=57 pid=57
exec: tid=57 pid=57
exec: tid=56 pid=56
exit: tid=57 pid=57 exit_code=0
exit: tid=56 pid=56 exit_code=0

Credits to @cirosantilli
Comment: Credits to @ciro-santilli-新疆改造中心996icu六四事件


Linux 'grep' only highlights but doesn't filter

Question: question is in the title.
I'm trying to perform
   "du -sh * | grep '^[0-9]'"
on my root dir to filter out any ... cannot access ..., but my console will just color matches and print out everything.
Thanks for any help
Answer: When you run a command, it will always open 3 files: stdin (keyboard input), stdout (command output) and stderr (command output for error messages), these are numbered from 0 to 2.
Those error messages from du are written to stderr, while the normal output is written to stdout. This allows you to redirect the error messages to /dev/null. This makes the error messages disappear, you don't need grep for that.
du -sh * 2>/dev/null

Comment: thanks alot, i was banging my head against the wall the last half an hour because of this :D


maximum recursion depth exceeded google colab

Question: Trying to run some python code on Google colab. I have some preprocessed data that I need to read in:
<code>train, test, unused_feat, target_features, features, cat_idxs, cat_dims  = pickle.load(open('/content/drive/My Drive/xxx/data/train_test.pkl', 'rb'))
</code>
Then if I call train I get the error:
<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/IPython/core/formatters.py in __call__(self, obj)
    697                 type_pprinters=self.type_printers,
    698                 deferred_pprinters=self.deferred_printers)
--> 699             printer.pretty(obj)
    700             printer.flush()
    701             return stream.getvalue()

8 frames
pandas/_libs/properties.pyx in pandas._libs.properties.AxisProperty.__get__()

/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in __getattr__(self, name)
   5268             or name in self._accessors
   5269         ):
-> 5270             return object.__getattribute__(self, name)
   5271         else:
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):

AttributeError: 'DataFrame' object has no attribute '_data'
</code>
and when I call
<code>---------------------------------------------------------------------------
RecursionError                            Traceback (most recent call last)
<ipython-input-35-5e6a15ce28a5> in <module>()
----> 1 train.shape

321 frames
pandas/_libs/properties.pyx in pandas._libs.properties.AxisProperty.__get__()

/usr/local/lib/python3.6/dist-packages/pandas/core/generic.py in __getattr__(self, name)
   5268             or name in self._accessors
   5269         ):
-> 5270             return object.__getattribute__(self, name)
   5271         else:
   5272             if self._info_axis._can_hold_identifiers_and_holds_name(name):

RecursionError: maximum recursion depth exceeded while calling a Python object

</code>
When I work on my own jupyter notebook I have no problem with this. I wonder what went wrong. Also train contains roughly 250000 rows.
Answer: I think you could change the recursion limit if that is your constraint, however, you might be in an endless loop.
This post tells you how to increase your recursion limit.
What is the maximum recursion depth in Python, and how to increase it?
However, I am not sure about the other error you got. Hope it helps a bit.
Comment: I ended up solving it by reducing the memory usage of my dataframe
Comment: Sweet, great to know! Good luck.


Best practices for detecting when "user is typing" for chat functionalities?

Question: I am currently using PubNub to handle the realtime aspects of chat, and plan to change a PNChannel's state when a user is typing or has completed typing.
My question relates more to the client side of how something like an isTyping state can be measured . Since every tap on the screen keyboard is bound to have some space of time in between, I was wondering if there is a "best practice" way to either measure the time gaps between screen taps to understand whether a user is typing (for example, a slow typer versus a faster typer) versus when the user has actually stopped typing?
Thanks!
Comment: Use `NSTimer` in combination with detecting keystrokes. It's up to you to decide how much time can go by after the last detected keystroke and still consider it "typing".
Answer: You can look up in these delegate methods of UITextField
-(void)textFieldDidBeginEditing:(UITextField *)sender //method fires when u start begining typing anything in a textfield
-(BOOL) textFieldShouldReturn:(UITextField *) textField // method fires whenever u type anything in a textfield- returns character wise
-(void)textFieldDidEndEditing:(UITextField *)sender // fires when u finished typing stuffs in a textfield.

Hope this helps