How to turn On/OFF closed captions in HLS Streaming URL in Exoplayer?

Question: I am using Exoplayer Version 2.0.4 to play HLS Streams(.m3u8). My HLS streams contains the closed captions with it. How can i control the closed captions with exoplayer? Is it feasible to hide/show the subtitle when required and change the placement of the subtitle layout if required?
Comment: @RamJay were you able to show/hide subtitles? I also have managed to show the subtitles in Exoplayer but now want to turn them ON/OFF. How do you do this?
Comment: Hi Ram, were you able to display the subtitles successfully? If so can you share your code to add subtitles with version 2 of Exoplayer? Thanks
Comment: In Exoplayer, i was able to customise closed captions by playing with the SimpleExoplayer View class in github project. You can able to hide/show, change title text font, color, placements ...
Answer: I was able to control caption selection in ExoPlayer 2 using a DefaultTrackSelector. The code below was modified based on the ExoPlayer 2 Demo's TrackSelectionHelper class, which should be referenced for more implementation details.
To turn captions off, you need to disable the renderer for the text tracks and clear the selection overrides.
trackSelector.setRendererDisabled(TRACK_TEXT, true);
trackSelector.clearSelectionOverrides();

TRACK_TEXT is a local static variable I created representing the index of the text tracks (2), in relation to video/audio tracks. I believe that SelectionOverrides are just programmatically specified track selections.
To enable the tracks again, you need to enable the renderer for text tracks, and then set up a new SelectionOverride for your desired text track. Before you can do this, you need to get the TrackGroupArray of the currently mapped text tracks from your DefaultTrackSelector.
MappingTrackSelector.MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
TrackGroupArray textGroups = mappedTrackInfo.getTrackGroups(TRACK_TEXT); // list of captions
int groupIndex = 1; // index of desired caption track within the textGroups array

trackSelector.setRendererDisabled(TRACK_TEXT, false);
MappingTrackSelector.SelectionOverride override =
    new MappingTrackSelector.SelectionOverride(fixedFactory, groupIndex, 0);
trackSelector.setSelectionOverride(TRACK_TEXT, textGroups, override);

For more implementation details (e.g., initializing the trackSelector and fixedFactory), check out the ExoPlayer 2 Demo.
You can use a SubtitleView to position the captions within your layout. Your class will need to implement TextRenderer.Output and override the onCues() method.
@Override
public void onCues(List<Cue> cues) {
    if (subtitleView != null) {
        subtitleView.onCues(cues);
    }
}

Comment: Thanks @Taylor but I'm using DASH and I need to link the captions to the video. I'm currently using the same solution in the link you shared, however, this method doesn't allow us to enable and disable captions unless we release and re-initiate the player.
Comment: for me this answer is not working ..i am using exoplayer version 2.7.1
Comment: Where and how do you pass the subtitle Uri/link to this code?
Comment: @SamRamezanli See here for how to create a media source and prepare the player: https://google.github.io/ExoPlayer/guide.html#preparing-the-player
We are using HLS so the text and video tracks are all included in one manifest/url. Further implementation details were based on the [demo](https://github.com/google/ExoPlayer/tree/release-v2/demos/main/src/main/java/com/google/android/exoplayer2/demo)
Comment: I have the same problem which is mentioned by @Sam Ramezanli and  I have a scenario like while switching to next clip close caption of the previous video will show in the current clip. may I know how to control this kind of issue.
Comment: There is no `TrackSelectionHelper` class in the demo app now and the methods used in your code are not present anymore.
Comment: @khateeb Most of the methods referenced are on the DefaultTrackSelector class, so those should still be a part of the library. However, you're right, it does look like the TrackSelectionHelper file was swapped out for a different approach in this commit: https://github.com/google/ExoPlayer/commit/6ac252843ec990ff32acb30429f2173ea44b73c9
Comment: How would you remove or hide a particular closed caption/subtitle from the track groups, say a forced subtitle?
Answer: In my application I initialize the trackselecktor as follow
To turn off close captions from video track
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    trackSelector.setParameters(new DefaultTrackSelector.ParametersBuilder()
            .setRendererDisabled(C.TRACK_TYPE_VIDEO, true)
            .build()
    );

To turn on close captions from video track
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    trackSelector.setParameters(new DefaultTrackSelector.ParametersBuilder()
            .setRendererDisabled(C.TRACK_TYPE_VIDEO, false)
            .build()
    );

Comment: Works like a charm
Comment: you may need to set preferred language.
Answer: After updating the ExoPlayer library to
implementation 'com.google.android.exoplayer:exoplayer:2.9.5'

I found that the MappingTrackSelector.SelectionOverride method does not exist anymore.
I was unable to find a working alternative, as just replacing with DefaultTrackSelector.SelectionOverride didn't work for me, and subtitles were not playing in my case for video.
MediaSource mediaSource =  new HlsMediaSource.Factory(mediaDataSourceFactory).createMediaSource(uri);

Final set of lines which worked for me:
TrackGroupArray trackGroups = trackSelector.getCurrentMappedTrackInfo().getTrackGroups(newSubtitle.renderIndex);

DefaultTrackSelector.ParametersBuilder paramsBuilder = trackSelector.buildUponParameters();

DefaultTrackSelector.SelectionOverride sOverride = new DefaultTrackSelector.SelectionOverride(newSubtitle.groupIndex, newSubtitle.indexWithinGroup);

boolean isDisabled = trackSelector.getParameters().getRendererDisabled(newSubtitle.renderIndex);

paramsBuilder.setRendererDisabled(newSubtitle.renderIndex, isDisabled);

if (sOverride != null) {
    paramsBuilder.setSelectionOverride(newSubtitle.renderIndex, trackGroups, sOverride);
} else {
    paramsBuilder.clearSelectionOverrides(newSubtitle.renderIndex);
}

trackSelector.setParameters(paramsBuilder);

Old code was:
TrackGroupArray trackGroups = trackSelector.getCurrentMappedTrackInfo().getTrackGroups(newSubtitle.renderIndex);

MappingTrackSelector.SelectionOverride sOverride = new MappingTrackSelector.SelectionOverride(
    new FixedTrackSelection.Factory(),
    newSubtitle.groupIndex,
    newSubtitle.indexWithinGroup
);

trackSelector.setSelectionOverride(newSubtitle.renderIndex, trackGroups, sOverride);
trackSelector.setRendererDisabled(newSubtitle.renderIndex, false);

To close subtitles:
DefaultTrackSelector.ParametersBuilder paramsBuilder = trackSelector.buildUponParameters();

paramsBuilder.setRendererDisabled(playingSubtitle.renderIndex, true);

trackSelector.setParameters(paramsBuilder);

Comment: Where are you getting `newSubtitle` from?
Comment: Your Answer is very good but newSubtitle is missleading. Didnt downvote though..
Answer: I highly recommend don't use the constant TRACK_TEXT or C.TRACK_TYPE_TEXT as this:
trackSelector.setRendererDisabled(TRACK_TEXT, true);
trackSelector.clearSelectionOverrides();

because it could vary depends on the asset which you are using, you can ensure that you are disabling the correct renderer with the following code (Kotlin version):
  private fun disableSubtitles(){
    (0 until (trackSelector.currentMappedTrackInfo?.rendererCount ?: 0)).filter {position ->
      player.getRendererType(position) == C.TRACK_TYPE_TEXT
    }.map {position ->
      trackSelector.parameters = trackSelector.buildUponParameters()
          .setRendererDisabled(position,true)
          .clearSelectionOverrides(position)
          .build()
    }
  }

Answer: To disable a track, let's say a Subtitle(Text) track, you need to use DefaultTrackSelector that you've passed earlier to ExoPlayerFactory.newSimpleInstance, to disable a track you need its rendererIndex. There are actually two confusing(at least for me!) terms in selecting the tracks in ExoPlayer, one is TrackType and the other one is RendererIndex. Basically there are some TrackTypes which can be accessed in com.google.android.exoplayer2.C class and the main ones are TRACK_TYPE_AUDIO, TRACK_TYPE_VIDEO and TRACK_TYPE_TEXT. but rendererIndex on the other hand could be any number starting from 0 (I guess). So to disable a track you need to find it's rendererIndex first. then use the code below to disable the track:
trackSelector
            ?.buildUponParameters()
            ?.setRendererDisabled(rendererIndex, true)
            ?.let {
                trackSelector?.setParameters(it)
            }

Answer: Solution for Xamarin.Android:
[Obsolete]
private DefaultTrackSelector CreateTrackSelector()
{
    var bandwidthMeter = new DefaultBandwidthMeter();
    var videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
    var trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    var trackParameter = new DefaultTrackSelector.ParametersBuilder()
         // disables closed caption / subtitle
        .SetDisabledTextTrackSelectionFlags(C.TrackTypeText)
        .Build();
    trackSelector.SetParameters(trackParameter);
    return trackSelector;
}


Prove fact using matrix multiplcation

Question: Prove $F_αR_θF_α = R_{−θ}$.
I'm trying to prove that this fact holds true, where $F_\theta$ is the reflection matrix (assuming $\mathbb{R}^2)$ and $R_\theta$ is the rotation matrix.
$R_\theta =   \begin{bmatrix}
    cos\ \theta & -sin\ \theta \\
     sin\ \theta & cos\ \theta
  \end{bmatrix}
$, $F_\theta =   \begin{bmatrix}
    cos\ \theta & sin\ \theta \\
     sin\ \theta & -cos\ \theta
  \end{bmatrix}
$
Performing routine matrix multiplication, I get for the left hand side,  \begin{bmatrix}
    cos^2(α) cos(\theta) & -sin^2(α) sin(\theta) \\
     sin^2(α) sin(\theta) & cos^2(α) cos(\theta))
  \end{bmatrix}
And the right, \begin{bmatrix}
    cos\ \theta & sin\ \theta \\
     -sin\ \theta & cos\ \theta
  \end{bmatrix}.
Which aren't equal? What mistake am I making?
Comment: Mathematica, and I assume Wolfram|Alpha, too, performs element-by-element multiplication if you simply juxtapose the matrices. If you want matrix multiplication, you have to specify that explicitly.
Comment: Could you give more detail about how you computed the LHS? It looks like your are multiplying the matrices elementwise instead of using matrix multiplication: https://en.wikipedia.org/wiki/Matrix_multiplication
Comment: May have been a mistake but since it's a tedious computation, I simply plugged it into Wolfram and got that as my result.
Answer: The correct calculation of the LHS gives:
$\begin{pmatrix}\ \sin(\alpha)^2\cos(\theta)+\cos(\alpha)^2\cos(\theta)&\ \sin(\alpha)^2\sin(\theta)+\cos(\alpha)^2\sin(\theta)\\
  -\sin(\alpha)^2\sin(\theta)-\cos(\alpha)^2\sin(\theta)&\sin(\alpha)^2\cos(\theta)+\cos(\alpha)^2\cos(\theta)
\end{pmatrix}$
 which after using $\sin(\alpha)^2+\cos(\alpha)^2=1$ gives the desired result.

Prove fact using matrix multiplcation


JavaScript Error in Pentaho - Cannot call method "toUpperCase" of null

Question: // Sets all the letters as uppercase
var str = ae_a_asset_e$manufacture_code.toUpperCase();
var str2 = ae_a_asset_e$serial_no.toUpperCase();
var str3 = ae_a_asset_e$manu_part_number.toUpperCase();
var str4 = ae_a_asset_e$region_code.toUpperCase();
var str5 = ae_a_asset_e$fac_id.toUpperCase();

