Is the following derivation of how to find $v$ given $a=v'$ wrong?

Question: My physics professor did the following:

Let $a(t)=v'(t)$ be a given function. Suppose $v(0)$ is known, then
  $$
\int_{v(0)}^{v(t)} dv=\int_0^ta(t)dt \iff v(t)=v(0)+\int_0^ta(t)dt
$$

I believe this is incorrect in many ways:

The  limits of integration (I don't understand why he got those!).
Having $t$ both as variable of integration and limit of integration.
"Multiplying by $dt$ on both sides"(??).

Could someone explain how to correctly get $v(t)$ from $v(0),a(t)$?
Comment: Plotting graph and calculating area is the best way.
Comment: Given that you know the points
Comment: @ArchisWelankar The thing is: I believe the result is correct, (say, if we write $\int_0^t a(s)ds$) but I don't know how to correctly derive this. Am I wrong?
Answer: Your professor isn't wrong per se, but his notation is not terribly precise, especially when teaching students who are new to calculus. Properly, the steps are the following.
Suppose we have $a(t) = v'(t)$. Now, let us integrate both sides with respect to $t$ from $0$ to some time $\tau$. Here $\tau$ is our time variable, which I've renamed from $t$ (which I will use as a dummy variable) to keep the two separate. This gives us
$$\int_0^\tau a(t)\ dt = \int_0^\tau v'(t)\ dt.$$
Now consider the formula for integration by substitution
$$\int^{g(b)}_{g(a)} f(t)\ dt = \int_a^b f(g(t))g'(t)\ dt.$$
We will take $f(t) = 1$, the constant function, and $g(t) = v(t)$. Then, taking the integration limits $a=0$ and $b=\tau$, the formula gives us
$$\int_0^\tau v'(t)\ dt = \int_{v(0)}^{v(\tau)}\ dt.$$
And this is precisely the result your professor got. A few things to mention here:
1. First, you must realize that the integration variable we use is completely insignificant. It is a dummy variable, and we are free to rename it anything we want. In this example, I've chosen to use $t$ consistently, while your professor chose to rename the dummy variable to $v$ in
$$\int_{v(0)}^{v(\tau)}\ dt = \int_{v(0)}^{v(\tau)}\ dv.$$
The two are completely equivalent, and in my experience, your professor's convention is in fact the common convention. The only source of confusion here is the fact that he chose to use $v$ both as the dummy variable and as the integration limits, which brings us to our second point.
2. The $t$ in the integration limit and the $t$ in the dummy variable of integration have nothing to do with each other. As I've stressed in point 1, the integration variable can be freely renamed without changing the value of the integral. It is good mathematical practice to keep the two separate just so confusion doesn't arise here. That's why I've chosen to rename my time variable as $\tau$ instead. But while using $t$ both as an integration limit and as an integration variable is confusion, it is not technically wrong. There is an unambiguous value that we can extract from the integral, and that's all we really care about.
3. Lastly, you mentioned about "multiplying by $dt$". This is not truly allowed of course, but it is formalized by integration by substitution. We can rewrite the integration by substitution formula in Leibniz notation
$$\int_{g(a)}^{g(b)} f(g)\ dg = \int_a^b f(g(t))\frac{dg(t)}{dt}\ dt,$$
where I've renamed the dummy variable on the left-hand side to $g$ as an abuse of notation. This is very suggestive notation, and it seems to suggest that we've cancelled the $dt$ in $\frac{dg}{dt}\,dt$ to get just $dg$, but all that's really going on is integration by substitution. This is the source of the "multiply by $dt$" that you will very often see. There is nothing dubious going on, and I think you will find that this way of thinking is much quicker than going through the formal substitutions each and every time. The notation is suggestive, but completely justifiable.
Comment: I'm quite sure a lot of people here would fight you over "the variable in the limit of integration can be the same as the variable of integration"...
Answer: Integrating both sides of $a(t)=v'(t)$ with respect to tthe same variable $t$ and for the same interval $(0,x)$ we have:
$$
\int_0^x a(t)dt=\int_0^xv'(t) dt
$$
and, by the fundamental theorem for the RHS;
$$
\int_0^x a(t)dt=v(x)-v(0)
$$
Answer: Little rant: sterilize this from the awful "$dv$" notation and it is clear what is going on.
The first equality states
$$\int_{v(0)}^{v(t)}1=\int_0^t a.$$
This clearly implies
$$v(t)-v(0)=\int_0^t a.$$
Hence,
$$v(t)=v(0)+\int_0^t a.$$
The other implication is also clear.
Your teacher probably just used the notation (also awful) that normal texts use for the change of variables. It bogs down to a "lifehack" for quick integral computations, but for conceptual purposes is not a good choice (in my opinion, of course).
Note also that what is written is somewhat ambiguous. The "iff" part is always true, regardless of whatever relationship $a$ and $v$ might have. So, if we read this as
"(...) then ($A \iff B$)",
we do not need the hypothesis for the thesis. However, he probably meant: "(...) then $A$, which happens to be equivalent to $B$".

Summing up, what the text is trying to communicate is:

Let $v$ be a real function, and $a=v'$. Then
$$v(t)=v(0)+ \int_0 ^t a. $$
Note: The previous equality is equivalent to
$$\int_{v(0)}^{v(t)} 1=\int_0^t a.$$
Comment: But why can you integrate on one side from $v(0)$ to $v(t)$ and on the other from $0$ to $t$?
Comment: They are numbers. What is the problem?


How to verify if a prediction performance improvement is significant better?

Question: I have a model M1 that achieved the predictive score (accuracy / AUC / F1 ...) of s1 in the test dataset.
I developed a new model M2 that achieved the predictive score of s2 on the same testset. Suppose that s2 > s1.
Is there any test to confirm that M2 is actually better than M1, or it is just the result of randomness in the models?
Comment: Is there any randomness involved in building your models or are they completely deterministic?
Comment: @user2974951randomness might come from data sampling as well - so the question here is that is there a kind of test that can say a model is actually better than other, like t-test in statistics.
Comment: No, this is not really done. If your models are random in nature then you could build multiple models and check their averages / variances, you could even use a test to check for significance, but this is dubious.
Answer: A few possibilities come to mind.
If you have multiple datasets, you could use a Diebold-Mariano test. The tag wiki contains information, as well as pointers to the original and a follow-up publication. The DM test is very commonly applied in the time series forecasting community, but there is nothing specifically "time-seriesey" about it.
If you have only a single dataset, then you could in principle bootstrap your model fits for both models and assess whether one improves on the other in (say) 95% of cases.
If you do this on the same test set in each replicate (only bootstrapping the training data), then all you can conclude is whether one model is better on this particular test set, so the bare minimum I would do would be to wrap the exercise in a cross-validation step. And even so, applying this machinery on a single dataset would be very prone to just making you very confident that an overfitting model is better than it actually is.
Answer: Dietterich (1998) proposes a 5x2 cross validation followed by a t-test to identify better models. When comparing models across multiple datasets, Demsar (2006) suggests the use of Wilcoxon Signed Rank test for comparing two models and Friedman test when comparing more than two models.


The inequality $|x-f(x)| \leq 1/2 |x| $ implies $ |x-x'| \leq 2|f(x)-f(x')|$