Any idea how to fix this? I would think there would have to be a way to say if value = null then don't worry about it.
Comment: "I would think there would have to be a way to say if value = null then don't worry about it.", Yes there is, have you tried implementing that?
Comment: How would I go about doing that? Brand new to all this.
Comment: if(null != ae_a_asset_e$manufacture_code)
Comment: var str = (if (ae_a_asset_e$manufacture_code) == null) ? (true block) :  : (else ae_a_asset_e$manufacture_code.toUpperCase()))
Answer: First you have to think whether it is correct that some values are null or not, such as ae_a_asset_e$manufacture_code.
If they can be null you can access them in a safe way like this (extend this code to all other vars as required):
var str = ae_a_asset_e$manufacture_code ? ae_a_asset_e$manufacture_code.toUpperCase() : "";

If they cannot be null then, your should check your data integrity first and then run this script (assuming they are never null).
Comment: I'm doing an excel input and some of the columns don't have data which is fine. Just need the code to look past the null values.
Comment: OK, then the code I posted should be perfectly fine for your scenario.
Comment: var str = ae_a_asset_e$manufacture_code ? ae_a_asset_e$manufacture_code.toUpperCase() : "";
var str2 = ae_a_asset_e$serial_no ? ae_a_asset_e$serial_no.toUpperCase() : "";
var str3 = ae_a_asset_e$manu_part_number ? ae_a_asset_e$manu_part_number.toUpperCase() : "";
var str4 = ae_a_asset_e$region_code ? ae_a_asset_e$region_code.toUpperCase() : "";
var str5 = ae_a_asset_e$fac_id ? ae_a_asset_e$fac_id.toUpperCase() : "";

Look better?
Comment: You are welcome! and please, consider [accepting](http://stackoverflow.com/help/someone-answers) this answer if it solved your problem.
Comment: Sorry, new to stackoverflow as well. Accepted it! thanks again.


Design guidance on Business Layer Paging

Question: WCF/C# N-Tier app.
We have implemented Paging in our business Layer using this snippet as a basic guideline.
I'm just wondering- in an effort to make the paging functionality testable, should I make the pager a public property of our Manager classes or inject it in the constructor?
We already inject a repository for unit testing but I do not feel it's right to go down the route of injecting too much.
Alternatively, is it better to keep the pager private? The page size will be specified in a config file anyway so I guess I could specify the page size in the test app.config.
Comment: I see no issue in injecting to much. The opposite, using an IoC-container for injecting just a repository only, shouldn't feel right.
Answer: I would inject your pager as something like:
<code>  public interface IPager {
     int PageSize {get;}
  }
</code>
Your concrete class would then be something simple like:
<code>  internal class ConfigPager : IPager {
     public int PageSize {
         get{

             int pageSize = 10;  // default value
             Int32.TryParse(ConfigurationManager.AppSettings["PageSize"], out pageSize);
             return pageSize;
         }
     }
  }
</code>
By injecting the IPager you're able to more fully test your manager class to make sure that it actually respects different settings for PageSize since you can easily mock it and test different sizes.  This will call out any cases where someone might try to hard-code a page size value in your manager.


Frequentist definition of probability; does there exist a formal definition?

Question: Is there any formal (mathematical) definition of what frequentists understand under ''probability''.  I read that it is the relative frequency of occurrence ''in the long run'', but is there some formal way to define it ? Are there any known references where I can find that definition ?
EDIT:
With frequentist (see comment by @whuber and my comments to the answer @Kodiologist and @Graeme Walsh below that answer) I mean those that ''believe'' that this long run relative frequency exists. Maybe this (partly) answers the question of @Tim also
Comment: Please explain what you mean by "Frequentist."  The uses I have seen in other threads indicate many people have no consistent or clear sense of what this term might mean.  A definition would therefore help keep any answers relevant.
Comment: I am not sure I will have the energy to write an answer myself, but I would like to leave here the same link to the Stanford Encyclopedia of Philosophy entry on [Interpretations of Probability](http://plato.stanford.edu/entries/probability-interpret/) that I posted under your answer in the related thread. The section on frequentist interpretation/definition is a good read. It talks extensively about various conceptual problems with attempts to give a frequentist definition of probability.
Comment: @whuber I guess the definition of frequentist is "non Bayesian" and of Bayesian is "non frequentist" in most cases :)
Comment: I was going to say that this http://stats.stackexchange.com/a/230943/113090 would probably be of interest to you, but then I realized that you are the person who posted that answer, so never mind. Anyway your thought process there might be of interest to others who also have the same question as you (e.g. me) "does there exist a formal frequentist definition of probability"
Comment: Closely related: https://en.wikipedia.org/wiki/Empirical_probability
Comment: @whuber: my question was just that, what is ''frequentist probability'', how is this probability defined formally ? I read this : https://en.wikipedia.org/wiki/Frequentist_probability, but are there any other references than wiki ? Is this a ''valid'' definition of probability ?
Comment: @whuber after thinking about it, it seems that your question is interesting, to be asked: http://stats.stackexchange.com/questions/232356/who-are-frequentists
Comment: @whuber: ''what is frequentist''; see my comment below Kodiologist's answer (the one that reacts to  Graeme Walsh's comment)
Comment: `'believe' that this long run relative frequency exists` This might open Pandora's box of opinions what is "to exist" and what is "to believe" and how they are related to what is "reality". It might turn in the end that the Q raised by you in its current form is a pseudo-question.
Answer: I don't think there is a mathematical definition, no. The difference between the various interpretations of probability is not a difference in how probability is mathematically defined. Probability could be mathematically defined this way: if $(Ω, Σ, μ)$ is a measure space with $μ(Ω) = 1$, then the probability of any event $S ∈ Σ$ is just $μ(S)$. I hope you agree that this definition is neutral to questions like whether we should interpret probabilities in a frequentist or Bayesian fashion.
Comment: @fcop As Walsh notes, this "definition" is not rigorous.
Comment: that's fine but this definition of probability as $\mu$ that fulfills the axioms of Kolmogorov is very abstract, it needs to be defined in specific cases.  It is the same as 'a circle is the set of points that is at a given distance from a fixed point'.  It does not mean anything as long as you don't say in which metric space you are:  you should say what is the definition of ''distance''.  I think that defining $\mathbb{P}$ as a long run relatve frequency does fulfill the axioms of Kolmogorov, what do you think ? P.S. The defintition in the comment of @Silverfish also fulfill these axioms.
Comment: (continued) so for short, I can define (**define** is the right word), many $\mu$ that fulfill the axioms of Kolmogorov and these are all valid probabilities according to the axiomatic theory.
Comment: Arguably, Kolmogorov's system provides _an_ axiomatic basis - which does not necessarily entail a frequentist or Bayesian interpretation. In the spirit of the frequentist view, the basic idea is that as the number of trials increases to infinity, the empirical frequency stabilizes around, or converges to, some value; the probability of the event. $$
\lim_{n\rightarrow \infty} \left(n_{A}/ n\right) = P_A = P(A).$$ Although the frequency approach improves the classical approach, the lack of rigour leads to the axiomatic foundation. Is this more a question about the history of probability theory?
Comment: @Graeme Walsh: could you put that into an answer, and complete it with arguments why such a definition of $P(A)$ is in line with Kolmogorov's axioms ? (of course one can question the existence of the limit, but then we might say that frequentists are those that ''believe'' in the existence of it?)
Comment: @fcop First, I don't get the point about having to be in line with Kolmogorov - my point was that he provided _an_ axiomatic approach - indeed, the most popular one, but there are other systems. Second, in history, the frequentist view precedes the very existence of Kolmogorov. The lack of rigour in frequentist interpretation ultimately led to the axiomatic approach. It's a matter of the course of history. No? Are you asking for a formulation of the frequentist approach as a special case of an axiomatic theory like Kolmogorov's? Maybe I am missing something.
Comment: @Graeme Walsh: well it is not so hard to show that the definition with the 'limit' that you provided fulfills all the axioms of Kolmogorov. So 'yes' I think it is a special case of the axiomatic theory. That is not unexpected, as Kolmogorov probably wanted to find an axiomatic system that ''contained'' the definitions that preceded Kolmogorov's theory.  I assume he did not want to replace everything but only wanted to find a consistent (axiomatic) basis for all the existing definitions ?
Comment: @fcop I don't see how you're going to get a mathematical formalization of a concept that isn't entirely mathematical, namely, frequentism. But if you disagree, I invite you to try to prove me wrong.
Comment: @Kodiologist: see the definition given by Graeme Walsh in the comments supra. ''frequentism'' is the long run relative frequency of occurence, so if $n$ is the number of experiments and $n_A$ the number of times that the event $A$ occurs then $P(A)=lim_{n\to +\infty} n_A/n$ ?
Comment: @Kodiologist: please explain why it is not rigorous ?
Comment: @fcop It's not rigorous for two reasons (I think). First, how does one create an infinite number of trials? Second, what happens in situations where repeated trials are not possible?
Comment: @Graeme Walsh: How can you then define $lim_{x \to +\infty} f(x)$ ? You can not walk to infinity do you ?
Comment: @fcop " please explain why it is not rigorous ?" — The first thing that comes to mind: suppose $X$ is a standard normal random variable, and try using this definition to compute the probability that a draw from $X$ is irrational. The sequence of outcomes of $X$ could be all rational, all irrational, or a mixture, but the unique correct answer is 1.
Comment: @Kodiologist: well talking about rigorous; I will tell you if you give me a rigorous definition of ''irrational'', without that I can't tell and please, tell me in terms of all the concepts of the probability space that you mentioned.
Comment: @fcop A real number $x$ is irrational if there are no integers $a$ and $b$ with $x = a/b$. Am I missing something? Irrationality requires no probabilistic or measure-theoretic concepts to define.
Comment: @Kodiologist: look at your answer, the probability is only defined for the elements of $\Sigma$, am I missing something when I say that $\Sigma$ does not mention anything about ''rational'' or ''irrational'' or ''integer'' ? What are you talking about, you should only talk about $\Omega$ or $\Sigma$ or $\mu$, all these other ''things'' are undefined so non-rigorous ?
Comment: @fcop Yes, you are missing something: the set of irrational numbers is a measurable set and hence is an element of $Σ$. In particular, in this case, $Σ$ is the Borel σ-algebra on ℝ.
Answer: TL;DR It doesn't seem like it is possible to define a frequentist definition of probability consistent with the Kolmogorov framework which isn't completely circular (i.e. in the sense of circular logic).
Not too long so I did read: I want to address what I see as some potential problems with the candidate frequentist definition of probability $$\underset{n \to \infty}{\lim} \frac{n_A}{n} $$ First, $n_A$ can only be reasonably be interpreted as a random variable, so the above expression is not precisely defined in a rigorous sense. We need to specify the mode of convergence for this random variable, be it almost surely, in probability, in distribution, in mean, or in mean squared.
But all of these notions of convergence require a measure on the probability space to be defined to be meaningful. The intuitive choice, of course, would be to pick convergence almost surely. This has the feature the limit needs to exist pointwise except on an event of measure zero. What constitutes a set of measure zero will coincide for any family of measures which are absolutely continuous with respect to each other -- this allows us to define a notion of almost sure convergence making the above limit rigorous while still being somewhat agnostic about what the underlying measure for the measurable space of events is (i.e. because it could be any measure absolutely continuous with respect to some chosen measure). This would prevent circularity in the definition which would arise from fixing a given measure in advance, since that measure could (and in the Kolmogorov framework usually is) defined to be the "probability".
However, if we are using almost sure convergence, then that means we are confining ourselves to the situation of the strong law of large numbers (henceforth SLLN). Let me state that theorem (as given on p. 133 of Chung) for the sake of reference here:

Let $\{X_n\}$ be a sequence of independent, identically distributed random variables. Then we have $$ \mathbb{E}|X_1| < \infty \implies \frac{S_n}{n} \to \mathbb{E}(X_1)\quad  a.s.$$ $$\mathbb{E}|X_1| = \infty \implies \underset{n \to \infty}{\lim\sup}\frac{|S_n|}{n} = + \infty \quad a.s. $$ where $S_n:= X_1 + X_2 + \dots + X_n$.

So let's say we have a measurable space $(X, \mathscr{F})$ and we want to define the probability of some event $A \in \mathscr{F}$ with respect to some family of mutually absolutely continuous probability measures $\{\mu_i\}_{i \in I}$. Then by either the Kolmogorov Extension Theorem or Ionescu Tulcea Extension Theorem (I think both work), we can construct a family of product spaces $\{(\prod_{j=1}^{\infty} X_j)_i\}_{i \in I}$, one for each $\mu_i$. (Note that the existence of infinite product spaces which is a conclusion of Kolmogorov's theorem requires the measure of each space to be $1$, hence why I am now restricting to probability, instead of arbitrary, measures). Then define $\mathbb{1}_{A_j}$ to be the indicator random variable, i.e. which equals $1$ if $A$ occurs in the $j$th copy and $0$ if it does not, in other words $$n_A = \mathbb{1}_{A_1} + \mathbb{1}_{A_2} + \dots + \mathbb{1}_{A_n}.$$ Then clearly $0 \le \mathbb{E}_i \mathbb{1}_{A_j} \le 1 $ (where $\mathbb{E}_i$ denotes expectation with respect to $\mu_i$), so the strong law of large numbers will in fact apply to $(\prod_{j=1}^{\infty} X_j)_i$ (because by construction the $\mathbb{1}_{A_j}$ are identically and independently distributed - note that being independently distributed means that the measure of the product space is multiplicative with respect to the coordinate measures) so we get that $$\frac{n_A}{n} \to \mathbb{E}_i \mathbb{1}_{A_1} \quad a.s. $$ and thus our definition for the probability of $A$ with respect to $\mu_i$ should naturally be $\mathbb{E}_1 \mathbb{1}_{A}$.
I just realized however that even though the sequence of random variables $\frac{n_A}{n}$ will converge almost surely with respect to $\mu_{i_1}$ if and only if it converges almost surely with respect to $\mu_{i_2}$, (where $i_1, i_2 \in I$) that doesn't necessarily mean that it will converge to the same value; in fact, the SLLN guarantees that it won't unless $\mathbb{E}_{i_1} \mathbb{1}_A = \mathbb{E}_{i_2} \mathbb{1}_A$ which is not true generically.
If $\mu$ is somehow "canonical enough", say like the uniform distribution for a finite set, then maybe this works out nicely, but doesn't really give any new insights. In particular, for the uniform distribution, $\mathbb{E}\mathbb{1}_A = \frac{|A|}{|X|}$, i.e. the probability of $A$ is just the proportion of points or elementary events in $X$ which belong to $A$, which again seems somewhat circular to me. For a continuous random variable I don't see how we could ever agree on a "canonical" choice of $\mu$.
I.e. it seems like it makes sense to define the frequency of an event as the probability of the event, but it does not seem like it makes sense to define the probability of the event to be the frequency (at least without being circular). This is especially problematic, since in real life we don't actually know what the probability is; we have to estimate it.
Also note that this definition of frequency for a subset of a measurable space depends on the chosen measure being a probability space; for instance, there is no product measure for countably many copies of $\mathbb{R}$ endowed with the Lebesgue measure, since $\mu(\mathbb{R})=\infty$. Likewise, the measure of $\prod_{j=1}^n X$ using the canonical product measure is $(\mu(X))^n$, which either blows up to infinity if $\mu(X) >1$ or goes to zero if $\mu(X) <1$, i.e. Kolmogorov's and Tulcea's extension theorems are very special results peculiar to probability measures.
Comment: @fcop I guess honestly I have no idea. I guess what I'm trying to say is that I don't see how any rigorous justification for the frequentist understanding of probability could lead to a useful/non-circular definition.
Comment: Thanks for the nice answer (+1).  I agree that there are ''problems'' with the definition in terms of a long-run relative frequency, that was probably one of the reasons why Kolmogorov developed his Grundbegriffe. However when we speak about frequentists we have to place ourselves in the time frame before Kolmogorov's theory I think ?
Comment: @fcop I really appreciate the generous bounty -- I was in really quite a bad mood today before receiving it. It honestly has me somewhat floored (in a good way). Again, I really appreciate it
Comment: don't mention it, your answer is very well developed and mathematically sound.


Get data attribute for selected dropdown options

Question: I'm trying to post a custom data attribute on a select box option to a hidden form field.
Here's my html:
<select id="sampleorder" multiple="multiple">
 <option value='xxx' data-amount='5'>Name</OPTION>
 <option value='xxx' data-amount='15'>Name</OPTION>
 <option value='xxx' data-amount='2'>Name</OPTION>
</select>

And jQuery
$('#submit_btn').click(function() {
  var options = $('select#sampleorder');
  var samplesSelected = options.val();

  $('input[name=order]').val(samplesSelected);
  $('input[name=quantity]').val(sampleAmount);
});

I'm guessing that my variable "sampleAmount" should look somewhat like this
  var sampleAmount = options.val().data("amount");

But it's not giving me the expected results.
What would be a good approach to get the data attribute value per item?
Thanks!
Answer: why use jQuery? Just use event.target.options[event.target.selectedIndex].dataset.amount
Comment: Thank you! I had to go through 4 different questions before I found an answer that didn't use jquery.
Comment: glad I could help:) haha I don't even remember writing this answer
Comment: Thanks! Found 8 jQuery solutions and only this one with vanilla javascript. In case someone else is looking for a way to get a data attribute of an option when it's selected, you need to set a variable with this, like so: `var yourVariable = event.target.options[event.target.selectedIndex].dataset.your-data-attribute; });`. That would typically reside in a change Event Listener.
Comment: Why using jQuery? Because maybe to support IE <11 and still maybe to avoid mixing plain js method with jQuery one in case like OP where jq is used.
Answer: Try this:
$('#submit_btn').click(function() {
  var samplesSelected = $('#sampleorder').val(),
      sampleAmount = $('#sampleorder option:selected').data("amount");
  $('input[name=order]').val(samplesSelected);
  $('input[name=quantity]').val(sampleAmount);
});

Answer: In pure vanilla javascript you can use :
var sampleAmount = this.selectedOptions[0].getAttribute('data-amount'));
Example:

function SelectChange(event) {
    console.log(event.selectedOptions[0].getAttribute('data-amount'));
}
<select onchange="SelectChange(this)">
    <option data-amount="1">one</option>
    <option data-amount="2">two</option>
    <option data-amount="3">three</option>
</select>
Comment: This one should have gotten much more love than it has. Solution that works as is, with no jQuery!
Answer: Try this,
HTML
Add id attribute to your select drop down
like
<select id="sampleorder" >
   ....

SCRIPT
 var sampleAmount = $('select#sampleorder option:selected').data("amount");

Fiddle http://fiddle.jshell.net/3gCKH/
Answer: Another vanilla JS answer:
var selectContainer = document.getElementById('sampleorder')
var selectedOption  = selectContainer.selectedOptions.item()
var amount          = selectedOption.getAttribute('data-amount')

Comment: It should be `item(0)` I think
Answer: I forgot to mention it has to be a multi select box, sorry.
With your help and a brief look into the jQuery documentation I've managed to solve it:
$("select#sampleorderm").change(function () {
    var samplesSelected = options.val().join("::");
    var samplesAmount = "";
        $("select#sampleorderm option:selected").each(function () {
            samplesAmount += $(this).data("amount") + " ";
        });

    $('input[name=sampleorder]').val(samplesSelected);
    $('input[name=sampleorderquantity]').val(samplesAmount);
 });


Examples of empty affine varieties

Question: The nullstellensatz says that a system $S$ of polynomial equations $f_1=0,f_2=0,…f_n=0$, where $f_i$ are elements of a polynomial ring over a field $K[x_0,x_1,…]$, will have a non-empty affine variety iff every polynomial in the sistem belongs to a proper ideal $I\subset K[x_0,x_1,…]$. The negation of the theorem says that if $S$ has no solution (and thus, $V(I)=\emptyset$), then $I$ is not a proper ideal, or putting it as Wikipedia states: "there exists $p_0,p_1,…,p_n$ such that $p_0f_0+p_1f_1+…+p_nf_n=1$".
So far i understood the theorem, but I can't seem to find a sistem $S$ with $V(I)=\emptyset$. Is there any example of a non-trivial $S$ with empty affine variety that you know of?
Edit: Maybe i can't find any because i presume the elements of $K[x_0,x_1,…]$ can have a constant/independent term (example, $x+y-3$). If it is the case, let me know in the answer.
Comment: There is always the $(0,0,0,\ldots)$  affine point. Do you mean projective variety? If so $x+y=0,x-y=0$ has no solution in $\Bbb{P}^1(K)$ if $char(K)\ne 2$.
Comment: The $(0,0,0…)$ point does not solve all the varieties. Take as an example the one-equation variety $x-1=0$. It does has a solution, but it is not $0$. Maybe the issue is that i formulated it backwards, let me edit…
Comment: Sure but you said homogeneous polynomials
Comment: Oh, if i add a constant term it is not homogeneus anymore?
Comment: Your statement of the Nullstellensatz seems a little off to me. Can you post the full statement and where you got it from?
Comment: Well, I would consider a constant polynomial to be homogeneous of degree 0, and if the constant is nonzero then it can have no roots already just by itself.
Comment: There! I edited already. Hopefully this makes more sense.
Comment: 1. Please use markdown (not MathJax) to format italics - i.e. `*italics*` produces *italics*. 2. Where has this idea that the polynomials need to be homogeneous come from? It sounds to me like you are confusing two different statements/versions of the nullstellensatz.
Comment: Oh, sorry! You're rigth. Homogeneous is indeed not a condition. I had it wrong. Should i delete?
Comment: Well, actually my question is still not answered, let me edit one last time…
Answer: The most direct example is $V(1)$. All other examples are essentially this example, but dressed up in a more interesting way - $V(f_1,\cdots,f_n)=\emptyset$ implies $(f_1,\cdots,f_n)=(1)$, as the Wikipedia page you quote says.
Here's a bunch of other examples:

$V(x,x-1)$
$V(x,y,x+y+1)$
$V(x,y,z,xyz-1)$
$V(x^2+y^2+1,x^2+y^2+4)$
and so on...

Examples of empty affine varieties


How can I use AZ CLI to find Azure resources which are missing a specific tag?

Question: I need to assure that all our resource groups have a specific tag.
I know I can use a policy to ensure that any created resource will have the tag, but for existing resources I'm trying to come up with a query using AZ CLI.
As an extra challenge, the tag has a space in the middle of its name: it is "Cost Center" instead of "CostCenter". :-/
Answer: I would recommend using Azure Resource Graph for this. Resource graph allows you to query all your Azure resources using the Kusto language either in the CLI or in the portal.
To look for the name of all resource groups that do not have the "Cost Center" tag you could run a query like:
ResourceContainers
| project name, type, tags
| where type == 'microsoft.resources/subscriptions/resourcegroups'
| where tags !contains 'Cost Center'
| project name

From the CLI this query would look like:
az graph query -q "ResourceContainers | project name, type, tags | where type == 'microsoft.resources/subscriptions/resourcegroups' | where tags !contains 'Cost Center' | project name"

Comment: Great! I didn't know about the Resource Graph.
Comment: This extension needs to be installed via `az extension add --name resource-graph`, otherwise you'll get the following error: `az: 'graph' is not in the 'az' command group`.


Group structure on set of homotopy classes

Question: Let $\text{Top}_*$ be the category of pointed topological spaces, and fix some $(X,x)\in\text{Top}_*$. Suppose that for all $Y\in\text{Top}_*$ we can give a group structure to the set $[X,Y]$ of homotopy classes of maps fixing the base point, in such a way that there exists a functor
$$
\mathcal F:\text{Top}_*\to\text{Gr},\;
(Y,y)\mapsto[(X,x),(Y,y)]
$$
where $\text{Gr}$ is the category of groups.