Question: I am reading a proof of inverse function theorem where the following inequality is used:
It's been established that $$|F(x)-F(x')| \leq 1/2 |x-x'|$$ for every $x,x' \in B_{\delta}(0)$ for some $\delta >0$ where $F(x)=x-f(x)$ for smooth $f$, with invertible derivative at the origin. And in particular if we let $x'=0$ we get
$$|F(x)| \leq 1/2 |x|$$
Then from the above the author claims that $|x-x'| \leq 2 |f(x)-f(x')|$. Somehow I fail to see how we get that. Must be a simple triangle inequality or something. Any help would be greatly appreciated
Answer: $|f(x)-f(x')|=|(x'-x)-(F(x')-F(x)|\geq |x'-x| -|(F(x)-f(x')|\geq |x'-x| - \frac 1 2 |x'-x| =\frac  1 2 |x'-x| $.
Comment: Thank you so much!


split string and leave the separators intact

Question: I cannot find a good way to split a string using a separator string but leave the separator as the prefix of each element of the resulting array:
from
var s = 'blah0__blah1__blah2';

I need to get
['blah0', '__blah1', '__blah2']

the closest thing that I could get was
s.split(/(__)/);

which returns
['blah0', '__', 'blah1', '__', 'blah2']

but this I would need to traverse to merge the underscores.
Is there a better way?
EDIT:
here is my best effort so far:
'blah__blah1__blah2'.split(/(__[^_]+)/)
// => ["blah", "__blah1", "", "__blah2", ""]

still, there are empty strings in the output...
Answer: How about this:
var s = 'blah0__blah__blah'
var s_split = s.match(/(__)?(.(?!__))+./g)
console.log(s_split)

I'm pretty sure it's much more costly (time and memory wise) than simply reiterating and joining after a regular split.
If you replace __ with your separator it should work fine for most cases.
Comment: thanks. looks like using a string instead of a regex as a separator is faster. even though I will have to iterate over the resulting array again.
Answer: A two-step process.
var s = 'blah0__blah1__blah2';
var blahs = s.split('__');
var scoreBlahs = blahs.map(preScore);
alert(scoreBlahs);
function preScore(b) {
    var x;
    var result = x.concat('__',b);
    return result;
}

Answer: 'blah0__blah1__blah2'.match(/^[^_]+|_+[^_]+/g);
["blah0", "__blah1", "__blah2"]

Seems to give you what you want. Though It may vary, if your input isn't exactly as you show it.
Comment: @wroniasty I've changed it to account for any length (this would be `1..infinity` potentially), but if you know the range beforehand, you can change `+` after the `_` to be that range, as in, for example: `_{2,42}`.
Answer: Just prepend the seperator after you seperate the string
var value = "a,b,c";
var splitter = value.split(",");
for(var i = 0; i < splitter.length; i++) {
    alert("," + splitter[i]);
    }

Answer: Since you know the separator - just add it again later on:
var s = 'blah0__blah1__blah2';
var sep = '__';
var arr = s.split(sep);
for (var i = 1; i < arr.length; i++) {
    arr[i] = sep + arr[i];
}

console.log(arr);

Comment: He already told to get better solution than traversing and prepending the seprator.
Comment: Somewhat true, however in my solution you only need to modify the array values, which is more efficient than *merging* the values of siblings in the array, and then modifying the array (with e.g. `slice`).
Answer: You could insert a secondary separator, and split on that, leaving the original intact.
var s = 'blah0__blah1__blah2';
s = s.replace('_', '_$');
s.split('$');


Universal piano chord voicings

Question: I am a bassist/guitarist who's recently started to play the piano. I am trying to learn songs/tunes I already know.
Generally I play the melody in the right hand and attempt to create bass line / harmony in the left hand. I am often puzzled which voicings to use for every chord, because there are many more possibilities compared to what is commonly used on guitar.
Most of the time I play roots and fifths in my left hand, while thirds, sevenths and above should be played in the right hand. However this often results in dull jumps, and does not sound good enough to me. I'd like to be able to create more smooth basslines and harmonies.
Is there any generic approach I should learn? I have a good theoretical grasp of harmony , but I'm looking for some good exercises to learn this in practice on piano. Could you please give me some advice?
Comment: It fairly dependent on the style of tunes you're trying to play. Whatever the tunes are, your bass lines on bass can transfer directly across to l.h. Melody note obviously goes at the highest part of r.h., leaving room for some notes from some chords under with r.h.
Comment: You should get some sheet music for a genre you like and learn how it's put together. There's not much universal about piano music.
Comment: If you can provide what style or styles you intend to play that will help us narrow down generic voicings. Classical is quite different from jazz, which is quite different from pop rock, etc. In classical, chords tend to not have as much "colour" as in other genres. For instance, 9th, 11th and 13th are rarely used in classical music.
Comment: @02fentym I was saying the same as you as answer, but there's a downvote.
Answer: It can be impractical to have the LH providing both a good bass line and chords.  Would you agree with me in considering the order of priority to be:
1: Melody
2: Bass line
3: Chords?
Unless you're accompanying a singer or other melodic soloist when the bass line could take priority.
Unfortunately, piano copies for 'songs' may not be much use.
Above all, watch some good pianists.  Watch, listen and learn.   As so often, a prime conclusion may be 'play less' :-)

Universal piano chord voicings


analysis of alpha lattice design

Question: Are there R some packages for analysis of alpha-lattice (0,1) designed experiment? My experiment includes two factors with two levels. The tests are performed in two replications with twenty blocks. Every block consists of 10 plots.
Answer: The PBIB.test() function in package agricolae can be used for analysis of a field experiment in alpha lattice design.
Please refer the tutorial http://tarwi.lamolina.edu.pe/~fmendiburu/index-filer/download/ENagricolae.pdf , page no. 51 for a detailed worked out example for designing and analyzing an alpha lattice design.

analysis of alpha lattice design


What type of dissonant voice leading is this Bach example?

Question: Dissonances have to be resolved in Bach's style. If you don't resolve dissonance, you're writing is out of style for the period.
Bach's WTC I Fugue in C# minor, BWV 849, has a passage with unresolved dissonance in Bar 92. The soprano voice plays the third subject starting on G#. On the 4th beat, the bass interjects with an A. This forms a major seventh, one of the most dissonant musical intervals.
This has to be resolved, right? Wrong, according to Bach, who leaves this major seventh by moving the bass by a leap(a dissonant leap of an augmented fourth, no less!). This dissonant G# does not fit any non-chord tone description; It is not a passing, neighbor, auxiliary, or suspension tone, so it has to have been formed as a part of a dissonant voice leading chord.
What is this dissonant voice leading chord, and how does it work in other contexts?
Answer: It does resolve. On the third beat of m. 93, the soprano moves to F#, resolving a suspension that actually began in the alto part on the third beat of m. 91.
Notice also that the "real" bass in mm. 92 is the low E followed by the low D# in m. 93 and then a low C# in m. 94 (not shown). The effect is that the bass is split into two voices: one walking from E–D#–C# and the other from B–A–G# (beginning with the final pitch of m. 91). This is how Bach "gets away" with what other seems like a "forbidden" leap. It's just a diatonic sequence in the bass part: B-E, A-D#, G#-C#.
Here are mm. 91 – 93 of the fugue:

And here is a harmonic reduction of the passage from the m. 91 beat 3 to m. 93 beat 3.
Answer: Aaron's answer here has been bothering me a bit, not least because of this claim:

The effect is that the bass is split into two voices: one walking from E–D#–C# and the other from B–A–G# (beginning with the final pitch of m. 91).

I am quite certain that Bach wasn't thinking of this in this way because, well, look at it:
X:1
M:C|
L:1/1
K:C#m bass
[E,,B,,]|[D,,A,,]|[C,,G,,]

A progression by descending fifths and ascending fourths is a much more idiomatic way of thinking about it (and the preceding analysis doesn't explain the A in 92 or the G♯ in 93):
X:2
M:C|
L:1/2
K:C#m bass
E,,A,,|D,,G,,|[C,,

I agree with the basic conclusion that the G♯ does resolve, but I would explain it somewhat differently.  Basically, measures 92 and 93 combine two common moves in a way that is perhaps less common.
The first technique is for a bass part with a sequence of descending fifths and ascending fourths to be harmonized by a voice that alternates between the third and the seventh above the bass.  As with a standard V7-I or V7-i cadence, the dissonant seventh resolves with the chord change rather than before.  For example:
X:3
M:C|
L:1/2
K:C#m bass
%%score {RH|LH}
V:RH clef=treble
GG|FF|E
V:LH
E,,A,,|D,,G,,|C,,
s: ~ 7 ~ 7

Also see the fugue Meine Seele harret from BWV 131:

You can also see this in the C major fugue from WTC Book I, for example at measure 5.
As a bonus, this technique can be used with an additional voice, though it seems more idiomatic for later music:
X:4
M:C|
L:1/2
K:C#m bass
%%score {RH|LH}
V:RH clef=treble
[DG][CG]|[CF][^B,F]|[CE]
V:LH
E,,A,,|D,,G,,|C,,
s: 7 7 7 7
s: ~ ~ ~ ♯

The second technique here is to delay the resolution of the seventh by suspension, which naturally yields a 4-3:
X:5
M:C|
L:1/2
K:C#m bass
%%score {RH|LH}
V:RH clef=treble
G(G|G/)F/F|E
V:LH
E,,A,,|D,,G,,|C,,
s: ~ 7 4~3 7

This is a common cadential formula in Bach's keyboard music, for example at measure 16 of the Goldberg aria.  Another example may be seen in Handel's water music, in measures three and four of the D minor Andante:

This is of course the basic structure of the passage in question, with the addition of the dotted rhythm in the bass:
X:6
M:C|
L:1/2
K:C#m bass
%%score {RH|LH}
V:RH clef=treble
G(G|G/)F/F|E
V:LH
E,,>A,,|D,,>G,,|C,,
s: ~ 7 4~3 7

With the addition of melodic detail, it is a short step to
X:7
M:C|
L:1/2
K:C#m bass
%%score {RH|LH}
V:RH clef=treble
G/c/g/g/|g/f//e//f|e2
V:LH
E,,z/A,,/|D,,z/G,,/|C,,
s: ~ 7 4~3 7 4~3


jQuery - What is the difference

Question: I was examining one of my client's code and came across this.
$(document).ready(function() {
    function foo1() {
        $("#id1").bind('click', function() {});
    }
    foo1();

    function foo2() {
        $("#id2").bind('click', function() {});
    }
    foo2();
});

What they are doing is, attaching event handler inside the function and then calling that function.
How does it differ from the following?
$(document).ready(function() {
    $("#id1").bind('click', function() {});
    $("#id2").bind('click', function() {});
});

That is attaching event handlers directly in $(document).ready() function.
It works fine in both the scenarios, I was just wondering if there are some performance related issues or something. Like one works faster or slower. Or is it a standard way of doing things which I am not aware of.
Comment: If you use JQuery >1.7, you will want to use `.on` instead of `.bind`. For your question, it does the same thing.
Answer: The difference it you can re-use that part of your code to call foo2() at any place in your code again instead of copy the whole code.
EDIT:
Let me give you an example
On failure it needs to show an alert with 'Hello, that was going wrong!' you can do these two things:
alert('Hello, that was going wrong!');

or
function showError() {
alert('Hello, that was going wrong!');
}
showError();

Solution 1 seems to be the easiest one.
But..... Imagine you are  working on a really large project with places to show that error on 1000 places. Now you need to edit your message at 1000 places instead of just one place.
Or when you want to show an HTML popup instead of an alert, imagine changing that.
Hopes the explanation it makes sense, when not please let me know.
Comment: hehe.. yes :)
I understand what you are saying. I was asking if there is some performance related issue. Creatind functions lets you reuse the code.
Comment: There won't be a lot of performance difference, not on this small type of differences. :)

jQuery - What is the difference


Include Views output in href

Question: I am trying to create a custom button in Drupal 7.  The link which the href should be equal to is dependent on the context such as the current UID.
I have created a view which normally has a plain text output as [title].
I want to use that text output as part of a link field such as
http://my-site.com/page/title

so I had written the code for the above link as such:
<a href="http://my-site.com/page/<?php $block = module_invoke('views', 'block_view', 'profile3-block_4'); print render($block[content]); ?>">LINK TEXT

however the output seems as if it is placing part of a views div tag in the link instead. I tried stripping all html from the views block but no success.  Anyone got ideas? Could it be an improper use of quotes?
Answer: You can try like this:
$block = module_invoke('views', 'block_view', 'profile3-block_4');
$url = render($block[content]);
Assume your Output will be
TITLE

then use **$url =  strip_tags($url);**
LINK TEXT
It will be better to use **l()**
l(t('Link text'), 'http://my-site.com/page/'.$url);

If you are still facing issue request you to provide block html output.
Answer: print render($block[content]); returns a lot of tags. It simply cannot be a valid part of URL string. Also, be sure to avoid module_invoke in tpl files if feasible.
Answer: If the url is one of the fields returned in the view query then you could access the raw data of the url by calling views_get_view_result($name, $display_id).
If it returns a uri then you may need to pass it though file_create_url() to get a url.
If the row returns a nid then the url might be generated via something like drupal_get_path_alias('node/' . $nid) (adapt as required for taxonomy terms, users, etc).
Comment: THank you .  I like your comment best. I will give this a try and get back to you
Comment: I assume that $name is the system field name? and $display_id is the block or page delta?
Comment: $name is the machine name of the entire view and $display_id is the machine name of the individual display within the view.  An easy way to find these is to go to the edit page of the view and look at the url.  It should be either "/admin/structure/views/view/VIEW_NAME/edit/DISPLAY_ID" or "admin/structure/views/view/VIEW_NAME", where VIEW_NAME will be replaced with the value you need for $name and DISPLAY_ID will be the replaced with the value you need for $display_id.  If it is the shorter version of the path and there is no $display_id then just call views_get_view_result($name).

Include Views output in href


AngularJS $resource interceptors

Question: How do I add interceptors to a $resource call?
Let's say I have a resource factory called Users, like so;
app.factory('Users', ['$resource', 'resourceInterceptor',
  function ($resource, resourceInterceptor) {
    return $resource(
      'users/:user_id',
      {
        user_id: '@id'
      },
      {
        query: {
          method: 'GET', // Not changing the default method, just adding an interceptor
          interceptor: resourceInterceptor // Is there any better way to do this.. like globally?
        },
        save: {
          method: 'POST', // Same here
          interceptor: resourceInterceptor // Again...
        },
        ..., // And so on
      }
    );
  }]);

and my resourceInterceptor service looks like;
app.factory('resourceInterceptor', ['$rootScope',
  function ($rootScope) {
    return {
      request: function () {
        // This function isn't executed at all?
        $rootScope.loading = true;
      },
      response: function () {
        $rootScope.loading = false;
      },
      responseError: function () {
        $rootScope.loading = false;
      }
    };
  }]);

First of all, the request intercept function is never executed, why not?
Secondly, having to hardcode the interceptor to existing $resource methods is very tedious , is there a way to easier assign interceptors to specific $resource calls, or maybe even assign an interceptor to all $resource calls?
Comment: Hello @Unidan. One year later ... do you have an answer to your question ?
Answer: To use an interceptor in a resource you should:
1 - Make an httpInterceptor with you request, response, responseError:
app.factory('myInterceptor', function () {
    //Code
    //return { request:...,
});

2 - Config this Interceptor in your app:
app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push('myInterceptor');
}]);

Right now as you have config your httpProvider to has an interceptor wherever you inject $http you will use this provider so... you will excute your request, response and responseError funciton.
3 - Using it in a resource.
As $resource use $http and you have config a httpProvider globaly you will call your interceptors' func when you use your resource.
Second question:
You can not set an interceptor to a concrete $http object, they (interceptors) are set globally.
(Even if you set the interceptor before your module definition and then you remove it, you can not know the execution order)
What you can do if you do not want to override the interceptor property in each $resource action (as you write in your question) you can improve your interceptor.
app.factory('userLoadingInterceptor', function () {
    //Code
    return {
        request: function(){
            //Check if your are working with a url related with users
            // and if so do things...
        }
});

Comment: Yeah but is there a way to specifically identify which requests are called through a `$resource` object, and which is just plain `$http`.
Comment: As $resource use $http and as you are defining an interceptor in the $httpProvider. Your interceptor only do things at $http level. I am going to edit my answer
Answer: From the docs:

The interceptor object has two optional methods - response and responseError

I don't know what you want to achieve but generic HTTP interceptors might be an alternative.
Comment: Afaik, the `$resource` service uses `$http`. The docs for `$http` interceptors (https://docs.angularjs.org/api/ng/service/$http#!) has a `request` field.
Comment: @WillB Do you really think the angular docs are wrong? `$resource` uses `$http`, but the interceptors used by `$resource` have no relation whatsoever to the interceptors of the `$http` service. Another alternative might be a decorator for `$resource`.
Comment: No, of course I don't think the docs are wrong. I just can't find the docs for `$resource` interceptors, so I assumed it was the same as `$http` interceptors. (Found it now on my laptop, was on mobile before). Well that sucks. What I want to achieve is a loading bar that is only shown when using a resource. I'll take a look at decorators.
Answer: A generic HTTP Interceptor should do what you want. You can find a sample here: Handle HTTP 302 response from proxy in angularjs.
Comment: Adding an interceptor to the `$http`  service will also trigger when angular loads static assets behind the scenes, which is not desired. Im sure there are ways to detect what kind of request it is, but it feels wrong. I guess I can just make a service that is injected to my controllers and deal with it there.
Comment: You should be able to configure the interceptor to not handle the error based upon the URL.

AngularJS $resource interceptors


C# interface function definition concrete implementation

Question: How do I implement the function defined in the interface below? When I implemented in VS2010 like I have below. MyType gets greyed out and it doesn't recongise the type anymore? thanks!
public interface IExample
{
  T GetAnything<T>();
}

public class MyType
{
  //getter, setter here
}

public class Get : IExample
{
 public MyType GetAnything<MyType>()
 {      ^^^^^^^            ^^^^^^
   MyType mt = new MyType();
   ^^^^^^^^^^^^^^^^^^^^^^^^^^    /* all greyed out !!*/
 }
}

Comment: This has an [XY Problem](http://meta.stackexchange.com/q/66377/4068) feeling to it...
Answer: Make a generic interface IExample<T> and then implement it using the concrete type class Get : IExample<MyType> as in the example below.
public interface IExample<T> where T : new()
{
    T GetAnything();
}

public class Get : IExample<MyType>
{
    public MyType GetAnything()
    {
        MyType mt = new MyType();
        return mt;
    }
}

public class MyType
{
    // ...
}

Comment: The method's type parameter `T` hides the interface's type parameter `T`; they have the same name, but they are independent.
Comment: @phoog yes, thanks. But I think you can drop the method's type parameter. Updated my code example accordingly.
Comment: you forgot a where T: new() on your interface declaration;)
Comment: Yes, I think that's what you intended.  It remains to be seen whether the OP is trying to store homogenous `IExample`s in a single collection; that's usually what people want, and of course it complicates matters somewhat.
Comment: @RaphaëlAlthaus Already added a few minutes ago. But thanks anyway. These are the details I always miss when writing code without the compiler. Once pasted in VS, it becomes obvious.
Comment: @DennisTraub especially if you have ReSharper
Comment: In the interface what is the difference between  IExample{T GetAnything();} vs  IExample {T GetAnything();}
Answer: Dennis' answer looks like what you want but just in case it isn't, in order to get your code working, you can do this but I'm not sure how much value this really has...
public class Get : IExample
{
    public T GetAnything<T>()
    {
        return default(T);
    }
}

public void X()
{
    var get = new Get();
    var mt = get.GetAnything<MyType>();
}


Best option between Task, Thread, Multi-Threading, Parallel, Async/await for my project

Question: As the title says, I'm searching for the most efficient option to use for my program.
Basically my program is doing many I/O tasks ( Opening files, reading them, searching for 4 specific bytes, closing the files )
I have built my program using the normal synchronous method but I feel like the program can work much faster using some of the method listed on the title, which one would be the fastest method to achieve that goal ?
PS : I'm using it on .NET framework instead of .NET core, so please advice me without forgeting that, thanks.
PS2 : I don't want to use any Nuget package too, only the .net framework itself
Comment: Try them out. You can gauge the pros and cons yourself. We are not the developers for your application, so we can't say what's "right" for it.
Comment: IO-bound tasks = async/await. You generally don't want to fire background threads for that (which is what `Task.Run()` and the `Parallel` class do) unless you have a good reason. If needed, you can run parallel asynchronous operations too.
Answer: Just use Task combined with async/await.
Comment: Also Tasks are a single API that allow you to do async method calls, and create long-running background processes (like Thread), or do many Tasks in parallel, like Parallel.ForeEach.
Comment: And why that over Parallel, or threads? What about the OP's code makes this approprate?
Comment: @gunr2171 "Basically my program is doing many I/O tasks"
Comment: I fear such general advice is not the intention of this opinion based question.
Comment: It is mvc or webform? If webform it will be a little hard to implement the async await for the ui(.aspx). Otherwise no issue.
Comment: @gunr2171, Rezo answer is the proper one, your advice about telling how should people learn programming is not, thanks anyways.


closed subset that has the same size

Question: Suppose that $\psi(A)>0$ where $\psi$ is some measure and $A$ is an open set. Is it true that we can always find a closed set such that $B \subseteq A$ and $\psi(B)=\psi(A)$?
I have a follow up question here (what if I change the question to $\psi(B)>0$ instead of $\psi(B)=\psi(A)$):
Existence of closed subset of positive measure
Comment: If the measure is regular, then you can find a closed set $B$ such that $\psi(B)>\psi(A)-\varepsilon$ or instead you can find an $F_\sigma$ set with the same measure of $A$. ($F_\sigma$ - countable union of closed sets - note that any open set is $F_\sigma$ so maybe this comment is irrelevant)
Answer: No. Suppose that $\psi$ is the Lebesgue measure on $\mathbb R$ and that $A=(0,1)$. If $B$ is a closed subset of $A$, then $\psi(B)<1=\psi(A)$.
Answer: No. The reason is that the complement of a closed subset is open and that open sets have a non-zero measure in most of the usual cases.

closed subset that has the same size


How to delete duplicate countries in data frame but keep entry in most recent year (R)?

Question: Suppose we have a data frame with many countries, an example like so:
country year
USA     2018
USA     2017
UK      2015
UK      2013

I want to amend the data frame so that the country only appears once, specifically the one with the most recent year. I.e. I want:
country year
USA     2018
UK      2015

Does anyone know how to do this?
Answer: We can group by 'country' and use slice_max to return the max 'year' for each 'country'
library(dplyr)
df1 %>%
   group_by(country) %>%
   slice_max(year)

-output
# A tibble: 2 x 2
# Groups:   country [2]
#  country  year
#  <chr>   <int>
#1 UK       2015
#2 USA      2018

data
df1 <- structure(list(country = c("USA", "USA", "UK", "UK"), year = c(2018L,
2017L, 2015L, 2013L)), class = "data.frame", row.names = c(NA,
-4L))

Answer: You can also try:
library(dplyr)
#Code
res <- df %>% arrange(country,desc(year)) %>%
  group_by(country) %>%
  filter(!duplicated(country))

Output:
# A tibble: 2 x 2
# Groups:   country [2]
  country  year
  <chr>   <int>
1 UK       2015
2 USA      2018

Some data used:
#Data
df <- structure(list(country = c("USA", "USA", "UK", "UK"), year = c(2018L,
2017L, 2015L, 2013L)), class = "data.frame", row.names = c(NA,
-4L))


Passing array as an argument: C and Java

Question: Before I ask my question, I will note that I know:

In C, we can call a method  by value as well by reference
In Java, we can only call a method by value ( when we pass an Object, we are passing the value of the object reference not the object reference itself )
In C and Java context, there is a difference between pointers and reference.

Now to the question:
Consider an array:
arr = {1,2,3,4,5} //len =5

In C, I can do the following two things:
foo(arr, len);
bar (arr+ 2, len -2);

Function definitions:
foo(int *a, int l) {
  ...
  printf("%d", &a[0];  //prints 1
  ...
}

bar (int *a, int l){
  printf("%d", &a[0];  //prints 3
  ...
}

As we can see array a in function bar starts with the value 3, as it contains the address of arr[2](the original array). This is a neat way of passing arrays in C, if we  want to treat a sub-array as a new array with starting index 0.
I was wondering if same can be achieved in Java not withstanding that the following call has different meanings in C and Java:
foo(arr);

Comment: Both C and Java only have pass-by-value semantics. In C you can pass a pointer by value, and in Java you can pass a reference by value, but both are pass-by-value.
Comment: `2. In Java, we can only call a method by value` it's not true!
Comment: You can always do something like the following in java: foo(array, offset, length)
Comment: Don't Java APIs tend to use `arr, offset, length` to achieve that (passing a slice of an array as argument)?
Comment: Your foo() and bar() functions are exactly the same. Why are you making a distinction in the example?
Comment: @Nathaniel Ford, the difference in the way they are being called and hence the different outputs they print.
Comment: @futurenext110 The output is different because of the input. They're the same function; you should probably think of them that way.
Comment: @JonSkeet To be picky, that isn't entirely true in C. When you pass `type** var`, then you pass a reference-to-a-reference by value, yet `*var` is a reference.
Answer: yes, just add a parameter int off or use the IntBuffer class.
void foo(int[] a,int off, int l) {
 ...
 System.out.printf("%d", a[off];  //prints 1
 ...
 ...
}

f(a,2,l);

void foo(IntBuffer a,int l){
   System.out.printf("%d",a.get(0));
}
IntBuffer buffer = IntBuffer.wrap(a,2,a.length-2);
foo(buffer,l);

Comment: this is a very common java pattern!
Answer: If your question is about whether you can address the elements of the array by doing pointer arithmetic like in arr + 2, then the answer is no.
However, you can achieve the same effect by passing in the array and the position where you want start reading the array.
Answer: The underlying structure of the array in java has an extra element at the head that indicates it's length. So your original array would be {len, 1, 2, 3, 4, 5} as stored by the JVM. This is done to keep java 'safe' from out of index operations on the array. This also makes it almost impossible to do pointer arithmetic in java.
To do something like this in java you would typically use some sort of Buffer class to wrap your array.
Answer: Java lacks native slicing functions (as the implicit one you have in C regarding the start of the array or the explicit ones you have in a few modern languages) but it's easy to build your own class wrapping an array, an index and a length if you need it.
Answer: The idea is the same when you pass arrays in C and Java.
In Java, all that are passed for objects are references to them, namely pointers. In Java, you never say: A *a = new A(); you just write A a = new A(); The lack of * is the difference. Otherwise, A behaves exactly like a pointer.
Primitive variables are passed by value.
Comment: But in Java you can't call "bar (arr+ 2, len -2);"?
Comment: You don't slice arrays in Java, sadly. Also, arr + 2 uses a primitive notation based on what the dereferencing pointer type is. That's not true in Java.


ASP.NET Membership - A design for tracking additional information

Question: I'm working on an ASP.NET4.0/C# application for a public site that needs to authenticate only the employees that work at the associated business. The idea is for the site to have a CMS such that employees can go in and make changes to certain content without having to work with any html.
My question relates to the design and use of a ASP.NET membership provider. I'm not trying to make the site work with an existing database, so there's no need to create my own MembershipProvider for that purpose. However, since each user is an employee, I want to track additional information such as name and office number. I can think of two readily apparent ways to accomplish this:

Use the default SqlMembershipProvider class. As a result, I would need to add the appropriate tables to my database and create a separate table for any "additional" information I want to store. This effectively creates a vertical partition on the user table, since I would use the asp.net-assigned userID as the primary key of the employee table as well. To retrieve the "additional" information, I could ask the provider for information about the current user and requery the database in the event I want to know anything else.
Create one table for all employee information (including login and password) and create my own custom MembershipProvider and MembershipUser classes with the functionality I desire.

I've also considered the use of profiles to store such information, however, the site will publicly contain employee listings, and these pages will need to access some of this information. As a result, I should probably cache this data and it seems like using the serialized fields that profiles provide would cause a problem.
Thus, purely in regards to design... would it be best to make a distinction between a user and an employee and use the default SqlMembershipProvider and associated tables, or write my own user tables that store the information I need and my own MembershipProvider for accessing that information?
Comment: Don't you want to use their AD for authentication, office number etc.?
Comment: Yeah, if I was using Windows Authentication. Their work computers aren't necessarily on the same network though, so Forms Authentication would make more sense.
Answer: If I understand your question correctly, you'd like to store additional user info within the ASP.NET Membership. I've created a number of sites using the following setup.

Install the default .NET Membership using the aspnet_regsql.exe tool
Create a UserProfile table with a uniqueidentifier (PK) UserID column that is linked via a foreign key to the aspnet_Users table
To access that information, all you need is the UserId of a particular User, then you can query your custom table for more information.

Microsoft has written an excellent post on how to do this.
Good luck!
M
Comment: Thanks, M. It looks like the general consensus is option 1, and that post is a good reference when implementing it.
Answer: I am doing something similar, using your option 1. Works great for me.
My business logic has some functions for mutating users. It knows when to touch my users table or the Membership functionality.
Using a custom MembershipProvider for this sort of thing will give you more work than you bargained for.
Answer: SQL Table profile provider (http://weblogs.asp.net/scottgu/archive/2006/01/10/435038.aspx ) will help you do just that.
You will get the power of the Profiles and on the same time not worry about caching or serialization since this provider stores the profile information in clear database table without any serialization. You can use them directly in your queries.


This is a bug in Flink-1.13.1 & HiveCatalog

Question: Flink:1.13.1
Hive:2.1.1—cdh6.2.1
The jar packages in the flink/lib directory are shown below.
enter image description here
When I execute sql-client.sh, I get the following error, which requires me to submit comments to the Apache Flink community.
<code> Exception in thread "main" org.apache.flink.table.client.SqlClientException: Unexpected exception. This is a bug. Please consider filing an issue.
        at org.apache.flink.table.client.SqlClient.startClient(SqlClient.java:201)
        at org.apache.flink.table.client.SqlClient.main(SqlClient.java:161)
Caused by: org.apache.flink.table.catalog.exceptions.CatalogException: A database with name [hive] does not exist in the catalog: [myhive].
        at org.apache.flink.table.catalog.CatalogManager.setCurrentDatabase(CatalogManager.java:295)
        at org.apache.flink.table.api.internal.TableEnvironmentImpl.useDatabase(TableEnvironmentImpl.java:1450)
        at java.util.Optional.ifPresent(Optional.java:159)
        at org.apache.flink.table.client.gateway.context.LegacyTableEnvironmentInitializer.initializeCatalogs(LegacyTableEnvironmentInitializer.java:202)
        at org.apache.flink.table.client.gateway.context.LegacyTableEnvironmentInitializer.initializeSessionState(LegacyTableEnvironmentInitializer.java:105)
        at org.apache.flink.table.client.gateway.context.SessionContext.create(SessionContext.java:233)
        at org.apache.flink.table.client.gateway.local.LocalContextUtils.buildSessionContext(LocalContextUtils.java:100)
        at org.apache.flink.table.client.gateway.local.LocalExecutor.openSession(LocalExecutor.java:91)
        at org.apache.flink.table.client.SqlClient.start(SqlClient.java:88)
        at org.apache.flink.table.client.SqlClient.startClient(SqlClient.java:187)
        ... 1 more
</code>
Comment: StackOverflow is a forum to ask questions - not to report bugs. If you believe you found a bug, report it to the Apache Link community directly. If you are not sure, then it might be more helpful if you rephrase your post as a question, showing an example/sample of your own code, as well as a brief summary of the generated error.
Answer: You have mixed together libraries compiled for different (and incompatible) versions of scala. That's not going to work. Pick either 2.11 or 2.12 and use it consistently.
Comment: I replaced it with the unified Scala 2.12, still reporting the same error.
Answer: This is a bug in flink that we are continuously facing while, we were trying to open the ./sql-client.sh on pyflink Can anyone address this issue. Which requires me to submit comments to the Apache Flink community.
Even I was having only the single version of scala 2.12 within the lib folder of pyflink but it is still giving the below error.
enter image description here
Comment: Please read [Why should I not upload images of code/data/errors?](https://meta.stackoverflow.com/q/285551/354577). Instead, format code as a [code block]. The easiest way to do this is to paste the code as text directly into your question, then select it and click the code block button.


Apache 2.2.14 / mod_auth_kerb 5.4 : Custom krb5.conf for Apache Instance

Question: Objective: Use Apache/mod_auth_kerb using a custom krb5.conf file, not system standard /etc/krb5.conf.
Issue: I've got a strongly regimented environment where we application owners are able to configure apache instances within their assigned directories, but the baseline configuration (OS and Apache core) are maintained by a separate group. As such, any changes I make to core config such as /etc/krb5.conf will mean replicating change to thousands of servers (risk+) or scripting a custom system configuration for this server (risk+,$+).
Model for success: In order to invoke kinit to test or ktutil to generate keytab files for use by Apache in this environment, overloading the KRB5_CONFIG environmental variable (discussed in StackOverflow:pass kinit a custom krb5.conf file)
Question: Is there anyway to specify either the KRB5_CONFIG environmental variable for Apache or force mod_auth_kerb to use another configuration?
Failed Attempts: I've tried running the same env command on the apachectl restart. Apache Directive SetEnv was overlooked as it applies to script execution based on user requests, not to Apache 'backoffice' functions.
Answer: on Red Hat systems I think /etc/sysconfig/httpd is the better place for env vars.
Comment: This is the better answer for most people. You should avoid modifying the init scripts, as shown in the other answer, as they may be replaced whenever updates are installed. (The OP's constraints were just absurd.)
Answer: On most systems there is also an /etc/init.d/httpd that does the original startup of the apache server. I think your only solution is to set an environmental variable in that script and use something like
/sbin/service httpd restart

to restart apache with the new environmental variables. You have to modify the environment of the process that starts httpd somehow.
Comment: I think it's a great answer, given the ridiculous constraints. I don't think it meets the objective as it requires a modification of the base  /etc, but I think you've shown yet another way for it to "not work". But given my research and your answer, I'm willing to put this to bed as "unsolvable" or "bad question".
Comment: Our final solution was to get the admins to to back down and let us have our custom kerberos config. But at least we came with reason in our pockets.


Proving that $\sum_{n=1}^\infty\left(\sqrt[n]{e}-1-\frac 1n\right)$ converges

Question: Problem: Prove that the series
$$S=\sum_{n=1}^\infty\left(\sqrt[n]{e}-1-\frac 1n\right)$$
converges.
My idea is to change $\sqrt[n]{e}$ to $\sqrt[n]{\left(1+\dfrac 1n\right)^n}$, and then try to prove that
$$\sqrt[n]{\left(1+\dfrac 1n\right)^n}-1-\frac 1n<\frac{1}{n^a}$$
for some $a>1$. But I got stuck here. Any idea on how we can move on from here, or is there another approach for this kind of problem?
Comment: You could note that $\sqrt[n]{e} = e^{\frac{1}{n}}$ and consider Taylor expansions, or show that $\sqrt[n]{e} - 1 - \frac{1}{n}$ "behaves like" $\frac{1}{n^2}$ as $n\to\infty$.
Answer: Apply L'hospital's rule twice to deduce that
$$\lim_{x\to 0}\frac{e^x-1-x}{x^2}=\frac{1}{2},$$
hence
$$\lim_{n\to\infty}\frac{e^{1/n}-1-1/n}{1/n^2}=\frac{1}{2}$$
so your series converges.
Answer: For all $n\in\mathbb{C}$ we have the Taylor series expansion of $e^x$ as follows
$$\exp{\left(\frac1n\right)}=\sum_{k=0}^\infty\frac{\left(\frac1n\right)^k}{k!}=\sum_{k=0}^\infty\frac1{n^kk!}$$
Thus for $n\ge1$ we have the inequality
$$\exp{\left(\frac1n\right)}-1-\frac1n=\sum_{k=2}^\infty\frac1{n^kk!}\le\frac1{n^2}\sum_{k=2}^\infty\frac1{k!}=\frac{e-2}{n^2}$$
So by the comparison test the series converges as
$$\sum_{n=1}^\infty\left(\exp{\left(\frac1n\right)}-1-\frac1n\right)\le\sum_{n=1}^\infty\frac{e-2}{n^2}=\frac{(e-2)\pi^2}6$$
Comment: Clever solution,+1
Answer: Hint:
Taylor gives for $0\leq x\leq 1$
$$0\leq e^x - 1-x \leq \frac{e}{2}x^2$$
Now, compare the series with $\frac{e}{2}\sum_{n=1}^{\infty}\frac{1}{n^2}$.


Windows Service to Watch the Downloads Directory for Files in C#

Question: I am fairly new to the Windows world, as most of my primary development is with UNIX systems. A specific request from a customer came in and asked if I could write a windows service to watch the Downloads folder for any downloaded content, and move it to their Documents folder. For some reason they didn't want to just change their default download directory on their browser.
So to give the customer what they asked I thought I would give it a shot. Here is my attempt:
    protected override void OnStart(string[] args)
    {
        watch();
    }

    public void OnDebug()
    {
        OnStart(null);
    }

    protected override void OnStop()
    {
    }

    String path = null;
    private void watch()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        string pathUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        path = Path.Combine(pathUser, "Downloads");
        watcher.Path = path;
        watcher.NotifyFilter = NotifyFilters.LastWrite;
        watcher.Filter = "*.*";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        String pUser = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        String directoryName = Path.Combine(pUser, "Documents"); ;
        DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
        if (dirInfo.Exists == false)
            Directory.CreateDirectory(directoryName);

        List<String> MyFiles = Directory
                           .GetFiles(path, "*.*", SearchOption.AllDirectories).ToList();

        foreach (string file in MyFiles)
        {
            FileInfo mFile = new FileInfo(file);
            // to remove name collusion
            if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
                mFile.MoveTo(dirInfo + "\\" + mFile.Name);
        }
    }

I tested my code in debug mode and when the service is running and I go to download a file, the download fails. Visual Studio then pops up with this error:
"An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file because it is being used by another process."
The error is thrown on:
mFile.MoveTo(dirInfo + "\\" + mFile.Name);
How can I fix this?
Comment: why don't you acquire the lock before moving the file , that way even if the file is still being downloaded you can wait till that finishes and the move it , of course you can make if perf better by trying the failed files after the first attempt and just taking lock on those. You will need to wrap it with try/catch for the first time
Comment: @loneshark99 what your describing makes sense, but I'm unfamiliar with C#. I just added a try/catch condition, which I should've done to begin with. Can you please elaborate on the locking?
Comment: Also do you really need a Windows service , you could just use robocopy and sync at regular time interval  as a scheduled job
Answer: Your download begins and a temporary file is created in the downloads folder which begins to receive the download stream. As soon as the temporary file is created however, your mover application attempts to intercept and move the file which is obviously locked by another process because the download client is still writing to it.
Perhaps you could cache a list of files in the download folder along with file size and check on it to make sure the size isn't changing before you do the move. You could also exclude known extensions associated with downloading. Eg. *.temp, *.downloading
As you are dealing with a live file system where the user could lock a file at any time, you may also want to deal with locked file exceptions a bit more gracefully.


Pick out the true statements regarding the properties of functions

Question: Pick out the true statements:
a. $|\cos^2 x − \cos^2 y| \le|x − y|$ for all $x, y \in \mathbb{R}$.
b. If $f : \mathbb{R} \to \mathbb{R}$ satisfies
$|f(x) − f(y)|\le|x − y|^{\sqrt{2}}$for all $x, y \in \mathbb{R}$ then $f$ must be a constant function.
c. Let$f : \mathbb{R} \to \mathbb{R}$ be continuously differentiable and such that $|f'(x)|  \le4/5$ for all $x \in \mathbb{R}$. Then, there exists a unique $x \in \mathbb{R}$ such that $f(x) = x$.

(a) using Lagranges theorem I get that this is true.
But I have no idea about the others.Can I get some help please?
Comment: "Lagranges theorem" = "Mean Value Theorem"?
Answer: Note that since $\sqrt{2}>1$, then we have
$$
0\leq \lim\limits_{y\to x}\frac{\vert f(x)-f(y)\vert}{\vert x-y\vert}\leq \lim\limits_{y\to x} \vert x-y\vert^{\sqrt{2}-1}=0
$$
Therefore, the limit in the middle exist and is equal to zero. What does this tell you about $f$ and its derivative?
For the last point, note that this implies that $\vert f'(x)\vert <1$. If there would exist two points $y$ and $x$ suche that $f(y)=y$ and $f(x)=x$, what would implie the Lagrange theorem that you used in a)?
Since for every $x, y$ and for some $c$ between them we have
$$
\vert f(x)-f(y)\vert=\vert f'(c)\vert\vert (x-y)\vert \leq\frac{4}{5} \vert x-y\vert
$$
Then, $f$ is a contracting mapping and we can use the Banach fixed point theorem  to show the existence of such an $x$
Comment: How would we know if this $x$ and $y$ actually exists?
Comment: No, the argument is to show that there exist at most one point $x$ such that $f(x)=x$ (those points are called fixed points}. I forgot to suggesr how to shoe the existence. I will fix it
Comment: Oh I see, you were going for some sort of contradiction.
Comment: For existence, you can integrate the inequality $-4/5 \le f'(x) \le 4/5$.
Comment: Ah okay, thanks. I up vote you
Answer: For part c), here is an alternate solution for the existence of a fixed point on $f$. If $|f'(x)| \le a$ for $0<a<1$, we have:
$-a \le f'(x) \le a$, which maybe integrated to $-a x + b \le f(x) \le a x + b$, and so
$$(-a-1)x + b \le f(x) - x \le (a-1)x + b$$
Since $(a-1)$ is not zero, one can find a sufficiently large $x$ so that $f(x) - x$ is negative.
Since $(-a-1)$ is not zero, one can find a sufficiently small $x$ so that $f(x) - x$ is positive.
Intermediate value theorem guarantees that $f(x) - x = 0$ for some $x$.
Intuitive picture: (two lines, opposite slopes, absolute value less than one; the line $y=x$. The three lines form a triangle. There is a part of $f$ that is trapped in the triangle, and it has no choice but to go through $y=x$.)


UpdatePanel - Always e conditional juntos

Question: Tenho uma duvida.
É possível disparar evento somente no updatePanel conditional sendo que ele está dentro de outro que não é conditional?
Segue o exemplo:
<asp:UpdatePanel runat="server" ID="upPagina">
<ContentTemplate>
    <asp:UpdatePanel ID="updatePanelGridView" runat="server" UpdateMode="Conditional">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="btnInserirGrid" EventName="Click" />
        </Triggers>
        <ContentTemplate>
        </ContentTemplate>
    </asp:UpdatePanel>
</ContentTemplate>

Answer: Descobri o que era.
Criei o metodo onInit e inseri o
scriptmanager1.EnablePartialRendering = false;

Resolveu.


Please verify my proof of: There is no integer $\geq2$ sum of squares of whose digits equal the integer itself.

Question: While going to sleep, I just started thinking about numbers, their squares, cubes and after thinking for about $20$ minutes I got that:

There is no integer (having any numbers of digits) except $0$ and $1$, sum of squares of whose digits is equal to number itself.

Isn't it interesting ??
Now I came out blanket and started writing everything on paper (Or started finding a proof of what I have got).
MY WORK
Suppose there exist an integer $a_0a_1a_2.......a_{n-1}$  having n digits.
Firstly, we can easily exclude negative integers from the race as the number will be negative and sum of squares will be positive (we can never equate negative and positive).
Now comes the turn of non negative integers.
As we have assume that there exist an integer which satisfy our condition so, it should yield us:
$$10^{n-1}a_0+10^{n-2}a_1+.........10a_{n-2}+a_{n-1}={a_0}^2+{a_1}^2+.......{a_{n-2}}^2+{a_{n-1}}^2$$
Which on further solving becomes,
$$a_0(10^{n-1}-a_0)+a_1(10^{n-2}-a_1)+.........+a_{n-2}(10-a_{n-2})+a_{n-1}(1-a_{n-1})=0$$
$$a_0(10^{n-1}-a_0)+a_1(10^{n-2}-a_1)+.........+a_{n-2}(10-a_{n-2})=a_{n-1}(a_{n-1}-1)$$
Now, the hardest part for me comes:
The terms of left are all positive and they increase as we keep on going towards left.
We can only compare the terms $$a_{n-1}(a_{n-1}-1)$$ and $$a_{n-2}(10-a_{n-2})$$ because the shortest of other terms is too far from comparison.
Now if we make some comparison, we will have $$a_{n-1}(a_{n-1}-1)=a_{n-2}(10-a_{n-2})$$
Now let's form a table for the function on RHS:
$$\begin{array}{c|c}
a_{n-2}&            a_{n-2}(10-a_{n-2})\\\hline
0&                         0\\
1&                         9\\
2&                         16\\
3&                         21\\
4&                         24\\
5&                         25\\
6&                         24\\
7&                         21\\
8&                         16\\
9&                         9
\end{array}$$
Again, we form a table and this time for the function on LHS:
$$\begin{array}{c|c}
a_{n-1}&                       a_{n-1}(a_{n-1}-1)\\\hline
0&                                  0\\
1&                                  0\\
2&                                  2\\
3&                                  6\\
4&                                 12\\
5&                                 20\\
6&                                 30\\
7&                                 42\\
8&                                 56\\
9&                                 72
\end{array}$$
Now we have all possible values of  $a_{n-1}(a_{n-1}-1)$ and  $a_{n-2}(10-a_{n-2})$ and A quick look at tables yield that the only common value $a_{n-1}(a_{n-1}-1)$ and  $a_{n-2}(10-a_{n-2})$ have is $0$.
So the condition is followed when ($a_{n-1}$ ,$a_{n-2}$ )=($0,0$) and ($1,0$). Or $1$ and $0$ are the only numbers which follow the condition.{ There is no integer (having any numbers of digits) except $0$ and $1$, sum of squares of whose digits is equal to number itself is proved}.
I hope you guys will understand that such questions are hard to write (specially for someone like me who is a beginer at Mathjax). So, if you have any problem in understanding, leave comment. I shall be thankful if someone can verify my proof or can give a new one (with completely different approach). You can suggest modification in my work or give suggestion that where it can be improved.Thanks
Comment: LONE WOLF It may give you conditions on the length of the resulting number when you sum squares of digits.
Comment: Side note:  I, too, am puzzled by the downvote (and have upvoted the post).  The OP states a clear, non-trivial, question and shows a very fleshed out argument in support of the proposed solution.  What more can one ask?
Comment: In general if you wprk with a fixed power of the digits of a number $\overline {a_{1}\ldots a_{n}}$, since $ a_{1}^k+\ldots a_{n}^k\le n9^k$, but $10^{n-1}\ge n9^k $, so there are only finitely values for $ n $.
Comment: The number of digits of a number will be of the magnitude of its logarithm, you can also work with that.
Comment: @mathma, I knew that. But how it is going to help me here??
Comment: Since this question hit the HNQ list, please oh please give it a more descriptive title.
Comment: @user2943160 I was thinking about this too. What shoud be title in your opinion. Any suggestion??
Answer: Your argument is good, though a little vague at the end.  I would tighten it up by remarking that $$a_{n-k}>0\implies a_{n-k}\left(10^{n-1-k}-a_{n-k}\right)>1\times \left(10^{n-1-k}-9\right)$$ which is greater than $99$ for all the terms you wish to discard. In that way, you reduce the problem to two digit cases, and you resolve those correctly.
An algebraically simpler argument:  If your integer has $n$ digits, then the sum of squares can be at most $81n$.  But we have $$10^{n-1}≤81n\implies n≤3$$ so your number can have at most $3$ digits.  Noting that $81\times 3= 243$ we see that in fact we only have to check up up $243$. This can easily be checked by (mechanically assisted) hand.
Comment: Your argument gets a little hazy at the end...with "the shortest of the other terms is too far from comparison".  You need to bound the terms explicitly, for example the right hand is at most $72$.  If you do that, I expect you'll end up with my argument.  Maybe you can do better and show that the number can have at most $2$ digits...that would make it a paper and pencil problem.
Comment: Indeed, the third term, $a_{n-3}(10^2-a_{n-3})≥99$ which, of course, is greater than $72$.  Thus your equality rules out three digit numbers.  So...I agree, your method significantly reduces the finite set you need to look at.  I stopped as soon as I got to a finite collection that was easy to run on the computer.  Your method is better in that it reduces the problem to something you can easily check by hand.
Comment: I would tend to agree with @Charter  ....  As the article I linked to on [Narcissistic Numbers](http://mathworld.wolfram.com/NarcissisticNumber.html) shows, people have gone over all these.  And I'd agree with the author of that article that, to date, nobody has found good number theoretic properties of these numbers...making the problems more interesting as puzzles than anything else.  They are definitely good puzzles though.
Comment: That's alright, but is there any problem in my proof??
Comment: Okay, thanks @lulu
Comment: Note:  you might find it interesting to read about [Narcissistic Numbers](http://mathworld.wolfram.com/NarcissisticNumber.html).  There are some good puzzles along these lines (for example, if you start with a number divisible by $3$ and you repeatedly add the sum of the cubes of the digits, you always end up with $153$).
Comment: Thanks @lulu. I was baffled by the downvote. By the way, now I have two solutions of the the theorem (or the fact)
Comment: can I submit this thing somewhere??
Comment: Honestly, this is more like an exercise in number theory.
Comment: Okay, thanks guys. I have conjectured its extension and i m working on that. Soon I will discuss with you @lulu
Answer: The problem requires
$$
\begin{align}
0
&=\sum_{k=0}^n\left(10^kd_k-d_k^2\right)\\
&=\sum_{k=0}^nd_k\left(10^k-d_k\right)
\end{align}
$$
The only negative term can be $d_0(1-d_0)\ge-72$.
For $k\ge2$, if $d_k\ne0$, then $d_k\left(10^k-d_k\right)\ge10^k-1\ge99$.
Therefore, only $d_0,d_1$ can be non-zero. So we just need to find $d_0,d_1$ so that
$$
d_1(10-d_1)=d_0(d_0-1)
$$
However
$$
d_1(10-d_1)\in\{0,9,16,21,24,25\}
$$
while
$$
d_0(d_0-1)\in\{0,2,6,12,20,30,42,56,72\}
$$
The only way they can be equal is if both are $0$ and that requires $d_1=0$ and $d_0\in\{0,1\}$.
That is, the only solutions are $0$ and $1$.
Your proof was a bit difficult to read, but it looks similar.


convert float values in dictionary into two decimal places

Question: Note, using Python 2.4.  Here is a dictionary I have called d_ourbook:
 {'130405C00465000': [[8.6999999999999993, 8.9000000000000004, 0.50749999999999995, 32.810000000000002, -141.1575]]}

The value is a list of floats.  I am trying to make a function that displays the same dictionary, but with values limited to two floating points.
I made a floating point --> 2decimal string function called two(floatnum):
def two(floatnum):
    return '%.2f' %(floatnum)

My function to loop or zip through the dictionary and convert all the values to two(value) have been a nightmare and returns float argument required:
Traceback (most recent call last):
  File "esecombo.py", line 496, in ?
    print ' -- dt: ', dt(d_ourbook)
  File "esecombo.py", line 23, in dt
    new_d_name = dict(zip(d_name.keys(), [two(value)for value in d_name.values()]))
  File "esecombo.py", line 10, in two
    return '%.2f' %(floatnum)
TypeError: float argument required

Any help would be a lifesaver.
Answer: Assuming that d_name is the dictionary you provided, then d_name.values() is a list of lists of lists of floats. So value is a list of lists of floats and you cannot hand that to two() without an error.
Even if you get that resolved the zip returns a number of tuples base on the shortest argument.
So that:
new_d_name = dict(zip(d_name.keys(),
                      [two(value) for value in (d_name.values()[0][0])]))

results in {'130405C00465000': '8.70'}
This assumes that all values are of the single item list in list type as in the example, in that case you probably could use:
new_d_name = dict(zip(d_name.keys(),
                      [[two(value) for value in (d_name.values()[0][0])]]))

to get:
{'130405C00465000': ['8.70', '8.90', '0.51', '32.81', '-141.16']}


Calculating conditional probability

Question: Let's consider I have the pair of distributions:
\begin{align}
X|t &\sim Binomial(n,t)  \\
t &\sim Beta(a,b)$
\end{align}
Here $n,a,b$ are known.
I need to construct conditional probability to sample from it, $t|X$. In this example I can do this analytically:
$$t|X \sim Beta(x+a,n-x+b)$$
But how can I do this in general case, for any distributions, either numerically or somehow else?
Answer: In general, you will do it the way you did in this case: you will compute the posterior using Bayes's Theorem. Unfortunately, in general, it won't be the case that the posterior has a nice identifiable simple form (your example is the nicest possible: the case of a conjugate prior). In general, you will have to use some Monte Carlo solution. The Metropolis-Hastings algorithm allows you to explore any posterior, in principle, but there are limitations: simple versions of the algorithm, such as Random Walk Metropolis, may not perform well if you have a multivariate posterior which exhibits extremely high correlations between its components. When you can sample from the full conditionals, Giggs Sampling (which can be seen as a particular case of Metropolis-Hastings) is probably the way to go. Check this for more information. Also, it may be the case that your problem needs an approximation technique such as ABC, which is a hot topic nowadays.

Calculating conditional probability


text to dataframe in r

Question: I have a problem in making a dataframe with a text in R.
my text is like this:
t1 = "[[1,5,3,4],[3,2,2,1],[19,11,1,1]]"

and I want to make this dataframe:
     V1 V2 V3 V4
  1  1  5  3  4
  2  3  2  2  1
  3 19 11  1  1

Comment: `jsonlite::fromJSON(t1)`
Comment: notice result is not a dataframe; it is a matrix.
Comment: wow thank you it works well! @DavidArenburg <3
Answer: To combine the comments, you need to do:
yourDf <- as.data.frame(jsonlite::fromJSON(t1))

text to dataframe in r


How to theme "My Results" (quiz module) tab that´s inside the user´s profile?

Question: I´m using quiz module in Drupal 7, and need to theme the output in "My Results" (wich is a tab in the user profile page).
Here´s the module´s function :
// THEME FUNCTIONS

/**
 * Theme the user results page.
 *
 * @param $results
 *  An array of quiz information.
 * @return
 *  Themed html.
 *
 * @ingroup themeable
 */
function theme_quiz_get_user_results($variables) {
  $results = $variables['results'];
  $rows = array();

  while (list($key, $result) = each($results)) {
    $interval = _quiz_format_duration($result['time_end'] - $result['time_start']);
    $passed = $result['score'] >= $result['pass_rate'];
    $grade = $passed ? t('Passed') : t('Failed');
    $passed_class = $passed ? 'quiz-passed' : 'quiz-failed';
    if (!is_numeric($result['score'])) {
      $score = t('In progress');
    }
    elseif (!$result['is_evaluated']) {
      $score = t('Not evaluated');
    }
    else {
      if (!empty($result['pass_rate']) && is_numeric($result['score'])) {
        $pre_score = '';
        $post_score = ' %
' . $grade . '';
      }
      else {
        $post_score = ' %';
      }
      $score = $pre_score . $result['score'] . $post_score;
    }
    $rows[] = array(
      'title'       => l($result['title'], 'node/' . $result['nid']),
      'time_start'  => format_date($result['time_start'], 'short'),
      'time_end'    => ($result['time_end'] > 0) ? format_date($result['time_end'], 'short') . '
' . t('Duration :  @value', array('@value' => $interval)) : t('In Progress'),

      'score'       => $score,
      'evaluated'   => $result['is_evaluated'] ? t('Yes') : t('No'),
      'op'          => l(t('View answers'), 'user/quiz/' . $result['result_id'] . '/userresults'),
    );

  }

  if (empty($rows)) {
    return t('No @quiz results found.', array('@quiz' => QUIZ_NAME));
  }

  $header = array(
    t('@quiz Title', array('@quiz' => QUIZ_NAME)),
    t('Started'),
    t('Finished'),
    t('Score'),
    t('Evaluated'),
    t('Operation'),
  );

  $output = theme('table', array('header' => $header, 'rows' => $rows));
  $output .= '
' . t('@quizzes that are not evaluated may have a different score and grade once evaluated.', array('@quizzes' => QUIZ_NAME)) . '
';
  return $output;
}

Now, all I need is to theme the output, and maybe add some special header before the results.
I´ve tried this at my template.tpl.php file, without any success:
function mythemename_quiz_get_user_results($variables) {
print "This is some information";
print "
";
print $variables;
print "
";
}

Now I know that print $variables; isn´t the way it should print an array, but the way to do this in Drupal 6 was this (I´ve took this code from an issue in Drupal´s forums):
function phptemplate_quiz_get_user_results($results) {
  // $results - An array of quiz results.
  // overriding statements
  print_r($results);
}

The function´s name changed, but the process shouldn´t be similar?
Thanks for your help!
Comment: template.tpl.php file ? If you mean template.php then this should work, you will have to clear the cache though.
Comment: Yes, I´m sorry, I mean template.php. But after clearing the cache, it didn´t worked either... That´s why I thought that maybe the code to print the variables is wrorng.
Comment: oh....so your function is being called? The variable sent to the function is an array, so your can't just print it. Maybe just copy and paste the original function and alter it to add what you need. If your function is not being called, double check the name of your function, I often get caught out by typos in function names.
Comment: Thanks for your reply! The thing is that if I print "function mythemename_quiz_get_user_results($variables) {   print_r($variables);" they do print (without any format, because of the print_r() statement), but if I try "print $variables;" they won´t.
Comment: print is for printing strings, you will have to print each part of the array separately. The same way the original theme_quiz_get_user_results does.
Comment: Thanks!!! So, I´ll just paste the whole function into the template file and then do whatever I need to. How shall I mark that as the accepted reply?
Comment: I have added an answer.
Answer: Copy and paste (and rename) the original theme function to your template.php file, than just change what you need. Remembering that $variables is an array. Use the dpm function of the devel module to look at what values are in $variables that you can use.


Postorder and Preorder traversal on a Binary tree

Question: For the tree below, list the labels of the nodes of the tree according to the pre-ordering algorithm, and then re-list them according to the post-ordering algorithm.
<code>                                    1
                                   / \
                                  2   3
                                 / \   \
                                4   5   6
                               / \     / \
                              7   8   9   10
</code>

Is my attempt correct I always get confused between the traversal methods:
Pre-ordering: 1, 2, 4, 7, 5, 8, 3, 6, 9, 10
Post-ordering: 7, 8, 4, 5, 2, 9, 10, 6, 3
Answer: Looks good; you just made a couple errors. The pre-order traversal should be:
$$
1, 2, 4, 7, \color{red}8, \color{red}5, 3, 6, 9, 10
$$
and the post-order should finish at the root, $1$.
Comment: Ok so you take the bottom right branch in situations like that.
Comment: Thanks I forgot about that root
Comment: Yes. For the tree rooted at $2$, all nodes in the left subtree (namely, $4,7,8$) should be traversed before all nodes in the right subtree (namely, $5$).
Comment: Nice explanation I was not thinking in terms of sub-trees.


Equation of tangent perpendicular to line

Question: I've got the homework question which I cannot solve.

Find the equation of the tangents to $4x^2+y^2=72$ that are
  perpendicular to the line $2y+x+3=0$.

What I have done so far:
I have found the gradient of the line which is $m_1 = -\frac12$.
Which means that the equation perpendicular to the tangent of $4x^2+y^2=72$ is $m_2 = 2$, since $m_1m_2 = -1$.
I've found the derivative of $4x^2+y^2=72$ which is $\dfrac{dy}{dx} = -\dfrac{4x}{y}$.
The next thing I have done is set $m_2=\dfrac{dy}{dx}$.
Now what?
Comment: Looks right so far, so we get $-4x/y=2$. Substitute in the equation of the ellipse. To diagnose your answer, one would have to know what it is.
Comment: What do you mean by substitute in the equation of the ellipse?
Comment: I wrote out a solution.
Answer: $$2y+x+3=0$$
The important thing is that you know what being perpendicular means. In terms of slopes, one line has to have a slope that's equal to the negative reciprocal of the other. This is a property you should know from your Algebra class. For this problem, we want to find the slope of the line that's perpendicular to the line we have above. To do that, we will first need to find the slope of the line above. Let's rearrange stuff to find it:
$$2y=-x-3 \\ y=-\frac12x-1.5$$
You can get $\frac{dy}{dx}$ of this, but really it's in the form of $y=mx+b$ and we know that the slope of this line is $-\frac12$. Thus, the slope of the line perpendicular to this one is $2$.
$$4x^2+y^2=72$$
We've got the slope, but not the line yet. We want to find a line that will be tangent to the ellipse that was given. How do we find that? Start with finding the point at which it is tangent. You probably already know how to do this. First take the derivative. For this problem, implicit differentiation is not a really good idea. Thus, isolate for $y$ first and then solve it:
$$y=\sqrt{72-4x^2}$$
$$\frac{dy}{dx}=\frac12 \left(72-4x^2\right)^{-\frac12}(-8x)$$
Now that you have the derivative, find the value for $x$ where the slope of the ellipse is the same as the perpendicular line. In other words, $\frac{dy}{dx}=2$:
$$2=\frac12 \left(72-4x^2\right)^{-\frac12}(-8x)$$
A little messy, but you'll find that $x=\pm3$. Therefore the point on the ellipse where the tangent will have this slope is $(\pm3, \pm6)$ (plugged in to the original to get the $y-$value). From this point, you can easily get the line now. You've got $y=mx+b$. $m$ is $2$, and now to find $b$ we'll plug in $x/y$:
$$6=(2)(-3)+b$$
$$b=12$$
Or for $x=3$, $b=-12$.
Our final answer ends up being:
$$\therefore y=2x\pm12$$
Pictorial proof:
Comment: Thanks for the detailed answer. :)
Answer: HINT :
You found $m_1=-\dfrac{1}{2}$ and $m_2=2$. This is correct. Then
$$
\begin{align}
4x^2+y^2&=72\\
y^2&=72-4x^2\\
y&=\sqrt{72-4x^2}\\
\frac{dy}{dx}&=\frac{d}{dx}(72-4x^2)^{\Large\frac12}\\
m_2&=\frac12(72-4x^2)^{-\Large\frac12}(-8x)\\
2&=-\frac{4x}{\sqrt{72-4x^2}}\\
\sqrt{72-4x^2}&=-2x\\
72-4x^2&=(-2x)^2\\
72-4x^2&=4x^2\\
x^2&=9\\
x&=\pm3
\end{align}
$$
Answer: Let the point of tangency be the point  $(x,y)$ on our curve. Your calculation shows that $\frac{-4x}{y}=2$, that is, $y=-2x$.
Also, we have $4x^2+y^2=72$. Substituting $-2x$ for $y$ in this equation, we get $8x^2=72$, and therefore $x=\pm 3$. That gives the two points $(3,-6)$ and $(-3,6)$.
The line with slope $2$ through $(3,-6)$ has equation $y-(-6)=2(x-3)$, which simplifies to $y=2x-12$. The other line has  equation $y=2x+12$.
Comment: You are welcome. For no very good reason, I would have chosen $(a,b)$ as the coordinates of the point on the curve, and solved for $a$ and $b$. Same calculation, just a change of name.


Is it possible to import other xquery modules in marklogic CPF action module?

Question: I am using MarkLogic CPF framework.
When a document is inserted in a particular collection a XQuery module will be invoked let's say create-doc.xqy.
I have configured the domain to have all the xquery modules in documents database under path /create/xquery/modules/*.xqy
Path for create-doc.xqy will be /create/xquery/modules/create-doc.xqy
Is it possible to import other xquery modules in create-doc.xqy and use it's methods?
Answer: From your description, it appears that the chapter related to importing modules is what you are looking for:
https://docs.marklogic.com/guide/app-dev/import_modules
Answer: There are two approaches to doing this

Just insert your xqy file in the MarkLogic Database on which the CPF is defined(not modules DB) and now you can refer it from the CPF actions.
The second method is to put the module in the "Modules" directory in MarkLogic installation folder. Now you can refer it from the CPF action same as you import search module to use "search:search" method.


Code works on localhost but not on server

Question: I have just launched my clients site to a temporary URL so they can do data input while i finish up on CSS and finishing touches. When I launched the site however, I found that part of it broke, the culprit being a custom-post slider. I don't understand why it's breaking as it works perfectly fine on my localhost.
I am using a pkg called Flickity, and it has been treating me very well up until now. I am using other Flickity sliders on my site, so I know that FLickity itself is not the problem. I have attached below my code for the slider.
The Custom Posts are Theatre Productions, and are meant to be ordered according to the closing performance date: ending_date [ACF].

    Our Productions

    <?php // query posts
      $params = array(
        'post_type' => 'productions',
        'post' => $id,
        'posts_per_page' => -1,
        'meta_key' => 'ending_date',
        'orderby' => 'meta_value',
        'order' => 'ASC',
      );

      $slider_posts = new WP_Query($params);
    ?>

    <?php if ( $slider_posts->have_posts() ) while ( $slider_posts->have_posts() ) : $slider_posts->the_post(); ?>

      <?php date_default_timezone_set('America/New_York');
        $slider_link = get_permalink();
        $starting_date = get_field('starting_date');
        $ending_date = get_field('ending_date');
        $location = get_field('location');
        $prod_link = get_permalink();
        $todays_date = date(Ymd);
        ?>

      <?php if (($todays_date<=$ending_date) and ($todays_date>=$starting_date)): ?>

          <a href="<?php echo $slider_link; ?>" class="slider-link">
            <?php the_post_thumbnail('hero'); ?>

                <?php the_title(); ?>

              <?php
                $end = date_create_from_format('Ymd',$ending_date);
                $start = date_create_from_format('Ymd',$starting_date);
                echo "" . $start->format('F') . "";
                echo " ";
                echo "" . $start->format('j') . "";
                echo ", ";
                echo "" . $start->format('Y') . "";

                echo " - ";

                echo "" . $end->format('F') . "";
                echo " ";
                echo "" . $end->format('d') . "";
                echo ", ";
                echo "" . $end->format('Y') . "";
                echo ", $location";
               ?>

                <?php echo wp_trim_words( get_the_content(), 40, '...' ); ?>

                Now Playing

      <?php endif ?>

    <?php endwhile; ?>

    <?php // query posts
      $params = array(
        'post_type' => 'productions',
        'post' => $id,
        'posts_per_page' => -1,
        'meta_key' => 'ending_date',
        'orderby' => 'meta_value',
        'order' => 'DEC',
      );

      $slider_posts = new WP_Query($params);

      $array_rev = array_reverse($slider_posts->posts);
      //reassign the reversed posts array to the $home_shows object
      $slider_posts->posts = $array_rev;
    ?>

    <?php if ( $slider_posts->have_posts() ) while ( $slider_posts->have_posts() ) : $slider_posts->the_post(); ?>

      <?php date_default_timezone_set('America/New_York');
        $slider_link = get_permalink();
        $starting_date = get_field('starting_date');
        $ending_date = get_field('ending_date');
        $location = get_field('location');
        $prod_link = get_permalink();
        $todays_date = date(Ymd);

        ?>

      <?php if (($todays_date<$ending_date) and ($todays_date<$starting_date)): ?>

          <a href="<?php echo $slider_link; ?>" class="slider-link">
            <?php the_post_thumbnail('hero'); ?>

                <?php the_title(); ?>

              <?php
                $end = date_create_from_format('Ymd',$ending_date);
                $start = date_create_from_format('Ymd',$starting_date);
                echo "" . $start->format('F') . "";
                echo " ";
                echo "" . $start->format('j') . "";
                echo ", ";
                echo "" . $start->format('Y') . "";

                echo " - ";

                echo "" . $end->format('F') . "";
                echo " ";
                echo "" . $end->format('d') . "";
                echo ", ";
                echo "" . $end->format('Y') . "";
                echo ", $location";
               ?>

                <?php echo wp_trim_words( get_the_content(), 40, '...' ); ?>

                Coming Soon

      <?php endif ?>

    <?php endwhile; ?>

    <?php // query posts
      $params = array(
        'post_type' => 'productions',
        'post' => $id,
        'posts_per_page' => -1,
        'meta_key' => 'ending_date',
        'orderby' => 'meta_value',
        'order' => DEC,
      );

      $slider_posts = new WP_Query($params);
    ?>

    <?php if ( $slider_posts->have_posts() ) while ( $slider_posts->have_posts() ) : $slider_posts->the_post(); ?>

      <?php date_default_timezone_set('America/New_York');
        $slider_link = get_permalink();
        $starting_date = get_field('starting_date');
        $ending_date = get_field('ending_date');
        $location = get_field('location');
        $prod_link = get_permalink();
        $todays_date = date(Ymd); ?>

      <?php if ($ending_date<$todays_date): ?>

          <a href="<?php echo $slider_link; ?>" class="slider-link">
            <?php the_post_thumbnail('hero'); ?>

                <?php the_title(); ?>

                <?php echo wp_trim_words( get_the_content(), 40, '...' ); ?>

                Past Production

      <?php endif ?>

    <?php endwhile; ?>

    <?php $prod_link = get_permalink(11); ?>

      <a href="<?php echo $prod_link; ?>" class="slider-news">

READ MORE

After checking the console errors in my Dev Tools, it came up with the following errors. Any Suggestions?
Uncaught ReferenceError: jQuery is not defined
    at jquery-migrate.min.js:2
(index):87 Uncaught ReferenceError: jQuery is not defined
    at (index):87
Comment: maybe links are broken. try to check the scripts and stylesheets if it's loaded successfully
Comment: See edited question with Console Errors Above!
Answer: You should debug your error, use developer tool of the browser and check for console errors it will show you all, I think all the files are not uploaded properly or their can be permissions issues on your uploaded files and folders you can check and update permissions from filezilla or any other ftp client you used
Comment: These are the errors that appear. Any Suggestions?

Uncaught ReferenceError: jQuery is not defined
    at jquery-migrate.min.js:2

Uncaught ReferenceError: jQuery is not defined
    at (index):87


Logic for grouping similar parameters

Question: I am trying to figure out the best logic for grouping parameters within a certain tolerance. It's easier to explain with an example...
Task1: parameter1=140
Task2: parameter1=137
Task3: parameter1=142
Task4: parameter1=139
Task5: parameter1=143

If I want to group tasks if they are within 2 of each other, I think I need to do several passes. For the example, the desired result would be this:
    Task4 covers Task1, Task2, and Task4
    Task3 covers Task3 and Task5
There are multiple possibilities because Task1 could also cover 3 and 4 but then 2 and 5 would be two additional tasks that are by themselves. Basically, I would want the fewest number of tasks that are within 2 of each other.
I am currently trying to do this in excel VBA but I may port the code to php later. I really just don't know where to start because it seems pretty complex.
Answer: You'l need a clustering algorithm i'd assume. Consider the following parameters-
Task1: parameter1=140
Task2: parameter1=142
Task3: parameter1=144
Task4: parameter1=146
Task5: parameter1=148

Depending on your logic the clustering will get weird here. If you simply check each number for numbers near it all of these will be clustered. But does 140 and 148 deserve to be in the same cluster? Try kmeans clustering. There will be some gray area but the result will be relatively accurate.
http://en.wikipedia.org/wiki/K-means_clustering
Answer: You can group tasks in a single pass if you decide the group boundaries before looking at the tasks. Here's a simple example using buckets of width 4, based on your goal to group tasks within +/-2 of each other:
Dim bucket As Integer

For Each parameter In parameters
    bucket = Round(parameter / 4, 0)

    ' ... do something now that you know what bucket the task is in
Next parameter

If the groups provided by fixed buckets don't fit the data closely enough for your needs, you will need to use an algorithm that makes multiple passes. Since the data in your example is one-dimensional, you can (and should!) use simpler techniques than k-means clustering.
A good next place to look might be Literate Jenks Natural Breaks and How The Idea Of Code is Lost, with a very well commented Jenks Natural Breaks Optimization in JavaScript.
Comment: I didn't think it mattered because I would just use the suggested method twice but it actually is two-dimensional. I was trying to make it a simple question to ask. There is a parameter2 that would have similar constraints. The tasks would be grouped by parameter1 of values within 2 of each other and also by parameter2 with values within 2 of each other. Maybe k-means would be the way to go.
Comment: In this case, the dimensionality matters; you can *sort* one-dimensional data in a way that you can't for two or more dimensions. Try k-means, and consider using an existing implementation like SciPy's [kmeans](http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html#scipy.cluster.vq.kmeans) instead of writing your own. This will let you see much more quickly if it gives the results you expect.

Logic for grouping similar parameters


Collection vs Collection

Question: After trying to understand the concepts at Spring MVC, I came across the expression Collection<? extends Book> which I have never seen before.  I have tried to figure it out on my own, but I am seeing no difference between using Collection<? extends Book> and Collection<Book>.  I was guessing that it only allowed for extensions of Book, but it does allow for Book as well.  So scratch that.  I have tried using Google, but since ? is a wildcard in google, it makes it nearly impossible to search for.  I have searched stackoverflow for the answer, but all questions about this (such as List<? extends MyType> and <? extends > Java syntax) already assume knowledge of Collection<? extends T>.  Here is the code that has initially intrigued my interest:
import java.util.ArrayList;
import java.util.Collection;

public class Book {
    public static void main(String[] args) {
        BookCase bookCase1 = new BookCase();
        BookCase bookCase2 = new BookCase(bookCase1);
    }
}

class BookCase extends ArrayList<Book> {
    public BookCase() {
    }

    //acts same as public BookCase(Collection<Book> c) {
    public BookCase(Collection<? extends Book> c) {
        super(c);
    }
}

What does <? extends T> do?  How does it differ from <T>?
EDIT:
Followup question:  Does BookCase extends ArrayList<Book> mean that BookCase extends Book?
Comment: A `Collection` is a `Collection` but not a `Collection`.
Comment: Times like these I wish I could green checkmark multiple answers.  Specifically Makoto's and Adam's answers.  While all answers were helpful, those in particular helped me understand it.  So if you are looking for an answer to this question, I suggest you read both of those at the very least, including comments.  Thanks everyone!!
Answer: Consider the following
class Animal { }
class Horse extends Animal { }

private static void specific(List<Animal> param) { }
private static void wildcard(List<? extends Animal> param) { }

Without the extends syntax you can only use the exact class in the signature
    specific(new ArrayList<Horse>()); // <== compiler error

With the wildcard extends you can allow any subclasses of Animal
    wildcard(new ArrayList<Horse>());  // <== OK

It's generally better to use the ? extends syntax as it makes your code more reusable and future-proof.
Comment: But a Horse is an animal, and specific() accepts a list of Animals...so why wouldn't a list of horses be accepted?
Comment: @Evorlor because if you specify the type parameter to be some Object, the compiler wants it to be that exact object
Comment: Yes, that is correct. `Collection` just can't stand in for `Collection` regardless of where the type variable appears, so it violates the Liskov Substitution Principle. `Collection` has a method `add(Horse)` whereas `Collection` has `add(Animal)`. Clearly, calling `add(Animal)` with any possible `Animal` must not pass through the static type checker.
Comment: Generics doesn't work in the same way as standard method signatures, yes foo(Animal animal) could take any type of Animal.
Comment: @Evorlor Perhaps [this](http://docs.oracle.com/javase/tutorial/java/generics/inheritance.html) link can be of help?
Comment: @Evorlor If `List` was a subtype of `List`, then you could have a method `addSomeCatsTo(List)`---and call it with `addSomeCatsTo(myDogList)`. The type system is here to stop you from doing that---unless your method promises to only *read* from the list. That's what you effectively say with `List`: you will be able to read `Animal`s from it, but won't be allowed to put any in.
Comment: So... `Collection` can fulfill requirement of `Collection`. `Collection` can fulfill requirement of `Collection`. `Collection` can fulfill requirement of `Collection`. But `Collection` CANNOT fulfill requirement of `Collection`. Am I getting it now?
Comment: this is the best explanation of a really difficult concept I have ever seen, please makes also an example of covariance if you like
Answer: Both Collection<Book> and Collection<? extends Book> represents a collection that can hold Book instances and objects that can be considered to be a Book through the is-a relationship.  This property extends to interfaces as well.
The difference here is that the latter form  is considered to be bounded.  Depending on the bound, you would not be able to add or remove elements from this collection.
? extends T is a upper bounded wildcard.  In effect, it describes a hierarchical bound between some type (?) at the low end, and Book at the high end.  It is inclusive, so you can store instances of Book in there, but if you had other classes and interfaces, such as:
class Novella extends Book {}
class Magazine extends Book {}
class ComicBook extends Book{}
class Manga extends Magazine {}
class Dictionary extends Book {}
class ForeignLanguageDictionary<T extends Language> extends Dictionary {}
interface Language {}

...you could find any of those instances inside of a Collection<? extends Book>.
Recall that I mentioned that you may not be able to add or remove things from this collection?  Remember this convention:

Producer extends; consumer super.

Note that this is from the perspective of the collection; if the collection is bounded with extends, it's a producer; if it's bounded with super, it's a consumer.
That said, from this collection's perspective, it has already produced all of its records, so you cannot add new ones to it.
List<? extends Book> books = new ArrayList<>(); // permanently empty
books.add(new Book()); // illegal

If it were the case that you had it bound with ? super Book, you could not retrieve elements from it in a sane way - you'd have to retrieve them as Object instead, which isn't concise.
List<? super Book> books = new ArrayList<>();
books.add(new Book());
books.add(new Manga());
Book book = books.get(0); // can't guarantee what Book I get back

Chiefly, if you are bound with ? super T, you only ever intend to insert elements into that collection.

Followup question: Does BookCase extends ArrayList<Book> mean that BookCase extends Book?

No.  A BookCase in that instance is an ArrayList, not a Book.  It so happens to be the case that the array list is bound to store books, but it itself is not a Book.
Comment: thank you very much for your help!  I wish I could green check multiple answers, but I cannot.  Know that your answer (as well as Adam's) was vital to my understanding, so thank you!  I also gave you a shoutout in the comments on the question.
Comment: So  represents the lowest child thru T, while  means T and only T - no children.  Is this correct?
Comment: It's using the same is-a relationship with children, so you'd be able to store children inside of `T`.  In my example, you could put an instance of `Manga` inside of a `Collection`.
Comment: Let me make some tweaks here.  There's a bit of confusion in place.
Comment: So... Collection can fulfill requirement of Collection.  Collection can fulfill requirement of Collection.  Collection can fulfill requirement of Collection.  But Collection CANNOT fulfill requirement of Collection.  Am I getting it now?
Comment: I've made some tweaks to the answer.  There was a bit of confusion, mostly on my part.  I do apologize for that, and hopefully you'll find this answer a bit more concise.
Answer: Check out this from the documentation.

In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the case that G is a subtype of G. This is probably the hardest thing you need to learn about generics, because it goes against our deeply held intuitions.

Take a look at the next page about wildcards too.
So basically when you write void doStuff(List<Book>){} you can only do stuff to a list of Book objects ONLY.
Not Novels, not Magazines, not ComicBooks.
Again, this is because although Novel extends Book, G<Novel> does not actually extend G<Book>. It is not very intuitive, but the example in the documentation will help you see it.
Answer: Here's the example that clearly shows the difference between Collection<? extends Book> and Collection<Book>:
public class Test {
    public static void main(String[] args) {
        BookCase bookCase1 = new BookCase();
        BookCase bookCase2 = new BookCase(bookCase1);
        List<FictionBook> fictionBooks = new ArrayList<>();
        BookCase bookCase3 = new BookCase(fictionBooks);
    }
}

class Book {}
class FictionBook extends Book {}

class BookCase extends ArrayList<Book> {
    public BookCase() {
    }

    //does not act same as public BookCase(Collection<Book> c) {
    public BookCase(Collection<? extends Book> c) {
        super(c);
    }
}

that code compiles. If you change the BookCases constructor parameter to Collection<Book>, this example won't compile.
Answer: List<Book> is a list that may contain any book. Because there is no restriction on the kind of book, you can add any book to it.
List<? extends Book> is as well a list that contains books, but there might but further restrictions. Maybe in fact it is a List<PoetryBook> and it may only store instances of PoetryBook, you can only be sure that every item inside this list is a book. Because of this possible restriction you can't add any items to this list.
Consider a method that takes a list of books and returns the book with the most pages.
Book getBookWithMostPages(List<? extends Book>) {
   ...
}

This method can be called with List<Book> or with List<PoetryBook>.
If you change the signature to
Book getBookWithMostPages(Iterable<? extends Book>) {
   ...
}

then it can also be used with Set<ScienceBook> or anything that is iterable and contains books.
Comment: ... but a method that adds some poetry to a list of books: `addSomePoetry(List)` would not work. (just rounding off your explanation.)

Collection vs Collection


Apache Error log with mod_fcgid process exit(lifetime expired)

Question: I have lots of errors in my apache error log as below, anyone has any idea why is this error ?
<code>[Thu Jan 30 17:15:40 2014] [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25614) exit(lifetime expired), get unexpected signal 11
[Thu Jan 30 17:15:40 2014] [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25616) exit(lifetime expired), get unexpected signal 11
[Thu Jan 30 17:15:40 2014] [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25618) exit(lifetime expired), get unexpected signal 11
[Thu Jan 30 17:16:30 2014] [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25668) exit(lifetime expired), get unexpected signal 11
[Thu Jan 30 17:16:39 2014] [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25661) exit(lifetime expired), get unexpected signal 11
[Thu Jan 30 17:17:03 2014] [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25684) exit(lifetime expired), get unexpected signal 11
[Thu Jan 30 17:17:03 2014] [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25688) exit(lifetime expired), get unexpected signal 11
</code>
Answer: I believe your php script takes too much time to finish.
Try adding these to your apache php.conf
ProcessLifeTime 7200
IPCConnectTimeout 30
IPCCommTimeout 60
Comment: do you meant php.ini file ? if so that didnt fix the problem
Comment: i still get [error] mod_fcgid: process /var/www/cgi-bin/cgi_wrapper/cgi_wrapper(25124) exit(lifetime expired), get unexpected signal 11
Comment: Nonono, into your apache's php config. Also with line breaks.