Is it true that the identity of $[(X,x),(Y,y)]$ is the class of the constant map?

If the functor $\mathcal F$ happens to be the most natural one, i.e., the one given by composition: for a continuous map $f:Y\to Z$,
$$\mathcal F(f):[X,Y]\to[X,Z],\quad[h]\mapsto[f\circ h],$$
then this is easily seen to be true. This is, for example, what happens for the fundamental group. However, what if $\mathcal F$ is an arbitrary functor (assuming, of course, that a functor not of this form exists, which for all I know it might not at all)? Is it possible that the identity of group is not the constant map?
Comment: $\textbf{Top}_*$ and $\textbf{Grp}$ both have zero objects, and your functor is guaranteed to preserve zero objects. Thus the functor also preserves zero morphisms. That tells you what the identity element of your groups must be.
Comment: FWIW I don't think it need be true.
Answer: Apologies, I have not fully read the question. This answer presumes that the functor lifts the normal Hom functor on both objects and morphisms.
Clearly the identity element of $[X,*]$ is constant. The image of the identity of a group under a group homomorphism is the identity of the codomain. Since, $*$ is initial and the composition of any constant map with another map is constant, we conclude that all identities are represented by constant.
Comment: I see I posted at the same time as Zhen.
Comment: Thank you for your answer, but I still don't see how this proves it. Certainly $[X,*]$ is the trivial group and the identity is the class of the constant map, and I also see that $i:\{*\}\to Y$ induces a map $\mathcal F(i):[X,*]\to[X,Y]$ which maps the identity to the identity. Hence $\mathcal F(i)([\text{constant map}])$ is the identity of $[X,Y]$, but why is $\mathcal F(i)([\text{constant map}])$ the class of a constant map?
Comment: @user3141592 Under $F(i)$ the identity of the group $[X,*]$ goes to the identity of the group $[X,Y]$. The identity in $[X,*]$ is the constant map. $F(i)$ on maps is post composition with $i$. This post composition on the constant map $X \rightarrow *$ yields the constant map $X \rightarrow Y$. Hence, the constant map $X \rightarrow Y$ is the identity.
Comment: Why does $\mathcal F(i)$ act like "post composition" though? Maybe I didn't explain myself clearly enough, but in the question $\mathcal F$ is *any* functor, I am not assuming anything about how it acts on functions
Comment: @user3141592 Oh I'm sorry, it looks like I skipped reading that part of your question. My brain is getting a bit confused while thinking about this, so if I think of an answer I will let you know. I suspect the answer is no, and I think my and Zhen's responses rely on using the normal action on maps. To me the first question to answer is if its possible to even supply a functor which acts on objects like Hom but doesn't act like that on maps.
Comment: Probably I should've highlighted that part to avoid misunderstandings, sorry :) Thanks a lot for your time!


Can number of states of minimum accepting automaton be equal to a constan from the pumping lemma?

Question: Let $L$ be a regular language. Prove that the number of states of the minimum accepting automata $L$ can be equal to a constant from the pumping lemma, but any smaller number can't.
From what I understand if we have a word $w=xyz$ we can create an automata with $3$ states $S_1 \to S_2 \to S_3$
where $S_1 \to S_2$ when $x$, $S_2 \to S_2$ when $y$ and $S_2 \to S_3$ when $z$. So the constant would be equal to $3$ and we can't go down to $2$. But I don't know how to prove that for every regular language.
Answer: Let me first remind you the pumping lemma for regular languages.
Let $L$ be a regular language. Then there exists an integer $p > 0$ (called the pumping length) such that every word $w \in L$ of length at least $p$ can be written as $w = xyz$, in such a way that $|xy| \leqslant p$, $|y| \geqslant 1$
and $xy^*z \subseteq L$.
If $n$ is the number of states of the minimal automaton of $L$, then one can choose $n$ for the pumping length. However, it may happen that the mimimal possible pumping length is strictly smaller than $n$. For instance, for $L = a^* \cup b^*$, one can take $p = 1$ as the pumping length, but the minimal automaton of $L$ has three states.


algorítimo não fazendo as verificações necessárias

Question: olá, tenho que fazer um algorítimo no visualg onde tem que ler do teclado um valor inteiro positivo e mostrar na tela todos os números primos menores que o número lido do teclado, porém, está sendo mostrado apenas o valor digitado caso ele seja primo, em baixo segue o que fiz:
Algoritmo "semnome"
Var
cont , x, v1, aux: inteiro

Inicio
escreval ("digite um valor")
leia (v1)
aux<-v1
repita
      para x de 1 ate aux faca
           se (v1%x=0) entao
              cont<-cont+1
           fimse
      fimpara
      se (cont=2) entao
         escreval (v1)
      fimse
      v1<-v1-1
ate (v1<0)

Fimalgoritmo

Answer: Você não definiu nenhum valor para x então ele tem por padrão o valor 0, olhe na condição "se v1 mod x é igual a 0", está acontecendo uma divisão por zero. Para verificar se é primo, o número deve ser dividido por 1 ou ele mesmo.
Answer: Como qualquer número sempre é divisível por 1 e por ele mesmo, para o número ser primo basta não ter nenhum outro divisor.
Algoritmo "semnome"
Var
    cont, cont2 , x, v1, aux: inteiro
Inicio
    escreval ("digite um valor")
    leia (v1)
    aux<-v1
    repita
        cont2 <- 0
        para x de 2 ate aux-1 faca
            se (v1%x=0) entao
                cont2 <-cont2 + 1
            fimse
        fimpara
        se (cont2=0) entao
            escreval (v1)
        fimse
        v1 <- v1 - 1
    ate (v1<=0)
Fimalgoritmo

Para otimizar um pouco mais você pode fazer:
        para x de 2 ate aux\2 faca


How to prevent apache2 from accepting urls without a file extension?

Question: I noticed apache2 will load a page, let's say info.php, even if the url is specified without a file extension like mysite.com/info
I thought you would need to do a mod_rewrite of some form to get that functionality but apparently it's the default functionality in my system.
Is there any way to prevent this default behavior so only pages with file extensions can be specified?
I have rewrite disabled fyi.
Answer: The magic you're seeing is performed by the MultiViews option of mod_negotiation.
From the Apache docs:

If the server receives a request for /some/dir/foo and /some/dir/foo does not exist, then the server reads the directory looking for all files named foo.*, and effectively fakes up a type map which names all those files, assigning them the same media types and content-encodings it would have if the client had asked for one of them by name. It then chooses the best match to the client's requirements, and returns that document.

Disable this magic by turning off MultiViews either in the apache config or in a .htaccess file:
Options -MultiViews

Comment: +1; `MultiViews` seems more likely than `DirectoryIndex` in this case.
Answer: What you are running into is a piece of one of the core modules of apache: mod_dir.
The directive you want to look for is DirectoryIndex this tells apache to look for certain file names when there is no absolute filename specified. The default is generally a line that looks like:
DirectoryIndex index.html index.php default.html default.php default.pl

If you don't want to have it search for these files, and display them by default you need to find the DirectoryIndex line in you apache config file and either comment it out or get rid of everything after the DirectoryIndex statement.
Comment: I'm pretty sure this is wrong. mod_dir only handles the typical files, like index.* and default.*.  Note that he described "info.*" which would be really bizarre to find as a value for DirectoryIndex.


Random Number From given numbers in C#

Question: Random Number From given numbers in C#
I want to choose a random number from array contains set of numbers?
Random r = new Random();
int [] arr={1,5,12,25,14};
int randomNoCorss;
randomNoCorss=r.Next(arr[i]);

Comment: So where did i creep in from?
Answer: Like this:
randomNoCorss = arr[r.Next(arr.Length)];

Comment: @AhmedSooft, that's what this answer does.
Comment: i want the same number in the arr but choose only one random number
Answer: My idea would be to say: OK I have 5 numbers.
Lets generate a random number between 0 and 1
arr[0] is <0.2
arr[1] is between 0.2 and 0.4
arr[2] is is between 0.4 and 0.6 and so on...
Enjoy your day.
Comment: i want the same number in the arr but choose only one random number

Random Number From given numbers in C#


How can i delete starting white spaces using perl regular expression?

Question: What's the way to indicate white spacess in perl ?
How can i delete starting spaces using perl regular expressions?
Answer: my $foo = " \t\n\r  hello, world!";
$foo =~ s/^\s+//;    # This is the line that removes the leading whitespace.
print "$foo\n";
print ord($foo) . "\n";

Will display:
hello, world!
104

104 is the ASCII character code for h, proving that the string has no leading whitespace.
Answer: This searches for repeated whitespaces (\s+) at the beginning of the string (^), substituting with nothing (i.e. what is between the delimiters here: //):
$myString =~ s/^\s+//;

Answer: $temp = "   Hello world";
#print $temp;
$temp =~ s/^\s+//;
print $temp;


Como adicionar um novo style em um elemento html?

Question: Olá, gostaria da ajuda de vocês em um problema que não encontrei a solução.
Eu tenho esse código: (exemplo)

.cifra.mono, .cifra.mono pre {
    font: 12pt 'Roboto Mono', monospace;
}
.c_config span {
    display: block;
}
.c_config a {
    color: #F60;
}
a {
    text-decoration: none;
    outline: none;
}
.cifra b {
    color: #F60;
    font-weight: bold;
    font-family: 'Roboto Mono', 'Courier New', 'Courier', monospace;
}
strong, b {
    font-weight: bold;
}

    Tom: G

     G          D
Parabéns pra você
               G
Nesta data querida
              C
Muitas felicidades
       D        G
Muitos anos de vida
    G
Muitos anos de vida

E eu gostaria de saber como eu poderia adicionar esse style ao clicar em um botão:
b {
  display: none;
  }

Resumindo tudo, gostaria de saber como ocultar os elementos que estão dentro de  ao clicar em um botão.
Answer:

$(document).ready(function() {
  $("span:first").on("click", function() {
    $("b").css("display","none");
  })
})
.cifra.mono, .cifra.mono pre {
    font: 12pt 'Roboto Mono', monospace;
}
.c_config span {
    display: block;
}
.c_config a {
    color: #F60;
}
a {
    text-decoration: none;
    outline: none;
}
.cifra b {
    color: #F60;
    font-weight: bold;
    font-family: 'Roboto Mono', 'Courier New', 'Courier', monospace;
}
strong, b {
    font-weight: bold;
}

    Tom: G

     G          D
Parabéns pra você
               G
Nesta data querida
              C
Muitas felicidades
       D        G
Muitos anos de vida
    G
Muitos anos de vida

Answer: Amigo adiciona um atributo id na sua tag e dê um nome a ele:

Após isso você poderá mudar o estilo do seu botão com jquery:
$('#teste').on('click', () => {
  $(#teste).css('display', 'none');
});

Espero ter ajudado.
Comment: Recomendo utilizar $(this) para referenciar o próprio objeto.
Comment: Verdade, mas já tive alguns problemas com scopo de função aí prefiro referenciar assim mesmo.
Answer: Você pode usar JavaScript para isso. É só criar um botão que ao ser clicado irá chamar uma função que seleciona todos os  dentro da div e adiciona o display: none:

function ocultaB(){
    var bs = document.querySelectorAll("div[itemprop='description'] b");
    for(var x=0; x<bs.length; x++) bs[x].style.display = "none";
}
.cifra.mono, .cifra.mono pre {
    font: 12pt 'Roboto Mono', monospace;
}
.c_config span {
    display: block;
}
.c_config a {
    color: #F60;
}
a {
    text-decoration: none;
    outline: none;
}
.cifra b {
    color: #F60;
    font-weight: bold;
    font-family: 'Roboto Mono', 'Courier New', 'Courier', monospace;
}
strong, b {
    font-weight: bold;
}
<button onclick="ocultaB()">Clique para Esconder</button>

    Tom: G

     G          D
Parabéns pra você
               G
Nesta data querida
              C
Muitas felicidades
       D        G
Muitos anos de vida
    G
Muitos anos de vida

Answer: Pra ter um efeito de ativar e desativar

$(document).ready(function() {
  var toggle = true;
  $("span:first").on("click", function() {
    if(toggle == true){
       $("b").css("display","none");
       toggle = false;
    }else{
       $("b").css("display","inline");
       toggle = true;
    }
  })
})
.cifra.mono, .cifra.mono pre {
    font: 12pt 'Roboto Mono', monospace;
}
.c_config span {
    display: block;
}
.c_config a {
    color: #F60;
}
a {
    text-decoration: none;
    outline: none;
}
.cifra b {
    color: #F60;
    font-weight: bold;
    font-family: 'Roboto Mono', 'Courier New', 'Courier', monospace;
}
strong, b {
    font-weight: bold;
}

    Tom: G

     G          D
Parabéns pra você
               G
Nesta data querida
              C
Muitas felicidades
       D        G
Muitos anos de vida
    G
Muitos anos de vida


Map Laplacian in terms of covariant derivatives

Question: I stumbled upon the following definition:

Let

$\mathcal{M}$ be a manifold,
$g_{ij}$, $h_{ij}$ be two Riemannian metrics on $\mathcal{M}$,
$\psi : \mathcal{M} \to \mathcal{M}$ be a twice differentiable map,
$C_1$, $C_2$ be two charts on $\mathcal{M}$,
$\Psi := C_2 \circ \psi \circ C_1^{-1}$.

The map Laplacian $\Delta_{g,h}$ is defined by $$ (C_2 \circ
 (\Delta_{g,h} \psi) \circ C_1^{-1})^q := g^{ij}\left( \partial_i
 \partial_j \Psi^q
 -  \Gamma(g)^k_{ij} \, \partial_k \Psi^q
 + (\Gamma(h)^q_{mn} \circ \Psi) \, \partial_i \Psi^m \, \partial_j \Psi^n \right) . $$

Basically, my question is how to make sense of the above beast, but since this is probably too broad, I would like to narrow it down to: can the above formula be expressed in terms of covariant derivatives?

What I got so far:
I recognise the term $\partial_i  \partial_j \Psi^q -  \Gamma(g)^k_{ij}\, \partial_k \Psi^q = \nabla_i \nabla_j \Psi^q$ as the second covariant derivative of $\Psi^q$ such that $g^{ij} \nabla_i \nabla_j \Psi^q = \nabla^i \nabla_j \Psi^q$ can be interpreted as the Laplacian of $\Psi^q$. Since $\Psi^q$ depends on the chart $C_2$, I also expect there to be some term to correct for that, which is probably the last one, but I cannot make that last statement any more precise.

Update: Another question would be whether it is possible to give a physical intuition for this operator. For example, if $\mathcal{M} = \mathbb{R}^3$, the map Laplacian becomes the vector Laplacian appearing in the Navier-Stokes equation where it describes the friction in the fluid (diffusion of momentum). This intuition does not generalise to the situation at hand, however, because $\psi$ is a map from the manifold onto itself, not from the tangent space (which is $T\mathcal{M} = \mathbb{R}^3 = \mathcal{M}$ for $\mathcal{M} = \mathbb{R}^3$) onto itself.
Answer: The map Laplacian has a very simple coordinate free expression - it is (as you'd expect for something called the Laplacian) the trace of the second derivative:
$$ \Delta_{g,h} \psi = {\rm tr}_g \nabla D \psi.$$
The complexity here is hidden in that $\nabla$: we need a covariant derivative that can act on $D \psi$. We can interpret $D \psi$ as a section of the bundle $T^* M \otimes \psi^* TM$, which can be naturally equipped with the tensor product connection formed from $\nabla^g$ and $\psi^* \nabla^h$. The Christoffel symbols of this connection have components coming from both factors ($\Gamma(g)$ directly and $\Gamma(h)$ via $D\psi$), and thus you get the two correction terms in the coordinate formula.
Comment: Thanks for your help! I do not accept your answer (yet) because I do not really understand it. I'm a newbie to differential geometry and don't know what a connection is, nor am I entirely sure what you mean by $D\psi$. An explanation in simpler terms would be much appreciated!
Comment: @gTcV: all I can say in simpler terms is that your original interpretation is essentially correct: the first two terms together make up the Laplacian of the component function $\psi^q$ and the last term corrects for the dependence on $C_2$ in the same way the second term does for $C_1$. The extra $\partial \psi$ factor is there because one has to pass the direction $i$ of differentiation across the map $\psi$.


Comparision trigger in Zabbix

Question: I got two items created for showing certain values. One of them is shoving value from today and the other one from week ago. How can I create trigger that compares them and alert when one of them is lower than the other one by 15% or higher by 10%? I'm running on Zabbix 5.2
Comment: you could even do this using one item and using the time shift. In the trigger you can compare the item as it was a week ago with how the last value is. See https://www.zabbix.com/documentation/current/manual/config/triggers/expression
Answer:
to compare 2 items you can use an expression:
<code>{Template Module Linux CPU by Zabbix agent active:system.cpu.load[all,avg1].last()}>{Template Module Linux CPU by Zabbix agent active:system.cpu.load[all,avg15].last()}
</code>
for example

Comparision trigger in Zabbix


How can I fix this TextPad external tool command?

Question: When I'm editing a file named:
<code>S:\!DJ DAP\PlaylistFormatName.vbs
</code>
and execute this tool:

I expect launch of the file
"S:!DJ DAP\PlaylistFormatName-Test.bat"
but get this fail:
<code>'S:\!DJ' is not recognized as an internal or external command,
</code>
operable program or batch file.
How can I fix this?
I'm using TextPad 7.5.1.on Windows 7 Pro 64-bit.
PS Removing the brackets gives the same fail:

EDIT: This workaround may suit. It succeeds in the test case, but I am not certain the result is always equivalent.
Answer: Take out the () from the parameters.  When I used "$FileDir\($BaseName)-Test.bat", I could recreate the error.  When I used "$FileDir\$BaseName-Test.bat" it worked as expected.
Or try this:
Command: c:\windows\System32\cmd.exe
Parameters: /c "$FileDir\$BaseName-Test.Bat"
Initial Folder: $FileDir
I swear by an even bigger stack of K&R manuals that it worked.
Comment: I got the same behavior with the ( on either side of the $.
Comment: Thanks, but here that gives the same fail (added to Q). The magic ingredient at yours must be something else. Or perhaps your $FileDir does not contain a space? Could you show a screenshot?
Comment: I swear on a stack of K&R text books, I tried it both ways more than once and it behaved the way I answered it.  Today I couldn't recreate it.
Comment: LOL! Yes, I'm not too surprised to find is it variable. Thanks for trying!


looping twice on the same list at the same time as deleting elements from this list leads to elements that are not processed

Question: I'm looking for a way to loop twice on the same list at the same time as removing some items from this list. I noticed with the code below that looping twice on the same list at the same time as removing elements from this list leads to elements that are not processed.
a=[1,3,1,9]

for i in a:
    print(i ,"element from the frist loop for")
    for j in a:
        if i==j:
            p=a.index(i)
            del a[p]
            print(a ,"list after removing element in the second loop for")

Result:
1 element from the frist loop for
[3, 1, 9] list after removing element in the second loop for
[3, 9] list after removing element in the second loop for
9 element from the frist loop for
[3] list after removing element in the second loop for

The number 3 is not processed because it is  not iterated from the first loop
In the first loop we went from 1 to 9 and jumped 3. I want to process also 3 in the first loop.
I understood that the way to loop the list with for loop is frozen by default before running the loop for. In the example the list a must be traversed of the index 0 to 3 since there are 4 numbers in the list so the value 3 has index 1. Knowing that in the first iteration we removed the 1 of the list a, the value 3 no longer has index 1 but 0. But as the index 0 has already been scanned so the value 3 is skipped.
Here true code:
a=[object1,object3,object1,object9]

for i in a:
    print(i ,"element from the frist loop for")
    for j in a:
        if distance(i,j) == 0:
            p=a.index(i)
            del a[p]
            print(a ,"list after removing element in the second loop for")

I try to delete two elements if they are close ( euclidean distance) otherwise I keep them in the list. All these elements are in the same list, hence the double looping on the same list
Comment: The immutables, Deep Copy to the rescue.
Comment: Changing the length of an iterable whilst iterating over it can result in significant issues. I suggest you avoid it if you possibly can. Likely the most straightforward approach is to duplicate your original list to use as a reference, and delete from the one you're not iterating over.
Comment: Post a desired output as well.
Comment: if you want to get a new list without duplicates ( as per i get from your code) , you can use set operation. `a= list(set(a))`
Comment: In the original code I try to delete two elements if they are close otherwise I keep them in the list. All these elements are in the same list, hence the double looping on the same list.
Comment: @pedrocolombino What do you mean by *close*? What should be desired output?
Comment: Iterating backward the old-fashioned way using the index and while loop won't skip items. Still it's not recommended.
Answer: The simplest way to remove duplicates from a list is with the builtin set() function. In your case:
list(set(a))

If you want to use a loop, though, you can just create a new list instead of trying to modify the one you're iterating over. There are a variety of (much) more efficient ways to do this, but here's a simple example of what I mean:
a=[1,3,1,9]
b = []

for i in a:
    if i in b:
        continue
    else:
        b.append(i)

For a more efficient method that avoids scanning the entire list for each item, you can use this recipe from itertools documentation:
from itertools import filterfalse

def unique_everseen(iterable, key=None):
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in filterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

Comment: Well then why didn't you say that in your question? You shared code which was trying to remove duplicates from a list and said nothing about what you were actually trying to do ... so what would you expect?
Comment: I'm not looking for to delete duplicates in the list. I want to delete elements (vectors) that are near, for example in using a euclidean distance.
Comment: I modified my post ^^
Answer: First, you should avoid to modifiy an iterable while you're interating on it. That could be very tricky.
I think the item 3 is not processed because when you use the a.index() method, the current index of a is moved to the position of the second 1, skipping the 3.
You could avoid this kind of issue by creating a new list
a=[1,3,1,9]
a2 = list(a) # Or use `deepcopy` if your list contains other mutables like dict or lists

for p, i in enumerate(a):
    print(i ,"element from the frist loop for")
    for j in a:
        if i==j:
            del a2[p]
            print(a ,"list after removing element in the second loop for")

Update
Eventually, you could simplify this problem by using lists comprehension, for example:
a2 = [i for p, i in enumerate(a) if i > 0]

Comment: `TypeError: '>' not supported between instances of 'list' and 'int'` for the update.
Comment: Sorry, I meant `i`, not a. I'll correct it.
Comment: But the `i > 0` is just here for the example, you should replace it with any condition you would need.


How to eagerly fetch all child collections?

Question: I need a way to eagerly retrieve all child collections of all entities of a certain type using NHibernate.
I tried:
var myObjectList = SessionHolder.Current
    .CreateCriteria(typeof(MyObject))
    .SetFetchMode("Clients", FetchMode.Eager)
    .SetFetchMode("Locations", FetchMode.Eager)
    .SetFetchMode("Contracts", FetchMode.Eager)
    .List<MyObject>();

Query should had returned all MyObject instances from the DB with their collections eagerly loaded but it did not work as intended, instead it returned more objects than expected. I assume it has something to do with n+1 selects problem.
I found this solution to retrieving the collections but I am currently restricted to using NHibernate 220.127.116.1100 so I can't use Futures.
I did a lot of research before posting but couldn't find anything.
Thanks for your replies!
Answer: Try using distinct result transformer:
var myObjectList =
    SessionHolder.Current
                 .CreateCriteria(typeof(MyObject))
                 .SetFetchMode("Clients", FetchMode.Eager)
                 .SetFetchMode("Locations", FetchMode.Eager)
                 .SetFetchMode("Contracts", FetchMode.Eager)
                 .SetResultTransformer(new DistinctRootEntityResultTransformer())
                 .List<MyObject>();

Comment: I tested it, now it returns the right number of MyObject entities but the children are returned replicated, for example, for one instance of MyObject I might have in the returned list of Clients: Client1, Client1, Client1, Client2, Client2, Client2. Any ideea why that happens?
Comment: Could you please try it using HQL? Something like `SessionHolder.Current.CreateQuery("from MyObject o left join fetch o.Clients left join fetch o.Locations left join fetch o.Contracts").SetResultTransformer(new DistinctRootEntityResultTransformer()).List()`
Comment: gives the error message: `Cannot fetch multiple collections in a single query if one of them is a bag `
Comment: @RăzvanPanda: Sorry, I can't help you any further. It looks like the differences between the current and your extremely old version are too big.


What is the format for combining several Parameters in RewriteCond?

Question: I want to use the current [OR] but also add: [L,R=301,NC] for a permanent redirect.
So is that [OR, L,R=301,NC]?
Comment: Just to clarify, what you asking about are _flags_, not _parameters_. The whole _flags_ argument is _one parameter_ to the `RewriteCond` directive (regardless of how many _flags_ you are including).
Answer: The docs for RewriteCond say that the flags are a comma-separated list.
But only OR and NC are flags for RewriteCond. R and L are flags for RewriteRule, so you wouldn't put them together with OR and NC.
Comment: "a comma-separated list" - and _no spaces_ (unlike the OPs example).


Do you know how to generate the dist folder from a combined Angular and .Net Core Application using YAML CI/CD with Azure?

Question: I am trying to get my Angular/.Net Core application to produce the dist folder and show the index.html file and have tried both the classic pipeline and YAML.
But when I run the CI/CD pipeline using the YAML below it runs and gives the green light but doesn't actually deploy the application dist folder as expected.
It ends up showing the following error in the browser:
InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
The YAML is below:
trigger:
- master

pool:
  vmImage: windows-latest

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '14.x'
  displayName: 'Install Node.js'

- script: |
    npm install -g @angular/cli
    npm install
    ng build --prod #--optimization=false
  displayName: 'npm install and build'

# Copy files from a source folder to a target folder using patterns matching file paths (not folder paths)
- task: CopyFiles@2
  inputs:
    sourceFolder: $(Build.SourcesDirectory)
    contents: '**/dist' # Pull the dist directory (Angular)
    targetFolder: $(Build.ArtifactStagingDirectory)

#used to look up directory of published files
- task: Bash@3
  inputs:
    targetType: inline
    workingDirectory: $(Build.SourcesDirectory)
    script: ls -R

#install .net sdk
- task: UseDotNet@2
  displayName: Install .NET 5 SDK
  inputs:
    version: '3.1.x'
    packageType: 'sdk'

#restore nuget packages from build
- task: DotNetCoreCLI@2
  inputs:
    command: 'restore'
    projects: '**/*.csproj'
    feedsToUse: 'select'
    vstsFeed: '9e1f...'

#perform build action
- task: DotNetCoreCLI@2
  displayName: Build .Net
  inputs:
    command: 'build'
    projects: '**/*.csproj'
    arguments: '--configuration $(BuildConfiguration)'

#perform publish
- task: DotNetCoreCLI@2
  displayName: Publish
  inputs:
    command: publish
    publishWebProjects: True
    arguments: '--configuration $(BuildConfiguration) --output $(build.artifactstagingdirectory)'
    zipAfterPublish: True

#perform publish of artifact
- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
  condition: succeededOrFailed()

The release looks good and gives a green light as well but then I get the above error.
I have tried changing the PathToPublish to add /dist afterward it and also tried adding CopyFiles tasks to try to get the dist folder to copy from the source to the target to no avail.
The release pipeline has this as the package to publish in the Deploy to Azure App Service portion of the release pipeline:
$(System.DefaultWorkingDirectory)/drop/drop/...Web.NgClient.zip
Any help is appreciated in understanding why it isn't creating the dist folder and why it isn't serving up the index.html per the error above.
Comment: Please check Zach Sexton's suggestions, and if you need any help, please feel free to let us know.
Answer: The problem is probably in this task:

    # Copy files from a source folder to a target folder using patterns matching file paths (not folder paths)
    - task: CopyFiles@2
      inputs:
        sourceFolder: $(Build.SourcesDirectory)
        contents: '**/dist' # Pull the dist directory (Angular)
        targetFolder: $(Build.ArtifactStagingDirectory)

The copy files task copies the contents inside of the folder specified, not the folder and its contents. Read the Contents argument here.
You need to specify something like targetFolder: $(Build.ArtifactStagingDirectory)/dist to have it show up in a folder named dist.
It's probably generating all of your files, but at the root of whatever $(Build.ArtifactStagingDirectory) is.
Comment: I tried updating the CopyFiles task to add the 'ClientApp' as well as 'ClientApp/dist' but then that step says 0 files were copied.
Comment: Start simple and try to get ahold of the output of your build after the npm build step so you can see what the structure is and go from there, you probably are missing a path somewhere simple but have no visibility.

Also to be clear, you changed the target directory right? I think your source was probably correct.


Problemas com background

Question: Estou com problemas para preencher o meu background com uma cor em específica, no caso, azul.
Segue o código da minha aplicação:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>

</h:head>
<h:body>
    <h:form id="form">

Bem vindo ao sistema CALC-ME,

Resumo:

                <h:panelGrid id="pLogin" cellspacing="10" styleClass="Bimage" columns="3"
                    style="position: absolute;top:140px; left: 450px;">

                </h:panelGrid>

                <h:panelGrid id="pLogin2" cellspacing="10"
                    bgcolor="blue" columns="3"
                    style="position: absolute;top:140px; left: 250px;">

Rendas:

Despesas:

Total Liquido:

Poupança VAR 1:

Poupança VAR 2:

                </h:panelGrid>

    </h:form>
</h:body>

Porém, ele só preenche as bordas do layout, eu precisava preencher todo o conteúdo. Como posso resolver isso? Obrigado.
Segue a imagem de como está preenchendo atualmente (preciso que a parte em branco fique toda azul):
Comment: você já tentou setar o `opacity` para essas `layoutUnit`?
Answer: Ao invés de usar simplesmente "style" coloque o código css entre as tags   <h:outputStyles></h:outputStylesheet> que são as saídas para o jsf reconhecer a folha de estilo.
Substitua isso:
<h:head>

por isso:
<h:head>
<h:outputStyles>
    .Bimage{background-color: gray;}
    body{background:blue;}//ou a cor que desejar
</h:outputStylesheet>

Comment: Explique melhor o que o código faz, assim fica melhor para quem for implementar ele.

Problemas com background


Tell git-blame to use imported history

Question: I have a repository which was created by copying files (not the history) from an SVN repository, with many changes added on top since.
I have since converted the history in SVN into git, and merged it with git merge -s ours.
The problem is when I do a git blame on a file, it still shows every line as being created by the initial commit in the git repository (which copied all the files from SVN), rather than the SVN commit which was really responsible.
Is there a way I can solve this without rewriting all of the git history?
Comment: how many commits are there in the "git-only" history? Why do you not want to rewrite? Rewriting would probably be the cleanest solution.
Answer: You can create a replacement ref for the initial commit from git to make it
appear to most git commands that the history which originated in git was built
upon history imported from svn.
With recent versions of git that can be done using the command:
git replace --graft <FIRST_GIT_COMMIT> <LATEST_SVN_COMMIT>

For older version which don't support that, you can do the same with the following commands:
git checkout -b temporary <FIRST_GIT_COMMIT>
# Set parent of next commit to last one from svn,
# but don't change the working tree or contents of next commit
git reset --soft <LATEST_SVN_COMMIT>
# Create a new commit using contents and message of the first git commit
git commit -C <FIRST_GIT_COMMIT>
# Tell git to use the newly created commit in place of the original git
# commit in most cases.
git replace <FIRST_GIT_COMMIT> HEAD

But, in either case, replacement references do not get transferred automatically with the
standard refspecs used for remotes either when pushing or pulling.  Than can be
done manually by using:
git push origin 'refs/replace/*:refs/replace/*'
git pull origin 'refs/replace/*:refs/replace/*'

It is not possible to have the altered history automatically transferred to
other repositories without changing the commit ID of every commit which was
originally created with git.
Comment: @imz--IvanZakharyaschev Yes, that was added since I'd originally written the answer. I've updated it to reflect that. Thanks.
Comment: A single command would probably also do the thing: `git replace --graft FIRST_GIT_COMMIT LATEST_SVN_COMMIT`
Comment: You may also need to run after `git filter-branch`

Tell git-blame to use imported history


Mailserver using SMTP Relay

Question: I'm using OVH as SMTP Relay. It was always working great, but now I can't send mails anymore.
If I answer to an E-Mail everything is normal. But if I write a new E-Mail it is never being received.
The logfile says that the Mail is being set normally.
<code>"SMTPD" 4576    618 "2017-07-05 11:42:22.357"   "127.0.0.1" "SENT: 220 mysite.com ESMTP"
"SMTPD" 2724    618 "2017-07-05 11:42:22.357"   "127.0.0.1" "RECEIVED: EHLO mail.mysite.com"
"SMTPD" 2724    618 "2017-07-05 11:42:22.357"   "127.0.0.1" "SENT: 250-mysite.com[nl]250-SIZE 20480000[nl]250-AUTH LOGIN[nl]250 HELP"
"SMTPD" 4576    618 "2017-07-05 11:42:22.358"   "127.0.0.1" "RECEIVED: AUTH LOGIN"
"SMTPD" 4576    618 "2017-07-05 11:42:22.358"   "127.0.0.1" "SENT: 334 VXNlcms5hbWU6"
"SMTPD" 3500    618 "2017-07-05 11:42:22.358"   "127.0.0.1" "RECEIVED: ZmFiaW9AbW9kc3ptvbWJpZXMuY29t"
"SMTPD" 3500    618 "2017-07-05 11:42:22.358"   "127.0.0.1" "SENT: 334 UGFzc3dvcmQ6"
"SMTPD" 4576    618 "2017-07-05 11:42:22.358"   "127.0.0.1" "RECEIVED: ***"
"SMTPD" 4576    618 "2017-07-05 11:42:22.359"   "127.0.0.1" "SENT: 235 authenticated."
"SMTPD" 2724    618 "2017-07-05 11:42:22.359"   "127.0.0.1" "RECEIVED: MAIL FROM:<firstname.lastname@example.com> SIZE=924"
"SMTPD" 2724    618 "2017-07-05 11:42:22.359"   "127.0.0.1" "SENT: 250 OK"
"SMTPD" 4576    618 "2017-07-05 11:42:22.360"   "127.0.0.1" "RECEIVED: RCPT TO:<firstname.lastname@example.com>"
"SMTPD" 4576    618 "2017-07-05 11:42:22.360"   "127.0.0.1" "SENT: 250 OK"
"SMTPD" 3500    618 "2017-07-05 11:42:22.361"   "127.0.0.1" "RECEIVED: DATA"
"SMTPD" 3500    618 "2017-07-05 11:42:22.361"   "127.0.0.1" "SENT: 354 OK, send."
"SMTPD" 4700    618 "2017-07-05 11:42:22.363"   "127.0.0.1" "SENT: 250 Queued (0.000 seconds)"
"SMTPD" 2636    618 "2017-07-05 11:42:22.363"   "127.0.0.1" "RECEIVED: QUIT"
"SMTPD" 2636    618 "2017-07-05 11:42:22.364"   "127.0.0.1" "SENT: 221 goodbye"
"SMTPC" 4576    631 "2017-07-05 11:42:22.598"   "18.104.22.168" "RECEIVED: 220 ssl0.ovh.net player772"
"SMTPC" 4576    631 "2017-07-05 11:42:22.598"   "220.127.116.11" "SENT: EHLO mysite.com"
"SMTPC" 4576    631 "2017-07-05 11:42:22.602"   "18.104.22.168" "RECEIVED: 250-player772.ha.ovh.net[nl]250-SIZE 104850000[nl]250-AUTH PLAIN LOGIN[nl]250-AUTH=PLAIN LOGIN[nl]250-ENHANCEDSTATUSCODES[nl]250 8BITMIME"
"SMTPC" 4576    631 "2017-07-05 11:42:22.603"   "22.214.171.124" "SENT: AUTH LOGIN"
"SMTPC" 2724    631 "2017-07-05 11:42:22.607"   "220.127.116.11" "RECEIVED: 334 VXNlcm5hbWU6"
"SMTPC" 2724    631 "2017-07-05 11:42:22.607"   "184.108.40.206" "SENT: c2VydmVyQG1vZHN6b21iaWVzLm92aA=="
"SMTPC" 4576    631 "2017-07-05 11:42:22.611"   "184.108.40.206" "RECEIVED: 334 UGFzc3dvcmQ6"
"SMTPC" 4576    631 "2017-07-05 11:42:22.612"   "188.8.131.52" "SENT: ***"
"SMTPC" 2724    631 "2017-07-05 11:42:22.628"   "220.127.116.11" "RECEIVED: 235 2.7.0 Authentication successful"
"SMTPC" 2724    631 "2017-07-05 11:42:22.628"   "188.8.131.52" "SENT: ***"
"SMTPC" 4576    631 "2017-07-05 11:42:22.635"   "22.214.171.124" "RECEIVED: 250 2.1.0 Ok"
"SMTPC" 4576    631 "2017-07-05 11:42:22.635"   "126.96.36.199" "SENT: RCPT TO:<email@example.com>"
"SMTPC" 2636    631 "2017-07-05 11:42:22.646"   "188.8.131.52" "RECEIVED: 250 2.1.5 Ok"
"SMTPC" 2636    631 "2017-07-05 11:42:22.647"   "126.96.36.199" "SENT: DATA"
"SMTPC" 2636    631 "2017-07-05 11:42:22.651"   "184.108.40.206" "RECEIVED: 354 End data with <CR><LF>.<CR><LF>"
"SMTPC" 2636    631 "2017-07-05 11:42:22.652"   "188.8.131.52" "SENT: [nl]."
"SMTPC" 4576    631 "2017-07-05 11:42:22.699"   "126.96.36.199" "RECEIVED: 250 2.0.0 Ok: queued as 6126F74008D"
"SMTPC" 4576    631 "2017-07-05 11:42:22.700"   "220.127.116.11" "SENT: QUIT"
"SMTPC" 2636    631 "2017-07-05 11:42:22.704"   "22.214.171.124" "RECEIVED: 221 2.0.0 Bye"
</code>
I'm using hMailServer on Windows and I didn't change anything.
SPF records are setup correctly, but only answers work..
Comment: Looks like there in no problem between your server and relay.
Answer: When you are sending a new email what the log is saying? Do you see an attempt? Do you get a bounce back email with an error code?
From your description it sounds like a dns issue, like it cannot fetch the correct MX Records for other domains. Login directly to the server and see if it can resolve normally the domains you are sending to.

Mailserver using SMTP Relay


Element names as constants jquery

Question: Just wondering if anyone has any best practices for naming of jquery elements used in events. e.g elements as constant variables declared at the top, vs inline.
My question for this, is I have a very Jquery heavy client side application and only using server side for data handling and auth.
With this, seeing lines like below drives me a little mad:
$("#examplea").hide();
$("#exampleb").fadeIn(300);

Does anyone use any separation such as:
var examplea = "#examplea";
var exampleb = "#exampleb";

$(examplea).hide();
$(exampleb).fadeIn(300);

I see this looking cleaner in some way, and also means having one place to change code if an element name changed down the track and was used in multiple locations.
I guess this only would become an issue for very large javascript heavy sites, so just throwing out the question on what other people have done to deal with this?
Thanks,
Comment: `var $exampleA = $('#exampleA'); $exampleA.hide();` is my preferred method, and I believe most common practice. The `$` in the variable name isn't completely necessary but is a nice notation to indicate that the variable is a JQuery Object.
Comment: read some style guides... conventions vary across projects but you can get some ideas from them
Comment: @Santi's solution is definitely better. DOM queries are expensive and you should try to do as few as possible
Comment: @Jorg Not an issue!
Answer: Going to the DOM to fetch the same elements is relatively slow, especially if you get those elements often. It might be better to store the actual jQ variable of it:
var $examplea = $('#examplea');

so that you can use it everywhere else:
$examplea.hide();
$examplea.fadeIn(300);

Comment: I'm amazed after all these years of using Jquery ive never considered the cost in fetching from the DOM, always been too worried about the performance in my data fetching. Need to go beat myself with a stick for a while. Great answer.
Prefixing the $ as per @Santi's comment is also a nice notation to add.
Comment: @Nick noted and changed. Try it in a [jsfiddle](https://jsfiddle.net/jorgthuijls/zk7egghv/), you'll be surprised.
Comment: that jsfiddle shocked me. Accepted answer.
Answer: I often place such things inside a simple object literal, and in some cases auto fill this object literal.
eg.  recently knocked up a simple example of an undo / redo.. It's not jQuery but pure javascript.  And right at the top I pull the names of elements automatically from the DOM. For me I think it keeps things a little bit more DRY.
How to undo and redo event in Javascript with browser compatible?
If you look at the first few lines, you will see how I'm capturing all the elements and placing into an object literal 'e';

Element names as constants jquery


Generating random samples obeying the exponential distribution with a given min and max

Question: Random samples obeying the exponential distribution can be generated by the inverse sampling technique by using the quantile function of the exponential distribution:
$$
x = F^{-1}(u) = - \frac{1}{\lambda} \ln(u)
$$
where $u$ is a sample drawn from the uniform distribution on the unit interval $(0, 1)$.
In OpenFOAM software, a distribution model called exponential (here) can be used to generate exponential-distribution random samples, and its users can, supposedly, choose a minimum and maximum value for the exponential-distribution samples prior to the random-number generation.
The governing expression implemented into this software is as follows:
$$
x = -\frac{1}{\lambda} \ln \left[ \exp(-\lambda t_{min}) + u \{\exp(-\lambda t_{max}) - \exp(-\lambda t_{min})\} \right]
$$
where $t_{min}$ and $t_{max}$ are user-defined minimum and maximum values, respectively.
Two (rather broad) questions arise:

Have you ever come across the above expression (or similar one) in the literature for generating exponential-distribution random samples with a given min-max? Or do you think this expression looks like (or is) a heuristic solution?
If heuristic, would you suggest a way to carry out verification tests on this expression to test whether the expression produces samples obeying the exponential distribution within [min,max]? (Plotting normalised histogram (i.e. counts in a bin divided by the number of observations times the bin width) and comparing it with the analytical exponential distribution seem to be problematic due to the min/max limits).
Comment: The first equation inverts the exponential CDF.  The second inverts the truncated exponential CDF.
Comment: This expression inverts the CDF.  It is exact.  This is not a discrete distribution, however, so what do you mean by "discrete" random samples??
Comment: Removed the 'discrete' term. Is the second equation also the inverted CDF? The min and max variables thereat confuse me.
Comment: please post this little sentence as an answer, so that I can hit the accept button.
Answer: You describe truncation to an interval.  I will elaborate.
Suppose $X$ is any random variable (such as an exponential variable) and let $F_X$ be its distribution function,
$$F_X(x) = \Pr(X\le x).$$
For an interval $[a,b],$ the truncation limits $X$ to that interval.  That lops off some probability from $X,$ namely the chance that $X$ either is less than $a$ or greater than $b.$  The chance that is left is
$$\Pr(X\in[a,b]) = \Pr(X\le b) - \Pr(X\le a) + \Pr(X=a) = F_X(b) - F_X(a) + \Pr(X=a).$$
Thus, to make the total probability come out to $1,$ the distribution function for the truncated $X$ must be zero when $x\lt a,$ $1$ when $x\ge b,$ and otherwise is
$$F_X(x;a,b) = \frac{\Pr(X\in[a,x])}{\Pr(X\in[a,b])}= \frac{F_X(x) - F_X(a) + \Pr(X=a)}{F_X(b) - F_X(a) + \Pr(X=a)}.$$
When you can compute the inverse of the distribution function--which almost always means $X$ is a continuous variable--it's straightforward to generate samples: draw a uniform random probability $U$ (from the interval $[0,1],$ of course) and find a number $x$ for which $F_X(x) = U.$  This value is written
$$x = F^{-1}_X(U).$$
$F_X^{-1}$ is called the "percentage point function" or "inverse distribution function."
For example, when $X$ has an Exponential distribution with rate $\lambda \gt 0,$
$$U = F_X(x) = 1 - \exp(-\lambda x),$$
which we can solve to obtain
$$F_X^{-1}(U) = -\frac{1}{\lambda}\log(U).$$
This is called "inverting the distribution" or "applying the percentage point function."
It turns out--and this is the point of this post--that when you can invert $F_X,$ you can also invert the truncated distribution.  Given $U,$ this amounts to solving

$$U = F_X(x;a,b) = \frac{F_X(x)-F_X(a)}{F_X(b) - F_X(a)},$$

because (since we are now assuming $X$ is continuous) the terms $\Pr(X=a)=0$ drop out.  The solution is

$$x = F_X^{-1}(U;a,b) = F_X^{-1}\left(F_X(a)+\left[F_X(b) - F_X(a)\right]U\right).$$

That is, the only change is that after drawing $U,$ you must rescale and shift it to make its value lie between $F_X(a)$ and $F_X(b),$ and then you invert it.
This yields the second formula in the question.
An equivalent procedure is to draw a uniform value $V$ from the interval $[F_X(a),F_X(b)]$ and compute $F_X^{-1}(V).$  This works because the scaled and shifted version of $U$ has a uniform distribution in this interval.  I use this method in the code below.

The figure illustrates the results of this algorithm with $\lambda=1/2$ and truncation to the interval $[2,7].$  I think it alone is a pretty good verification of the procedure.
The R code is general-purpose: replace ff (which implements $F_X$) and f.inv (which implements $F^{-1}_X$) with the corresponding functions for any continuous random variable.
#
# Provide a CDF and its percentage point function.
#
lambda <- 1/2
ff <- function(x) pexp(x, lambda)
f.inv <- function(q) qexp(q, lambda)
#
# Specify the interval of truncation.
#
a <- 2
b <- 7
#
# Simulate data and truncated data.
#
n <- 1e6
x <- f.inv(runif(n))
x.trunc <- f.inv(runif(n, ff(a), ff(b)))
#
# Draw histograms.
#
dx <- (b - a) / 25
bins <- seq(a - ceiling((a - min(x))/dx)*dx, max(x)+dx, by=dx)

h <- hist(x.trunc, breaks=bins, plot=FALSE)
hist(x, breaks=bins, freq=FALSE, ylim=c(0, max(h$density)), col="#e0e0e0",
     xlab="Value",
     main="Histogram of X and its truncated version")
plot(h, add=TRUE, freq=FALSE, col="#2020ff40")

abline(v = c(a,b), lty=3, lwd=2)
mtext(c(expression(a), expression(b)), at = c(a, b), side=1, line=0.25)

Comment: this answer is literally amazing.
Answer: whuber has given you a general answer showing the overall technique.  I will give you a shorter answer that focuses only on your specific case.  Note that there is an answer to a similar question (using the same method but for the truncated normal distribution) here.

You have already pointed out the technique of inverse-transform sampling, which involves generating a random quantile from the uniform distribution $U \sim \text{U}(0,1)$.  When sampling within a truncated interval, you need merely adjust this procedure so that you generate a random quantile over the range of allowable quantiles for the truncated interval, giving a restricted random quantile $R \sim \text{U}(q_\min,q_\max)$.
Now, if $X \sim \text{Exp}(\lambda)$ then the relevant quantile values are obtained by substituting the boundaries of the interval into the CDF, giving:$^\dagger$
$$q_\min = F(t_\min) = \exp(-\lambda t_\min)
\quad \quad \quad
q_\max = F(t_\max) = \exp(-\lambda t_\max).$$
Since $R \sim \text{U}(q_\min,q_\max)$ we can obtain this value from the random variable $U \sim \text{U}(0,1)$ using the transformation:
$$\begin{align}
r
&= q_\min + u (q_\max - q_\min) \\[6pt]
&= \exp(-\lambda t_\min) + u (\exp(-\lambda t_\max) - \exp(-\lambda t_\min)). \\[6pt]
\end{align}$$
Thus, inverse-transformation sampling gives the formula used by the software:
$$\begin{align}
x
&= -\frac{1}{\lambda} \ln (r) \\[6pt]
&= -\frac{1}{\lambda} \ln \bigg( \exp(-\lambda t_\min) + u (\exp(-\lambda t_\max) - \exp(-\lambda t_\min)) \bigg). \\[6pt]
\end{align}$$

$^\dagger$ Here I am making use of the fact that the distribution is continuous to gloss over a slight complication; see whuber's answer for more detail on the general case.
Comment: a very beautiful and useful answer as well.
Comment: just a minor point: the last equation might missing the negative sign?
Comment: The point isn't quite that minor, because the wrong expression for $F$ was used here.  The correct one is $F(t)=1-\exp(-\lambda t).$


Batch - Natives, Jars, and loose class files

Question: I am running Windows 7 64-bit.
I would like to make a .bat file that will run my eclipse project's main.class using (preferably) only that .bat file. The project is still undergoing construction so exporting a runnable jar every few minutes isn't an acceptable solution (nor is installing eclipse on all machines). Furthermore I don't really want to install any more plug-ins, I know there is a way to do this with a .bat but haven't been able to figure it out. Here is what the project root folder looks like:
C:/.../ShootEmUp <-inside there we have:
<code>bin/
lib/
    natives/
    lots of .jar files
res/
src/
    ShootEm/
        OtherPackages/
        ShootEmMain.java
.classpath
.project
RunMe.bat
</code>
I have tried more combinations inside the .bat file than I care to admit. Right now RunMe.bat looks like:
<code>@ECHO OFF

javac src.ShootEm.ShootEmMain.java
java -cp lib/*.jar;. src/ShootEm/ShootEmMain;

PAUSE
</code>
This currently produces a javac: file not found: src.ShootEm.ShootEmMain.java error
I have also tried putting the .bat inside the folder ShootEmUp/src/ShootEm/ (next to the class with public static void main [ShootEmMain.java]) and editing the RunMe.bat code to:
<code>@ECHO OFF

javac ShootEmMain.java
java -cp ../../lib/*.jar;. ShootEmMain;

PAUSE
</code>
This seemed to work a little better as the error I would get then was:
ShootEmMain.java:5: error: package ... does not exist. (the a whole bunch more for all the other jars in the lib folder)
It's useful to note I've already added C:\Program Files\Java\jdk1.7.0_25\bin; to the front of the value of the Path environment variable.
I have also tried classpath instead of cp and a whole crazy list of syntax combinations for each (once I was well past frustrated) to no avail.
Also I realize my .bat example doesn't set the natives as I'm not really sure where that fits into this mess. Thank you in advance!
Answer: You should look at using a tool like ant or maven to build your application. This will streamline producing your artifact.
If it's unreasonable to export a working jar across your environment, I boggle at how you could imagine it's more manageable to export your source code around your environment.
Comment: Ant may work. I am confused as to what you meant by exporting source around the environment. I didn't want to move anything out of the folder eclipse is using. Just create a batch file inside it that would allow for double click execution of the project. If I get ant to work as anticipated I'll choose this as my accepted answer and forget the batch file, assuming it isn't possible.
Comment: It's possible to compile your code using a batch file, but it's unnecessarily complex.
Comment: RE exporting code: "so exporting a runnable jar every few minutes isn't an acceptable solution (nor is installing eclipse on all machines). " My only guess as to why you're writing this batch file is to get your changes to your other machines, or as an attempt to make your project not rely on Eclipse (Which is a great goal).
Comment: Oh yeah, sorry I completely misread that! Yeah I'd rather our artist and tester not need to install eclipse (there's just too much they could mess up).
Comment: If you want to ensure your testers have the most up-to-date artifacts, you should look at using maven over ant, as maven also provides a better mechanism for archiving your artifacts, and has a built in mechanism for versioning.


mod_ssl SSLCACertificatePath Proper Usage or What is the Best way to Handle Multiple Acceptable Client Certificate CAs

Question: I am attempting to use the mod_proxy SSLCACertificatePath directive, but I'm a tad bit confused on how to use it properly.
Here are two links explaining the SSLCACertificatePath directive:
http://httpd.apache.org/docs/2.0/mod/mod_ssl.html#sslcacertificatepath
http://www.modssl.org/docs/2.8/ssl_reference.html#ToC13
I'm not positive on how to create the hashed symbolic links.  The second link states to use the apache make file, but I'm quite clueless on what is exactly being said there.
Any friendly guidance would be greatly appreciated.
Thank you for your time.
UPDATE
The goal of my question was to figure out how to handle multiple CAs for validating end user Client Certificates.  I didn't realize that multiple pem certificates could be using in one file, which, in my case is clearly the right way to move forward.
Answer: I found an open bug regarding this.  Other than downloading the old modssl.org release referred to in the bug and getting the Makefile from it, it seems you can get the value of the hash from openssl x509 -in foo.crt -noout -hash though it's not clear what the ".N" part refers to (perhaps this was for hash collisions (eg first cert with hash 12345678 has a symlink 12345678.1 pointing to it, second cert that has the same hash uses .2?  Or maybe it starts with .0?)
If you get the Makefile.crt file from the old modssl, I believe what you would do is drop it in the folder with all your certificates, then run make -f Makefile.crt in that folder.
Comment: The numbering does start with `.0`.
Comment: Here is the `Makefile` already extracted from the tar.gz: https://gist.github.com/rocketraman/9228a42b78e094b3c2218f6e57844ee0
Comment: Thank you for your answer.  Pointing to that bug report really helped.  Here is the direct link for the download of the resource mentioned in the bug: http://www.modssl.org/source/mod_ssl-2.8.31-1.3.41.tar.gz  I did look at the Makefile.crt and I believe you're correct on the numbering scheme, but I'm not very good at *nix scripts.  .1, .2, .3, etc...  I did try using the commands you recommended and then the symbolic link named as the hash and everything seemed to work.  I will have to try with multiple CA files now.
Comment: Running `make -f Makefile.crt` in the folder with certificates gives `Makefile.crt    ... Skipped` error.
Answer: If you are unclear on how to make the hash-named symlinks my suggestion is not to use CACertificatePath, but rather to use CACertificateFile instead. (Actually this is my suggestion in general: properly maintaining a CACertificateFile  may be slightly more work if you have lots of CA certificates that change often, but you probably shouldn't have lots of CA Certificates, and they shouldn't change much anyway...)  In addition it appears that the Makefile referenced has disappeared from Apache's distribution tarballs (and the general lack of public outcry may indicate how many people are using the "path" method of storing certificates :).
All that said, if you still want to do this you can proceed per what DerfK said (either get the old Makefile, or write your own script/makefile that runs openssl x509 -noout -hash against all your certificate files and creates appropriately-named symbolic links).
Comment: It is in fact as simple as cutting and pasting -- there used to be a `ca-bundle.crt` included with mod_ssl in the Apache 1.x days (and still available at http://certifie.com/ca-bundle/ca-bundle.crt.txt).  For your sanity I would comment the file so you can tell which certificate block belongs to which CA if/when you need to change them later.
Comment: Thank you for your answer.  Unfortunately, we are going to have multiple CA certs and they will be changing.  Do you know how to have multiple certificates in one file?  Is it as simple as cutting and pasting a certificate from one file into another file that has all the certificates?
Comment: Fantastic news.  We most likely will be moving forward with this solution.  Luckily someone else will be in charge of having to generate that .crt file.  Thank you again for your time.


Set Value Variavel Local SQL Server

Question: Gostaria atribuir o valor da variável local dentro do SELECT, como no exemplo abaixo, porém apresenta a seguinte mensagem de erro:

"A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations."

CREATE PROCEDURE [dbo].[TESTE]
    @Param INT
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @VariavelLocal DECIMAL,@VariavelLocal2 DECIMAL
    SELECT  (@VariavelLocal1 = SELECT COUNT(TesteId) FROM Table)
            ,(@VariavelLocal2 = 1)
            ,@VariavelLocal1 + @VariavelLocal2
            ,T2.T2Teste
    FROM Table2 T2
END

Tem como fazer isto?
Answer: A mensagem é clara. Basta não usar SELECT para atribuir valor e para retornar dados:
SELECT @VariavelLocal1 = SELECT COUNT(TesteId) FROM Table),
       @VariavelLocal2 = 1

SELECT @VariavelLocal1 + @VariavelLocal2, T2.T2Teste
    FROM Table2 T2

Answer: Para criar variáveis utilize DECLARE e para atribuir valores utilize SET
Exemplo:
DECLARE @VariavelLocal DECIMAL, @VariavelLocal2 DECIMAL,@VariavelLocal1 DECIMAL
SET @VariavelLocal1 = (SELECT COUNT(TesteId) FROM [Table]);
SET @VariavelLocal2 = 1;
SET @VariavelLocal = (@VariavelLocal1 + @VariavelLocal2);

Pode-se fazer select após isso:
SELECT @VariavelLocal,
       @VariavelLocal1,
       @VariavelLocal2

No seu código:
CREATE PROCEDURE Sp_Teste
    @Param INT
AS
BEGIN

    SET NOCOUNT ON;
    DECLARE @VariavelLocal DECIMAL, @VariavelLocal2 DECIMAL,@VariavelLocal1 DECIMAL

    SET @VariavelLocal1 = (SELECT COUNT(TesteId) FROM [Table]);
    SET @VariavelLocal2 = 1;
    SET @VariavelLocal = (@VariavelLocal1 + @VariavelLocal2);

    SELECT @VariavelLocal,
           @VariavelLocal1,
           @VariavelLocal2
END

Executar Sp_Teste
EXEC Sp_Teste 1

Referências:

DECLARE @local_variable (Transact-SQL)
Instruções SET (Transact-SQL)

Set Value Variavel Local SQL Server


mudei o background do botão e parou o efeito de ação

Question: alterei o background do meu button para #000000 (preto) e parou de realizar a demonstração do click (ficava azul quando clicava)
<Button
   android:id="@+id/btNext2"
   android:layout_width="0dp"
   android:layout_height="match_parent"
   android:layout_weight="1"
   android:text="@string/Next"
   android:textSize="30sp"
   android:background="#000000"
   android:textColor="#ffffff"/>

Comment: Bem Vindo ao [StackOverFlow em Português](http://pt.stackoverflow.com/). No método onClick foi feita alguma alteração?
Answer: Você precisa de um selector nesse background para ter os estados do botão, e não simplesmente uma cor sólida. Crie um arquivo btn_selector.xml no seu diretório drawable e faça algo assim:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@android:color/darker_gray" android:state_pressed="true"/>
    <item android:drawable="@android:color/black"/>
</selector>

E na propriedade background do botão:
android:background="@drawable/btn_selector"