Combinatorial proof for: $\left(\!{n \choose r}\!\right) = \left(\!{n \choose {r-1}}\!\right) + \left(\!{ {n - 1} \choose r }\!\right) $

Question: Without algebraically manipulating this following equality (i.e. reducing down to $n - 1 +r\choose n-1 $ etc. ), what is a combinatorial proof for this following equation?:
$$
\left(\!\!{n \choose r}\!\!\right) = \left(\!\!{n \choose {r-1}}\!\!\right) +
\left(\!\!{ {n - 1} \choose r }\!\!\right)
$$
I can easily understand the LHS: we're placing r indistinguishable items into n distinguishable bins. Hence, n multichoose r.
However, as for the RHS, I'm having trouble understanding the disjoint cases here that allows for the use of  The Sum Rule.
Comment: Your formula is false: the first term in the r.h.s. should be $\dbinom{n-1}{r-1}$.
Answer: Consider the two cases, which are based on what you can do with bin $n$:

either you decide to use bin $n$, so at least one item gets placed in it, after which you have to place $r - 1$ items to $n$ bins, or
bin $n$ is not used at all, which means you have to place $r$ indistinguishable items to $n - 1$ bins

Therefore,
$$
\def\multiset#1#2{{\left(\kern-.3em\left(\genfrac{}{}{0pt}{}{#1}{#2}\right)\kern-.3em\right)}}
\multiset{n}{r} = \multiset{n}{r - 1} + \multiset{n - 1}{r}
$$
Answer: Left hand side: total number of multisets with size r on an n-element set.
Right hand side: Pick a certain element $x$ of the $n$-element set. Break the set of all multisets into 2 types: those containing an instance of $x$ and those not containing an instance of $x$.
Answer: We have that
$$\left(\!\!{n \choose r}\!\!\right)=\binom{n+r-1}r$$
Thus your identity is equivalent to this other
$$\binom{n+r-1}r=\binom{n+r-2}{r-1}+\binom{n+r-2}{r}$$
Then naming $m:=n+r-1$ your identity is equivalent to prove that
$$\binom{m}r=\binom{m-1}{r-1}+\binom{m-1}r$$
what can be proved easily from the definition of binomial coefficient, that is
$$\binom{m-1}{r-1}+\binom{m-1}r=\frac{(m-1)!}{(r-1)!(m-r)!}+\frac{(m-1)!}{r!(m-r-1)!}\\=\frac{(m-1)!(r+m-r)}{r!(m-r)!}=\frac{m!}{r!(m-r)!}=\binom{m}r$$


Javascript plugin to manage placeholder

Question: Look at the Twitter sign up page at https://twitter.com/signup
Even when you click on first input field "Full name" placeholder stays there until I start typing something. That is awesome.
Does anyone know of a good jQuery plugin that comes close to that?
Comment: its called watermarking.
Comment: http://plugins.jquery.com/plugin-tags/watermark
Comment: Twitter does it with an overlay div that is hidden as soon as you type something into the text box.
Comment: But it is not standard watermarking. The placeholder stays even if you have clicked on the input box.
Answer: There's a lot of plugins out there for this.  This is my homegrown solution I use:
/**
 *  Yet another textbox hint plugin...
 *  Usage: $('.selector').hint();
 *  The title attribute of the input will be used as the watermark value.
 */
(function($) {
    $.fn.hint = function() {
        var hintedClass = 'hinted';
        return this.each(function() {
            var $field = $(this),
                title = $field.attr('title'),
                $form = $(this.form);

            // bail out if there isn't a title attribute
            if (!title) { return; }

            // add/remove hint behavior
            var addHint = function() {
                    $field.val() || $field.addClass(hintedClass).val(title);
                },
                removeHint = function() {
                    if ($field.hasClass(hintedClass) && $field.val() === title) {
                        $field.val('').removeClass(hintedClass);
                    }
                };

            // set our focus/blur handlers
            $field.focus(removeHint).blur(addHint);

            // if the field isn't already focused, add the hint now
            $field.is(':focus') || addHint();

            // form submission handling
            $form.submit(removeHint);
        });
    };
})(jQuery);

Comment: Note that a "proper" plugin would probably provide some options for stuff like the hinted class, and how to determine the watermark value - this is just something I whipped together recently and hadn't planned on necessarily sharing (but it works).
Answer: Zero JavaScript needed in browsers that support the HTML5 placeholder attribute
Description: <input type="text" name="desc" placeholder="My Email Account">

Comment: with a standard placeholder when you click on it the placeholder disappears. that is not the case with the twitter sign up.
Answer: I wrote this example that functions just like the twitter one, but you might want to grab some additional CSS from the twitter bootstrap CSS if you want the exact styling.
I talk more about the method in this similar stackoverflow question.

Javascript plugin to manage placeholder


What's the recommend way of restoring only parts model in distributed tensorflow

Question: When we finetune a model on a different task, only a part of vars in the model are restored from the pretrained task and others are left as initial values.
As many docs recommends(page1 page2), when training with a local graph, restoring the pretrained model after running the global init op(call restoring in "init_fn" if MonitoredSession or supervisor is included).
But in the distributed case, does global init op make "model_ready" returns true before the restoring-model called? other non-chief nodes will use the "not ready" values.
Answer: Figure it out.
global_variables_initializer is in facet variable_initializers(global_variables()). So we can initialize only some selected vars and restore the lefts from pretrained models.
"model_ready" will keep as False until all vars are restored.


Rust JWT claim not valid struct field name

Question: I'm trying to generate some JWTs using the following https://github.com/Keats/jsonwebtoken crate. Basically, I have
#[derive(Debug, Serialize, Deserialize)]
struct MyTokenClaims {
    foo: String,
    bar: String,
    baz: String,
}

Now the problem is that in the JWT the claim foo would actually be example.com/foo. Is there a way to override the field name in the JWT that is used after encoding it, since I can't create a struct field with that name?
Answer: In serde you can alias the field name:
#[derive(Debug, Serialize, Deserialize)]
struct MyTokenClaims {
   #[serde(rename(serialize = "example.com/foo", deserialize = "example.com/foo"))]
    foo: String,
    bar: String,
    baz: String,
}

When reading JSON, your code now looks for the field "example.com/foo": "value" and serialises the value in rust to foo: "value".
Comment: `#[serde(rename(serialize = "example.com/foo", deserialize = "example.com/foo"))]` can be abbreviated to `#[serde(rename = "example.com/foo")]`.


Would you provide a study routine for Spivak's Calculus?

Question: I've been working on Spivak's Calculus for the past few days and although I can manage to solve most problems, they take a lot of time. Some chapters have over 20 exercises and it can take several days to get through the whole list. Would anyone care to provide a list of recommended exercises for each chapter? I take it that this book has been used in several honours course in Calculus, therefore someone should have a related material.
Thanks in advance.
Comment: follow to his "Calculus on Manifolds"
Answer: I am little skeptical that someone else's study or course routine will be optimally adapted to your needs.  But yes, I have used Spivak's text in an Honors Calculus course, and this webpage contains a list of problems I assigned week by week.
I feel compelled to add that there were also lectures and lots of office hours: each problem set includes more than one problem that very few students were able to answer without some assistance from each other and from me.
Comment: This is exactly what I was looking for, many thanks.
Comment: The links on that page to the PDFs are broken.  Add a `alpha.` to the domain name for each and they work.


Como remover ou limpar valor do input file?

Question: Oi pessoal do stackoverflow.
É possível remover ou limpar valor do input file ?
Também vi outro exemplo de resetar ou remover todos arquivos input file usando:
document.getElementById("seu_id_do_input").value = "";

Qual é melhor maneira de limpar input file ?
Alguma idéia brilhante ?
Comment: Não é possivel apagar arquivos no disco com JavaScript no lado do cliente. Precisas de fazer isso no lado do servidor.
Answer: Exemplo de como limpar o valor de um input type=file (na verdade é um truque):

$().ready(function() {
 list = $("[class^=f_clear_]");
 if (list.length > 0) {
  $.each (list, function(key, row) {
   var arr = row.className.split("_");
   var selector = "#f"+arr[2];
   $(this).click(function(){
    GenericInputFileCleaner(selector);
   });
  });
 }
});

function GenericInputFileCleaner(selector){
 var clone = $(selector).clone(true);
 clone.insertAfter(selector);
 $(selector).remove();
 clone.attr("id", selector.substring(1));
}

<form action="tmp.php" method="post" enctype="multipart/form-data">
<input type="button" value="x" class="f_clear_1"> <input name="f[]" type="file" id="f1">

<input type="button" value="x" class="f_clear_2"> <input name="f[]" type="file" id="f2">

<input type="button" value="x" class="f_clear_3"> <input name="f[]" type="file" id="f3">

<input type="submit" value="send">
</form>

A lógica aqui é clonar o elemento que deseja limpar, adicionar o clone logo na frente e remover original em seguida. Assim, o clone apresentará o atributo value vazio. No final, o clone recebe o mesmo ID do original. Mas isso deve ser feito após o original ter sido removido.
Isso é um meio mais simples e seguro do que tentar setar o atributo value:
document.getElementById("seu_id_do_input").value = "";

ou Jquery
$("#seu_id_do_input").val("");

Ambos deveriam funcionar bem, mas dependendo do browser e versão, podem não funcionar. O motivo todos já devem saber que é evitar manipular o atributo value com dados maliciosos. Porém, não há problema algum em apagar o atributo e todos os browsers poderiam liberar isso. Mas alguns browsers, talvez por bug ou falta de implementação, não permitem modificar nada, mesmo apagar o valor.
Por isso, uma opção mais segura é clonar, adicionar o clone no corpo HTML e remover o original.
Preferi fazer com JQuery por ser mais prático. O código ficaria maior e mais suscetível a erros de compatibilidade se tentasse inventar algo sem o auxílio do framework.
Achei desnecessário comentar o código e explicar em detalhes porque é bem pequeno, legível, fácil de entender. A parte que interessa é a função GenericInputFileCleaner(). O restante é meramente didático. Adapte conforme o seu caso.
A desvantagem é que obviamente perderá quaisquer eventos ligados a esse elemento ou que dependam do mesmo (onclick, por exemplo). Mas pode ser "facilmente" resolvido recriando tais eventos caso existam.


como chamar stored procedure com linq

Question: Bom dia pessoal.
Tenho uma stored procedure no sql server,
e gostaria de chama-lo na minha aplicação c#,
via linq.
Desde ja agradeço qualquer ajuda
Answer: Crie a Stored Procedure no seu banco de dados.
CREATE PROCEDURE BuscaCliente @nome varchar(255)
AS
BEGIN
  SELECT * from Cliente where nome = @nome
END

No Visual Studio adicione um arquivo do tipo LINQ to SQL, no meu caso
vou adicionar com o nome Banco.dbml.
Ao criar o arquivo, adicionei uma nova conexão em Server Explorer
apontando para meu banco de dados de testes e navegue até a pasta
StoredProcedures
Clique e arraste a StoredProcedures para dentro do arquivo Banco.dbml
Será adicionado um Método com o nome da SP, no código é só chamar a
SP

O código abaixo mostra o uso da procedure:
BancoDataContext bd = new BancoDataContext();

var resultado = bd.BuscaCliente("celso");
foreach (var r in resultado){
  Console.Write(r.nome);
}
Console.ReadKey();

Fonte: http://csharpnamarra.blogspot.com.br/2013/04/linq-x-stored-procedure.html
Answer: Boa tarde pessoal. ja resolvi o problema. pra quem tiver a mesma duvida ai vai a solução:
public List<SP_Comb> ListByCliente(int parametro1, string parametro2)
{
  List<SP_Comb> ListaCliente = new List<SP_Comb>();

  var q = DataContext.SP_ComboEntidade(parametro1, parametro2);

  foreach (var lista in q)
  {
    ListaCliente.Add(lista);
  }
  return ListaCliente;
}

onde:
SP_Comb - mapeamento das stored procedure(via sqlmetal)
SP_ComboEntidade - stored procedure

como chamar stored procedure com linq


Intuition about the deep meaning of Bayesian priors and its influence on posteriors

Question: In estimating posterior distributions, Bayesians rely on the idea of the prior distribution. In many examples, I see this being set fairly arbitrarily, ie ~N(0,1).
It's clear that the posterior is integrally related to the prior, however, the fact that it is arbitrary seems unsatisfactory. Furthermore, the prior affects the posterior in a qualitative way. Viewed in the sense of a "weighted" average, this is further unsatisfactory.
My two specific questions are:
What is the value of having priors when they seem arbitrary, or are handwaved or calculated away at a later stage? If this dismissive description of attention of priors is correct, and since priors are so integral to Bayesian stats, doesn't this undermine the practice or theory of Bayesian stats?
Related question: don't priors have considerable influence on the resulting posterior? (If they do not, the question above applies). If they do, and since apparently not much thought is given to them, doesn't this just push the "philosophy" and "content" of Bayesian stats into a black box?
I freely admit this question doesn't seem right (or is embarrassing to me). Where has my education about Bayesian stats gone wrong?
Comment: You can see a prior as containing prior information. You can also see them just as a form of regularization (i.e., preventing estimates from blowing up). The second view suggests that priors can still be very helpful even though they don't really capture everything we might know *a priori*. This is the approach the field of Machine Learning has used, to great success.
Comment: To borrow a really intuitive explanation from the ['Learn Stan with Ric' channel](https://www.youtube.com/watch?v=S-qU3lUG6Ck&list=PLtjJ_Rt8bTdJEeV0afADtWvqq_t0_iksX&index=4&t=1150s): think of the prior as just another data point (or, more generally, the combined influence of other data). Just not the one in your *current* sample.
Answer: Your statement echoes Jaynes.  He said

When we look at these problems on a sufficiently fundamental level and realize how careful one must be to specify the prior information before we have a well-posed problem, it becomes evident that there is, in fact, no logical difference between (3.51) and (4.3); exactly the same principles are needed to assign either sampling probabilities or prior probabilities, and one man's sampling probability is another man's prior probability.

The equations in chapter three are on elementary sampling theory and four on elementary hypothesis testing.
There are three primary methods to create Bayesian theory from Cox's, de Finetti's and Savage's axioms.  Cox is built on logic, de Finetti on gambling and Savage on preferences.
In all three cases, you do not get well-posed problems with arbitrary calculations.  If you think of a probability statement as a statement about a logical assertion, then to get a proper answer all parts of the logical argument must be included.  Likewise, when one gambles, one would be insane to purposely ignore information about which you were going to gamble on.  Finally, it begs rationality with respect to preferences to ignore knowledge.
I believe the mistake comes from a misunderstanding of probabilities as frequencies.  They are not.  Long run frequencies will not be derived from Bayesian methods.  It can be the case they have nice Frequentist properties, but this is incidental.
Now, this does ask is there any circumstance where one should ignore prior information and the answer is "yes."  As long as one is not introducing contradictory information or damaging the assertion there can be.  Consider the case of a high dimension model with prohibitive calculation costs that could be approximated closely by an approximate solution.  Weakening the prior gives a solution when a strong prior makes it impossible to do the work.  Likewise, consider a low dimension model where time is of the essence and determining a full prior would result in catastrophic losses due to the time constraints.  This is the terrorist with the bomb scenario.  In that case, it is rational to use less than the available information.
Laziness or ignorance is not an excuse for ignoring the prior.
Answer: This is how I read your question -- "Why are priors given arbitrary values when they have a bearing on the calculated posterior?"
Note: I come from a physics background -- please let me know if you think I am using some terms wrong.
I shall pose a series of atomic questions and answer them as I understand them from the perspective of Bayesian statistics.

Notation and terms: I think of a system connected to each other causally in pairs (think of a directed graph). The quantities are divided into Query, Hidden and Evidence. The posterior probability is given by $P(Q|E) = \sum_H P(Q|E,H)P(H)$, it is marginal with respect to the variables in the Hidden($H$) class.
 The statement of Bayes' Theorem is
 $\underbrace{P(Q|E)}_{\text{posterior distribution of Q given E}} = \frac{{\overbrace{P(E|Q)}^{\text{likelihood of E given Q}}}\;\times\;{\overbrace{P(Q)}^{\text{prior distribution of Q}}}}{\sum_{Q'}P(E|Q')P(Q')}$
Is the prior important to the calculation of the posterior?: Given enough evidence/data and a simple enough event space, no. But a suitable choice of the prior can lead to the "correct" posterior given less evidence/data or less iterations.
Is the prior distribution ignored in practice?: Given enough data, it is not important because you can use the valuable time you have to other things. But having a prior distribution available from experiments enables better sanity checks (tests or debugging) once the posterior is obtained.
When is the prior distribution important at all?

Less data is available
Multiple similar competing hypotheses (correlated with having a larger event space)
Philosophically important to Jayne's (or what I subjectively believe is Jayne's explanation of the prior -- I haven't had a lot of time to assimilate it yet) approach.

What makes sense for statistical mechanics? It is fine to seek explanations over discrete event spaces without referring to the priors. But faced with multidimensional systems on which most problems scale as the factorial, it seems to me that maximizing the entropy over the given constraints IS a very pragmatic way. But then I,as a beginner, haven't had enough time to understand if this is the only/best possible choice.
Answer: My possibly idiosyncratic view is as follows.  If we had an exact, fully-known, prior distribution on the parameters, possibly belief-based, and we knew the true likelihood function, the Bayesian paradigm gives us the optimal way of updating that prior with the likelihood to get a posterior.  In real life we don't have either a prior or a likelihood, except in what seems to me to be rare cases, so we apply an intuitive "smoothness in function space" argument that runs as follows.  As long as the prior we use for calculation is close to the real, unobservable prior we have, and the likelihood function we use for calculation is close to the real, usually unknowable likelihood function, applying the Bayesian paradigm will get us a posterior that is close to the real, uncalculatable posterior.  Applying the Bayesian paradigm even with approximate priors and likelihoods is likely to get us closer (on average) than doing something else, because it eliminates a source of noise in the move from prior to posterior - noise due to using a suboptimal updating algorithm.
This, then, is the value of trying to state your prior information as a probability distribution - it allows you to use the optimal updating algorithm, thereby reducing the error in the beliefs you form after you've looked at the data.
As a rather lengthy side note, this implies that Bayesian robustness is a desirable feature of our overall process (assigning priors and likelihood functions, performing the update calculations), the more so as our confidence in the accuracy of our constructed / assumed prior and likelihood functions degrades.  At some point, we'll have so little confidence in our ability to form any sort of reasonable approximation to one, the other, or both, that we may as well abandon the Bayesian paradigm and do something else. Alternatively, the cost of setting up and executing the Bayesian paradigm may be so great, relative to the gains thereof, that we are, again, better off doing something else, such as running a classical t-test, observing a t-statistic of 19.4, and rejecting the null hypothesis that we created just to make life simpler.
Now, as to the influence priors have - that depends on the prior, the likelihood function, and the data.  It is quite easy to find all sorts of real-world situations where the data overwhelms the prior, in which case even very different priors lead to very similar posteriors.  In these situations, worrying about the likelihood is far more important than worrying about the prior.  On the other hand, in situations where getting data is very cost or time-intensive, the prior information may have to be carefully extracted from the relevant experts in order to make the best use of it as we can.  (This was the case in my previous job, in which I did reliability analysis for solar panels and trackers, among other things - testing a large, expensive piece of equipment that is supposed to track the sun to derive a mean time to failure is both time-consuming and expensive.)  So, the influence of the prior is situational, and that same situationality drives where we should focus our efforts in order to make best use of the optimal updating algorithm that Bayes' Theorem gives us.
Comment: It seems like your post essentially agrees with my "critique" that the posteriors are arbitrary. To me, this seems to be saying that philosophically this is no better than just the frequentist approach and its use of normal distributions, except for some corner cases where priors do matter (and even then it seems like these unusual priors are subject to handwaving and "politics").
Comment: I acknowledge there seems to also Bayesian process, which has seperate and independent value to the "issues" or "controversy" about the priors (or does it, since it is so integrally linked?).
Comment: No, no!  Arbitrary priors that are close to reality are much better than no priors at all!   It's very roughly analogous to saying "243.19092 x 43.989 is approximately equal to 10,000"; sure, 10,000 isn't exactly right, but it's a lot better than just saying "some number greater than 243."  And... frequentist tests are known to be fundamentally incoherent in a way which Bayesian tests are not.


JavaFX8 Background Thread still interferes with GUI

Question: I want to write a JavaFX GUI that loads and parses a bigger file (22M) which takes about 30 seconds. However, when I start the parsing in a Task, the rest of the GUI is pretty unresponsive. It is however, not fully unresponsive, but still it hangs for several seconds now and then. To demonstrate that, I wrote a small application that shows the progress of the parsing in a progress bar and executes another task in parallel which simply updates a label every second. Now, this second task shouldn't be blocked by the first one, so I'm probably doing it wrong. Here's the code:
Task to tick every second:
class TimeTask extends Task<Void> {
    @Override
    protected Void call() throws Exception {
        while (true) {
            updateMessage(Instant.now().toString());
            Thread.sleep(1000);
        }
    }
}

Replacement for parsing the logfile:
The update method is called in 100ms steps from the parser.
public class ParseLogfileTask extends Task<Void> {

private LinkedList<Integer> numbers = new LinkedList<Integer>();
private Random random = new Random();

@Override
protected Void call() {
    Instant startInstant = Instant.now();
    while (Duration.between(startInstant, Instant.now()).getSeconds() < 25) {
        for (int i = 0; i < 10000000; i++) {
            numbers.add((Integer) random.nextInt());
        }
        Collections.shuffle(numbers);
        Collections.sort(numbers);
        numbers.clear();
        updateParseProgress(
                (int) Duration.between(startInstant, Instant.now())
                        .toMillis(), 25000);
    }
    return null;
}

public void updateParseProgress(int currentIndex, int maxIndex) {
    updateProgress(currentIndex, maxIndex);
}

}
start method of the application:
@Override
public void start(Stage primaryStage) {
    try {
        Group root = new Group();
        Scene scene = new Scene(root, 400, 400);
        VBox vbox = new VBox();
        vbox.setAlignment(Pos.CENTER);
        ProgressBar bar = new ProgressBar();
        Label label = new Label("new");
        vbox.getChildren().addAll(bar, label);
        root.getChildren().add(vbox);
        primaryStage.setScene(scene);
        primaryStage.show();

        Task<Void> timeTask = new TimeTask();
        Task<Void> logFileTask = new ParseLogfileTask();
        bar.progressProperty().bind(logFileTask.progressProperty());
        label.textProperty().bind(timeTask.messageProperty());
        Platform.runLater(() -> {
            new Thread(timeTask).start();
            new Thread(logFileTask).start();
        });
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

EDIT: I removed a 5 seconds sleep after the start of the timeTask. It is not necessary for the real problem. The real problem is that the timeTask does not update the label every second as long as the logfileTask is running. Is merely updates every 1-5 seconds. As soon as the logfileTask is done, the timeTask updates the label exactly as it should. Could this have to do with Thread priorities? The logfileTask produces quite heavy load...
EDIT 2: I cannot reproduce the problem by using other ways to create load. I have those problems only with the parser, which was created by ANTLR and creates a huge parse-tree (many objects). However, since the parser is launched in a background thread, how could it interfere with the JavaFX Application thread?
EDIT 3: Looks like it is indeed the garbage collection. I replaced the logfile parsing with generating a huge list of numbers, sorting them and throwing them away again, and I could see the same gaps as with the parser running (not so often, but with larger impact)
Comment: How big is the parse-tree? I suppose if you are creating too many objects you may be forcing the garbage collector to run frequently, which could potentially block all running threads.
Comment: well, that could indeed be the case. The tree has about 7 mio tokens = leaf nodes.
Comment: I think that makes it an ANTLR question, more than a JavaFX question: so I will defer to people who know that technology (I don't). For some very general advice: try increasing the heap size for your JVM to see if that fixes the issue. If it can run with a heap size comfortably in the range you can expect your users to be able to use, then I'd just go with that option. If not, you'll probably need to find a different parse strategy. (I have no idea what you're parsing, obviously, but you might want to think along the lines of "event driven" parsing rather than "document model" parsing.)
Comment: I already thought about the idea to get rid of the parse-tree at all. In ANTLR the nice thing about parse trees is that they allow you to write a pure grammar (without java commands in it). As a sidenote: the document that I'm parsing is a [Robocup 2D simulation](http://sourceforge.net/projects/sserver/) [logfile](http://fei.edu.br/rcs/2D/2014/finals/final/match_1/201407241009-WrightEagle_3-vs-Gliders2014_2.rcg.gz) of a game. The goal is to build a JavaFX Monitor for those games.
Comment: @James_D if you would make the garbage collection suggestion an official answer, I would mark it solved for you. Don't want to take the credit myself
Answer: The amout of operations you call in the ParseLogfileTask are way to many. It is like a while(true).
Use a Thread.sleep before the return null.
@Override
protected Void call() {
    Instant startInstant = Instant.now();
    while (Duration.between(startInstant, Instant.now()).getSeconds() < 25) {
        for (int i = 0; i < 100000; i++) {
            numbers.add((Integer) random.nextInt());
        }
        Collections.shuffle(numbers);
        Collections.sort(numbers);
        numbers.clear();
        updateParseProgress(
                (int) Duration.between(startInstant, Instant.now())
                .toMillis(), 25000);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {

        }
    }
    return null;
}

So it worked for me.
Additionally it would be better to use
ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(timeTask);
service.execute(logFileTask);
for calling your Threads.


f displays vector to orthogonal vector, then exists orthogonal map g so that λ $\epsilon$ $R_{>0}$ and f=λg

Question: I'm currently pretty stuck at showing this. This is the task:

Let an automorphism f: $V\buildrel\over\rightarrow V$ display orthogonal vectors to orthogonal vectors which means:
f(v) $\bot$ f(w) if v $\bot$ w. (for v,w in V)
Show there exists an orthogonal map g and  λ
$\epsilon$ $R_{>0}$  so that  f=λg.

In a first task we had to show that (v+w) $\bot$(v-w) $\leftrightarrow$ ||v||=||w||,  what I've done and it's a hint to use this. However I did not come up with anything special so far. I thought of the identity, but how do I know that f(v)=x=λv=λg(v) which I concluded wrong. I also thought of g=$\frac{1}{λ}$f. For orthogonal vectors it seems to work as the definition of an orthogonal map would be:

$<$g(v),g(w)$>$=$<$$\frac{1}{λ}$f(v),$\frac{1}{λ}$f(w)$>$=0=$<$v,w$>$ and obviously f=λg (maybe this is a wrong thought?)

but now for any vector v $\epsilon$ V it is not sure on what f displays v so that g is really orthogonal. I don't know how to make use of the hint here. Maybe work with the bijectivity? Nevertheless I would appreciate some help!
Comment: Is $f$ assumed to be a linear functional?
Comment: It's not written anywhere that it is ..
Comment: Also, what is an "orthogonal function" $g$? Orthogonal to what?
Comment: Does "orthogonal mapping" or "orthogonal map"is better? I did not know how to really translate the word into english.
Comment: So basically $(x,y) = (gx,gy)$, assuming the functions here are linear.
Comment: How is f=λg in your case?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/79296/discussion-between-babemcnuggets-and-alex-r).
Answer: Being an automorphism means that $f:V\to V$ is linear and invertible.
Fix an arbitrary unit vector $v$ (so that $\|v\|=1$, i.e. $\langle v, v\rangle=1^2=1$), and let $\lambda:=\|f(v) \|$. Since $f$ is invertible, $\lambda\ne0$. We have to show $g:=\frac1\lambda f$ is orthogonal.
Here is the key point: let $w$ be another unit vector, then $\|w\|=1=\|v\|$ so $v+w\perp v-w$ thus $f(v) +f(w) \perp f(v) -f(w) $ implying $\|f(w) \|=\|f(v) \|=\lambda$.
We get that $g$ maps unit vectors to unit vectors, hence preserves the norm, and preserves orthogonality, as $f$ did.
For any unit vector $w$, use that the orthogonal decomposition of an arbitrary vector $x$ along $w$ as $x=\alpha w+x_\perp$ is unique with $\alpha=\langle x, w\rangle$.
Apply $g$ to the decomposition and deduce $\langle g(w), g(x) \rangle=\langle w, x\rangle$.
Comment: Only question I have now is, why can I fix a vector v so that it is an unit vector? Was it Gram-Schmidt, where we can make any vector an unit vector?
Comment: No, just divide the arbitrary vector by its norm.


Does there exist a function such that the preimage of $x ^ { 2 } + y ^ { 2 } \leq 1$ is the closed interval $[-1,1]?$

Question: Does there exist a continuous function $f : \mathbb { R } \rightarrow \mathbb { R } ^ { 2 }$ such
that the preimage of the closed unit disk $x ^ { 2 } + y ^ { 2 } \leq 1$ is the closed
interval $[ - 1,1 ] ?$ the open interval $( - 1,1 ) ?$
To be honest, I don't really know how to go about this problem.
Comment: the preimage of a set $S$ being $[-1,1]$ is not the same thing as the image of $[-1,1]$ being $S$.  space filling curves are super overkill
Comment: https://en.wikipedia.org/wiki/Space-filling_curve
Comment: I'm fairly certain you can get a continuous function from $[-1,1]$ to the closed unit disc by an appropriate space filling curve.
Comment: @RolfHoyer how would you go about this without using space filling functions? We never went over those in my lecture so I doubt the answer would have to be related to that.
Answer: Space filling curves certainly work but that's quite excessive.
For a function $f:\Bbb R\to\Bbb R^2$ defined by $f(x):=(f_1(x),f_2(x))$, the preimage of $D:=\{(x,y)\in\Bbb R^2:x^2+y^2\le 1 \}$ is merely the set
$$\begin{align}
f^{-1}(D) &= \{ x\in\Bbb R: (f_1(x),f_2(x))\in D \} \\
&= \{ x\in\Bbb R: f_1(x)^2+f_2(x)^2\le 1 \}.
\end{align}$$
By letting $f(x)=(x,0)$, we have
$$
f^{-1}(D)= \{ x\in\Bbb R: x^2\le 1 \} = [-1,1].
$$
On the other hand, by requiring that $f$ be continuous, the preimage of $D$, which is a closed set, must also be closed. Since $(-1,1)$ is not closed, we cannot find a continuous function such that $f^{-1}(D)=(-1,1)$.
Comment: Yep. The trick here is to realize that the preimage need not necessarily give the given set when the function is then applied to it - only that the result of such application be contained within the given set.
Answer: f:R -> R×R, x -> (x,0) is continuous.
Let D be the closed unit disk.
The preimage of D by f is
f$^{-1}$(D) = { x : f(x) in D } = [-1,1].
Comment: Good example, but you really should format it better.


Usar uma pasta layout para mais de um tamanho

Question: Eu tenho um Tablet(7") e um smatphone(5").
Minhas pastas de layout são:
layout > Possui quase todos os layouts
layout-large > Uma das telas(Tela A) ira se comportar diferente para largos
layout-normal-land > Uma das telas(Tela B) ira se comportar diferente para normais
Até ai o resultado é o seguinte:
Tela A:

tablet, aparesenta a modificação
smatphone nao apresenta a modificação

Tela B:

tablet(land), aparesenta a modificação
smatphone(land) apresenta a modificação

Se o tablet é considerado large porque ele é afetado por normal ?
Como eu faço para contornar isso?
Eu não quero fazer inúmeros layouts!
Comment: Qual é a `minSdkVersion` da sua aplicação?
Comment: É a 17 ( android 4 )
Answer: A razão é simples, veja o que diz a documentação:

Be aware that, when the Android system picks which resources to use at runtime, it uses certain logic to determine the "best matching" resources. That is, the qualifiers you use don't have to exactly match the current screen configuration in all cases in order for the system to use them. Specifically, when selecting resources based on the size qualifiers, the system will use resources designed for a screen smaller than the current screen if there are no resources that better match (for example, a large-size screen will use normal-size screen resources if necessary).

O paragrafo em bold explica porque o tablet(large-size) está a usar os recursos definidos para normal-size:

(...)Especificamente, ao selecionar recursos com base nos qualificadores de tamanho, o sistema irá utilizar os recursos definidos para uma tela menor que a tela atual, se não houver recursos que melhor se adequam (por exemplo, um large-size screen usará os recursos definidos para normal-size screen se necessário).

Você definiu recursos para layout-normal-land mas não para layout-large-land.
O tablet, quando na posição landscape, como não encontra recursos definidos para esta situação(layout-large-land), utilizará os recursos definidos para uma tela menor(layout-normal-land).

Na versão Android 3.2 foram introduzidos novos qualificadores de tamanho que oferecem mais controle na definição dos recursos a usar por cada tamanho de tela.
Agora, os tamanhos que você especificar usando estes qualificadores, não são os tamanhos de tela reais. Em vez disso, os tamanhos são para a largura ou a altura em unidades dp que terão de estar disponíveis para o layout.
São 3 os qualificadores:

Menor largura: sw<N>dp
Use esse qualificador para garantir que, independentemente da orientação atual da tela, a sua aplicação tem, pelo menos, <N> dps de largura disponíveis para sua interface.
Exemplos de utilização:  sw600dp, sw720dp
Largura da tela disponível: w<N>dp
Especifica a largura mínima <N> necessária em dps para que os recursos possam ser usados. O valor correspondente do sistema para a largura muda quando a orientação da tela alterna entre retrato e paisagem para reflectir a largura real actual que está disponível.
Assim, esta opção pode ser usada para especificar a largura mínima necessária para o layout,tanto em retrato como em paisagem, evitando ter de usar qualificadores de tamanho e qualificadores de orientação juntos.
Exemplos de utilização:  w600dp, w720dp
Altura da tela disponível: h<N>dp
O mesmo que o anterior só que relativo à altura.
A maioria dos aplicativos não necessitará deste qualificador, considerando que geralmente é o possível usar o scroll vertical havendo, portanto, mais altura disponível, enquanto que a largura é mais rígida.
Exemplos de utilização:  h600dp, h720dp
Comment: Considere usar os novos qualificadores, eles normalmente permitem diminuir o número de *layouts* a definir.
Comment: Certo, eu criei uma pasta layout-large-land e coloquei a copia do layout que eu não queria que fosse afetado.


Excel VBA Seed based on the date

Question: I'm working on a programm where I use a seed. This seed should be based on the date, so every single day i get a new value. Using the seed several times a day should not change the value getting back.
This is what my seed looks like:
Randomize
todayValue = Int(50 * Rnd)
Now, how do I base a seed on the date?
Is there maybe another way to have a seed based on the date?
Thank you very much!
Comment: can you write your code so far? so we can help you better...
Answer: See this post on getting seeded random values in VBA.
All you need to do is call the Rnd function with a negative value, prior to running your code. To do that, you can use the Date function. In VBA, Date values are just Longs, representing the number of days since some set date in the past.
Here's an example of how you could do what you want.
Sub rndSeedTest()
    MsgBox Date & " --> " & CLng(Date)
    Rnd -Date
    MsgBox Rnd & _
        vbNewLine & Rnd & _
        vbNewLine & Rnd & _
        vbNewLine & Rnd & _
        vbNewLine & Rnd
End Sub

Answer: If you want to get same number every time the function runs, then that is not a random number, you have to create something that looks random, for example
Sub test()
    Dim todayValue As Long
    todayValue = Date
    todayValue = todayValue + 1538 ' To make it a little random
    MsgBox todayValue
End Sub

Answer: I found a way to do it, i just save the date and the Value of the day in a certain cell on my sheet. this is how my code looks like:
If MainSheet.Cells(1, 1) = Date Then
    todayValue = MainSheet.Cells(1, 2)
Else
    Randomize
    todayValue =  Int(50 * Rnd)
    MainSheet.Cells(1,1) = Date    'saves the date in Sheet
    MainSheet.Cells(1,2) = todayValue    'saves todayValue in Sheet
End If

Excel VBA Seed based on the date


Expected value of adjacent pairs in a deck of 52?

Question: I am having trouble wrapping this around my head. I believe that using an indicator random variable would be the best approach. Let N be the number of adjacent pairs. The probability of an adjacent pair would be 3/51. Given that the first card is a set value, the probability of the card to its right being the same value would be 3/51. So then E[I]=3/51.
I would like to believe that E[N] would equal=(3/51)*26. My thinking is that the deck of cards is set in a format of ABABABAB. The value of A is the key card. The value of B is the card that must match A. So if A were to be the King of Spades, but B were the Queen of diamonds, that pair would not be counted along with the other lonesome King card that should've been with the King of Spades.
That is why if one King card indicates that it is not a pair, the other king is automatically discarded as a potential pair. This is done with all cards so that is why you multiply it by 26. This is just my thinking, but can someone give me some guidance?
Edit: Typo
Comment: Oops sorry, typo.
Answer: Line the cards up. Number the $51$ gaps between the cards. Let the random variable $X_i$ be $0$ if the two cards on either side of the $i$th gap have different value, and $1$ if they are the same. Then we are after the expected value of $\sum_i X_i$, which by linearity of expectation is equal to $\sum_iE(X_i)$. Since each $X_i$ has expectation $\frac3{51}$, you have your answer there.
Note: this counts three-of-a-kind as two pairs (the two gaps between the three cards both have equal-value cards), and four-of-a-kind as three pairs. If you want it to count differently, you need to slightly adjust the definitions of the $X_i$ in order to take that into account. Note that (depending on how you do it) $X_1$ in that case might have a slightly different expectation from the rest. The idea of exploiting linearity of expectation to avoid having to take nasty interactions into account still stands, though.


Alter views results in a hook

Question: When I use contextual filters in a view, I can select an option to display a summary when the argument is not present. If I do it, it shows a list of node IDs instead of titles. For example, I get the following output, where the first number is the node ID, and the second number is the count of nodes.

1256 (12)
4323 (723)
5643 (34)

I want is to rewrite the output and replace the node ID with its title. ViewExecutable has a $args property I can check to know when the argument is not present.
How could I achieve this in a hook? In Drupal 7 I could use hook_views_post_execute(). I modified $view->result and changed it on my own.
I tried to do the same with Drupal 8 and the same hook, but hook_views_pre_render() gets a ViewExecutable object, and I don't know how to change it. I used the following code.
function MYMODULE_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'myidoftheview') {
    $results = $view->result;
    foreach ($results as $result) {
      \Drupal::logger('myview')->notice('
'.print_r($result,TRUE).'
');
      // What code should I write here?
    }
  }
}

Comment: You can also use `function MYMODULE_views_pre_render(\Drupal\views\ViewExecutable $view) { ...`. Next install Devel and the Devel submodule Kint. Then you can `ksm($result)` to print out vars. (Don't click the plus icon in the output, click only titles.)
Comment: Check other `hook_views_pre_render()` sample snippets on https://api.drupal.org/api/drupal/core!modules!views!views.api.php/function/hook_views_pre_render/8.2.x
Comment: Thanks guys for your help. Prior to put this question I have tried to find a solution. I have read drupal 8 views api, and some snippets examples, but all of them (I have found) change title, image style or similar. Neither of this examples are for change the values. On the other hand, I don't think this is a duplicate of the question that Neograph734 are indicating. I have read this question prior to post my question and as I understood it is for change the title.
Comment: @briast, your question is how to alter `$view`, which is exactly what the other question is about. Yes, the demonstrated alteration is indeed editing the title, but there is much more to edit. Please update your question to include what you want to edit in your results. I have to admin that I initially did not see you were already using the same hook.
Comment: I have updated my question to be more precise. I hope it was clear enough. Thanks for your help.
Answer: I was able to alter results just setting the view result property within hook_views_pre_render. My code looks something like:
$results = $view->result;
$filteredResults = [];

foreach ($results as $result) {
  if ($result->_entity->field_somefield->value === 'somevalue') {
    $filteredResults[] = $result;
  }
}

$view->result = $filteredResults;
$view->total_rows = count($filteredResults);

Comment: This solution would not help to rewrite the result. This is just filtering out some of the results.
Answer: View hooks like hook_views_pre_render() should be placed in an execution.inc file within the module directory: mymodule.views_execusion.inc
The execution order of View hooks is as follows:

hook_views_pre_view
hook_views_pre_build
hook_views_post_build
hook_views_pre_execute
hook_views_post_execute
hook_views_pre_render
hook_views_post_render

Read what these hooks do here
The following is a good example for Drupal 8.x|9.x. Your goal is to create a new result set of entities and set it to $view->result. It is important to set the index property so the results will render properly.
Slightly altered from @rosemarystanley
/**
 * Implements hook_views_pre_render().
 */
function HOOK_views_pre_render(ViewExecutable $view) {

  $results = $view->result;
  $filteredResults = [];

  foreach ($results as $result) {
    if ($result->_entity->field_name->value === 'fieldValue') {
      $filteredResults[] = $result;
    }
  }

  // Important to set index values for view results rendering
  foreach ($filteredResults as $key => $row) {
    $row->index = $key;
  }

  $view->result = $filteredResults;
  $view->total_rows = count($filteredResults);
}

Comment: It's important to set index values when using views bulk operations.
Answer: It depends on what your result stores. It can be like entity with relation or just field:
1) $result->_entity->set('field_Name', 'xxxxxxxxxxx');
2) $value->node__field_Name = 'xxxxxxxxxxx';
Comment: What about global field ?

Alter views results in a hook


What variety of song can be played on a 22 white keys - keyboard?

Question: I don't know much about pianos but I want to learn to play a few songs. I have an old keyboard with 22 white keys which I will label... Can I play most normal songs on this keyboard or does it become limited with only 22 keys?
Comment: Does this answer your question? [Using keyboard/MIDI controller to learn piano](https://music.stackexchange.com/questions/6302/using-keyboard-midi-controller-to-learn-piano)
Comment: Your keyboard has **only** white keys? If tere are black ones as well, there's really no need to label them - there's a distinct pattern - for example, there's always a D note between the two black keys - meaning there's C to its left and E to its right. Only 4 othrers to find!
Comment: Example(s) of what you think of as a "normal song" would help. We can probably give you more specific answers if we know the kind of music you might like to play.
Answer: A lot of melodies have a range of around 1 and 1/2 or 2 octaves. Your keyboard seems to have three octaves. You should be able to play many songs, but some things to consider...

You might need to transpose some songs to get them to better fit the limited range of your keyboard.
If a part of the melody goes too high, you can try dropping it down one octave.
Make changes to the accompaniment to keep it in your keyboard range. If you have to choose between changing the melody or accompaniment, try changing the accompaniment first.
Answer: By 22 white keys I'm assuming you mean a 3 octave keyboard. That means aside from the white keys you have 3 alternating sets of 2 and 3 black keys for a total of 37 notes. Correct me if I'm wrong.
This type of keyboard is fine for playing melodies with simple chords or chords and bass and you can have fun playing it if you accept its  main limitation, which is range. You can only play so low or so high on this keyboard before running out of room because of the relatively low number of notes it has. Most basic keyboards have 61 keys or 5 octaves and a piano or full sized keyboard has 88 keys. This gives you the ability to play more comfortably and not run out of notes as you go up or down.
By all means try it out, you may find that it's enough for you to get started. Down the road you can invest in a better keyboard with more notes and nice sounds for anywhere between $100 and $200.
Answer: You can play the tune of any song, and add some sort of accompaniment.   You'll be limited when trying to play sheet music literally though.
Please don't label the keys.


Troubles with adding video provider to Video Embed Field module

Question: I have installed Video Embed Field module, youtube links works good. Next I have installed Video Embed Wistia, and can't set valid Wistia's links. The error is

Could not find a video provider to handle the given URL.

Video embed field and Video Embed Wistia modules are on in admin/modules
What I have missed? Why it doesn't work?
Comment: I have the same problem with Dailymotion. Do you find a solution @Crantisz ?
Comment: @Pauleau i've found. I've posted it as answer
Comment: Thanks you, I found it too after few minutes, I wasn't in the good fields because of ECK embeded ones.
Answer: I've found solution, it's simple.
You need to go in the field settings of this field and find a checkboxes   with all video providers. Mark Wistia or any new provider here and it will work.
Comment: Hi there, I still have the same issue, even if providers are marked in the Field settings page. Any idea?


How to set DynamoDB read consistency in CloudFormation

Question: Is there a way to set DynamoDB read consistency (eventually vs strongly) mode in CloudFormation? I couldn't find how to do it in CF doc, but couldn't find a clear saying that CF does NOT support it either.
Thanks!
Answer: This is not part of CloudFormation nor is it part of table schema definition.
Read Consistency is a flag you add when querying the data;
Global Secondary Indexes do not support strong consistent reads at all;
Comment: oh got it. i thought there is a table property that makes all reads strongly consistent. thanks!


Receiving SSLHandshakeException: handshake_failure despite my client ignoring all certs

Question: I have a Java program that connects to a webserver using SSL/TLS, and sends various HTTP requests over that connection. The server is localhost and is using a self-signed cert, but my code is using custom TrustManagers, and ignores invalid certificates. It has worked perfectly until now.
The only difference on the server is that it used to run jboss 6 and is now running jboss 7. I'm not sure if this is a configuration issue, or whether there is a problem with my code, but I get the same errors if I try to connect using other Java-based programs like WebScarab or ZAP.
In any case, is there anything I can do to my code to get around this problem? Here is the error in full:
Received fatal alert: handshake_failure
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
        at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
        at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAlert(Unknown Source)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
        at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source)

Here are the debug messages before the failure:
main, WRITE: TLSv1 Handshake, length = 75
main, WRITE: SSLv2 client hello message, length = 101
main, READ: TLSv1 Alert, length = 2
main, RECV TLSv1 ALERT: fatal, handshake_failure

Answer: So I found the problem. There might be a bug in Java, but the client seems to initiate a TLSv1  Handshake, but then sends an SSLv2 client hello message, at which point the server rejects the connection.
This happens even if you create your SSLContext with an instance of TLS:
SSLContext sslContext = SSLContext.getInstance("TLS");

The solution is to set a system property before any connection attempts are made:
System.setProperty("https.protocols", "TLSv1");

There are probably other solutions to it, but this one worked for me.
Comment: It's not a bug, it's by design (the SSLv2 is for backward comp.). See [JSSE Ref/SSLContext](http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#SSLContext): "*For example, getInstance("SSLv3") may return a instance which implements "SSLv3" and "TLSv1"* [...] You can control which protocols are actually enabled for an SSL connection by using the method setEnabledProtocols(String[] protocols)". In your case, `https.protocols` takes care of `setEnabledProtocols` for `HttpsURLConnection`.
Comment: @Bruno Yeah, I saw that earlier whilst searching Google. Is this a bug in Java? I can't see how it could/should be default behaviour when I've specified the SSLContext as TLS.
Comment: Right, but that doesn't explain why it tries to use SSLv2 client hello messages when I've asked it to use TLS. The server only supported TLSv1 (specifically), and from the debug messages, it looks like Java initiated a TLSv1 handshake, before switching back to SSL (I've updated the original post with the debug messages).
Comment: A similar bug haunted me for days. Rsaesha's solution worked like a charm.
I tried to connect to a web service exposed via SimpleHttpServerJaxWsServiceExporter. Connecting to it from Java 7 worked without problems. Connecting to it from Java 6 caused the exception.
Answer: The info you provide is very little as well as your stack trace.
I'll take a guess here.
What I suspect is that in the new server the protocol is TLSv1 while your clients try to connect with SSLv3 (or less) and as a result the handshake fails.
Change you clients to use higher version of TLS
or
Make your webserver support SSLv3 as well. I know how to do this in Tomcat but not in JBoss.
If this doesn't work update the post with more info (and a full stack trace).
You should enable ssl debug info -Djavax.net.debug=ssl
Comment: The full stack trace just shows the connection method of my class, and whatever methods call that. It is the same method that has been working with previous versions of the server.

Anyway, here is the debug: http://pastebin.com/RJqcQwaP

What seems a bit odd to me is that even though I tell my program to use TLS, it seems to want to send out SSLv2 client hello messages.
Comment: For me also facing similar problem details here - https://serverfault.com/questions/954489/ssl-routinesssl3-read-bytestlsv1-alert-decrypt-error-on-mutual-authendication

How can we Identify this decrypt error ?
Answer: Was this ever resolved?
I had the exact same problem, essentially I was receiving a handshake exception immediately following the clientHello.  So The chain of events was

I would present my certificate to the server
Server would imediately respond with a handshake failure. (I would not even get a Server Hello back).

Eventually I found that the server was requiring a stronger encryption/decryption algorithm than what I Was supplying in the initial handshake phase (Ie. Client and Server could not agree on a mutual encryption algorithm to use for the ssl communication).
I need to install the Unlimited Java JCE (Java Cryptography Extension Policy).  There are export rules on using this, so if you ship your code overseas that may have implications..however this is what solved my problem.
This link explains how to install the updated policies
http://suhothayan.blogspot.com/2012/05/how-to-install-java-cryptography.html
This was also a great link that helped me understand exactly what was going on
https://support.f5.com/kb/en-us/solutions/public/15000/200/sol15292.html#id
This may or may not be the issue, but when the handshake fails immediately after the client Hello, it looks like the client and the server can not agree on something (in many cases its the encryption algorithms that they will mutually need to communicate).
Answer: You are seeing this error most probably because the keystore that your JBoss 6 had access to is not accessible to your JBoss 7 instance.
What I would recommend is the following.
Your self-signed server certificate must be imported into a truststore
keytool -import -alias gridserver -file server.crt -storepass $YOUR_PASSWORD_HERE -keystore server.keystore

Add the following properties to your run.conf
-Djavax.net.ssl.keyStoreType=pkcs12
-Djavax.net.ssl.trustStoreType=jks
-Djavax.net.ssl.keyStore=clientcertificate.p12
-Djavax.net.ssl.trustStore=server.keystore
-Djavax.net.debug=ssl # very verbose debug. Turn this off after everything looks good.
-Djavax.net.ssl.keyStorePassword=$YOUR_PASSWORD_HERE
-Djavax.net.ssl.trustStorePassword=$YOUR_PASSWORD_HERE

Comment: The server runs fine through a web browser like Chrome or Firefox, so the keystore on the server isn't the issue. Certification shouldn't be an issue either, since I am simply ignoring all certs.
Answer: The stack trace is from you client code and your client 'Received [a] fatal alert'. In other words, the SSL error happened in Jboss, not your client.
Your client side custom TrustManagers have therefore nothing to do with it. My wild guess is that your new Jboss 7 is configured to require client certificate and your client did not present any.
To debug your SSL connection, use openssl and try this:
openssl s_client -connect jboss.server.com:443
or is it is an SSLV3 server
openssl s_client -connect jboss.server.com:443 -ssl3
This should print a lot of interesting information.
Comment: My wild guess was just that, wild. Your server is fine. user384706 got you on the right track. This is more likely a protocol version mismatch. I see your server is TLSv1/SSLv3 and you seem to be sending SSLv2.
Answer: I think this is related to a Java 7 bug.  It is hard to be sure without more details.
Answer: For me solution was : System.setProperty("https.protocols", "TLSv1.1,TLSv1.2");


How is R-squared calculated in the "Blavaan" R package and is it appropriate to use/report in bayesian analysis?

Question: I am using the Blavaan R package to fit bayesian path analysis models. The output includes an R-squared value. It has come to my attention that there are problems with using R-squared for bayesian analysis i.e., it is a point estimate and can be greater than 1. I would like to know if Blavaan calculates it in a way that accounts for this.
Comment: Welcome to Cross Validated! I have heard of $R^2$ (or $R^2$-style) calculations yielding values below $0$ but never above $1$. What calculations have you seen that give values above $1?$
Comment: Thanks Dave, I am referring to this paper http://www.stat.columbia.edu/~gelman/research/unpublished/bayes_R2_v3.pdf where they show that the fitted variance can be higher than the total variance resulting in a value greater than 1.
Comment: Which particular equation(s)?
Comment: they are referring to the classical R^2 formula
Comment: Please point to a particular equation. I can think of three ways that are reasonably described as the classical formula, and I want to discuss the one you mean.
Comment: Sorry, I'm not seeing any way to write formulas here, but the link above shows it on the first page.
Answer: Sorry to be late to answer, but blavaan does nothing special here. It feeds the posterior means to lavaan, which does the calculation as if it is a frequentist model. The code for lavaan's calculation is on github.


How do you read without specifying the length of a byte slice beforehand, with the net.TCPConn in golang?

Question: I was trying to read some messages from a tcp connection with a redis client (a terminal just running redis-cli). However, the Read command for the net package requires me to give in a slice as an argument. Whenever I give a slice with no length, the connection crashes and the go program halts. I am not sure what length my byte messages need going to be before hand. So unless I specify some slice that is ridiculously large, this connection will always close, though this seems wasteful. I was wondering, is it possible to keep a connection without having to know the length of the message before hand? I would love a solution to my specific problem, but I feel that this question is more general. Why do I need to know the length before hand? Can't the library just give me a slice of the correct size?
Or what other solution do people suggest?
Comment: Can you post the error message?
Comment: Yes, the error is `EOF` followed by `exit status 1`.
Comment: I don't mind a slice backhand, but a slice beforehand should only be used in defence at full stretch, or occasionally in transition to the net.
Answer: Not knowing the message size is precisely the reason you must specify the Read size (this goes for any networking library, not just Go). TCP is a stream protocol. As far as the TCP protocol is concerned, the message continues until the connection is closed.
If you know you're going to read until EOF, use ioutil.ReadAll
Calling Read isn't guaranteed to get you everything you're expecting. It may return less, it may return more, depending on how much data you've received. Libraries that do IO typically read and write though a "buffer"; you would have your "read buffer", which is a pre-allocated slice of bytes (up to 32k is common), and you re-use that slice each time you want to read from the network. This is why IO functions return number of bytes, so you know how much of the buffer was filled by the last operation. If the buffer was filled, or you're still expecting more data, you just call Read again.
Comment: EOF isn't the end of the message, it's the connection being closed. TCP isn't just used to send single chunks of data, it's a stream that you can use to send and receive messages. The network connection doesn't even know what a "message" is, that's up to the application to determine how the data is framed.
Comment: @Pinocchio, that's why using the [`Type-Length-Value` scheme](http://en.wikipedia.org/wiki/Type-length-value) is quite often used to implement application-level protocols which use stream-based protocols like TCP.
Comment: Oh thanks! I just don't understand, why would someone **not** read until the end of the message? is EOF the same until the end of the message? Why isn't this detail just hidden/abstracted from the programmer? Why is this a thing in any network library?
Answer: A bit late but...

One of the questions was how to determine the message size. The answer given by JimB was that TCP is a streaming protocol, so there is no real end.
I believe this answer is incorrect. TCP divides up a bitstream into sequential packets. Each packet has an IP header and a TCP header See Wikipedia and here. The IP header of each packet contains a field for the length of that packet. You would have to do some math to subtract out the TCP header length to arrive at the actual data length.
In addition, the maximum length of a message can be specified in the TCP header.
Thus you can provide a buffer of sufficient length for your read operation. However, you have to read the packet header information first. You probably should not accept a TCP connection if the max message size is longer than you are willing to accept.
Normally the sender would terminate the connection with a fin packet (see 1) not an EOF character.
EOF in the read operation will most likely indicate that a package was not fully transmitted within the allotted time.


Soma de cada elemento de duas listas

Question: Existe algum código que soma os elementos de duas lista, por exemplo:
A=[1,2,3,4]

B=[2,4,5,6]

D=[3,6,8,10] # o elemento 3 e a soma dos elementos 1 e 2 da lista A e B

Comment: Possível duplicata de [Cálcula da soma da diferença entre 2 listas em Python](https://pt.stackoverflow.com/questions/183198/c%c3%a1lcula-da-soma-da-diferen%c3%a7a-entre-2-listas-em-python)
Comment: Outra: [Soma de elementos em listas](https://pt.stackoverflow.com/q/197452/5878)
Answer: A solução mais direta é utilizar a função nativa zip que permite juntar/mesclar dois iteráveis.
zip(iteravel1, iteravel2)

O resultado é um objeto que quando iterado funciona como uma lista de tuplas, em que cada tupla tem um elemento de cada um dos iteráveis. No exemplo acima cada tupla iria ter um elemento do iteravel1 e outro elemento do iteravel2.
No seu código, assumindo que tem a lista A e B criada, bastaria fazer assim:
D = []
for elemA, elemB in zip(A, B):
    D.append(elemA + elemB) #adicionar em D a soma dos elementos de cada lista

Como o zip devolve uma lista de tuplas, o for está a capturar cada um dos elementos da tupla em elemA e elemB
Se quiser tornar o código mais compacto e simples pode utilizar list comprehensions:
D = [elemA + elemB for elemA, elemB in zip(A, B)]

O zip suporta qualquer quantidade de iteráveis a juntar/mesclar. No seu exemplo poderia fazer a soma entre 3 listas com base no mesmo zip:
A = [1, 2, 3, 4]
B = [2, 4, 5, 6]
C = [3, 6, 7, 8]

D = [elemA + elemB + elemC for elemA, elemB, elemC in zip(A, B, C)]
print(D) # [6, 12, 15, 18]

É importante também dizer que consegue resolver sem utilizar zip mas não ficaria tão intuitivo e direto. Uma solução seria:
D = [B[posicao] + elemA for posicao, elemA in enumerate(A)]

Neste ultimo exemplo iterei sobre o A obtendo quer o elemento quer a posição através de enumerate e depois com base na posição fui buscar o elemento correspondente em B.
Veja todos estes exemplos no Ideone
Comment: Sugestão: sendo um pouco chato aos detalhes, mas o retorno de `zip` não é uma *lista*, mas um objeto *zip*, que é iterável, assim eu alteraria "devolve uma lista" para "devolve um objeto iterável" xD
Comment: @AndersonCarlosWoss Eu agradeço o comentário como sempre. No entanto fui literal à documentação *"This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables"*. Mas confirmando no interpretador, o retorno é de facto um objeto zip. Vou refrasear ligeiramente, tentando não perder o sentido original. Vê depois se achas que ficou bom..
Answer: A = [ 1, 2, 3, 4 ]
B = [ 2, 4, 5, 6 ]

D = [ (a + b) for a, b in zip(A, B) ]

print(D)

Answer: Você pode usar a função própria do Python, map().
Ela recebe dois valores, uma ação e um alvo: map(ação, alvo)
usando uma lambda simples você tem o resultado numa linha simples:
A = [1, 2, 3, 4]
B = [2, 4, 5, 6]

soma = list(map(lambda v1, v2: v1 + v2, A, B))

print(soma)

Obs. 1: Perceba que converti o resultado da função map numa lista.
Obs. 2: Perceba que dentro de map tem uma lambda e "os alvos" que neste caso são A e B, mas poderia ser uma lista com um conjunto de números.
Answer: Esse código funciona apenas se o array A tiver o mesmo tamanho ou ser menor que o array B:
 a=[1,2,3,4]
 b=[2,4,5,6]
 d=[]
 for x,y in enumerate(a): # Percorre o Array a enumerando suas posições
     d.append(y+b[x]) # somando elemento do array a com o elemento de mesma posição no array B
 print (d)

Answer: Uma outra opção seria isso aqui:
D = map(sum, zip(A, B))

basicamente uma forma reduzida das outras respostas.
Comment: Vale citar que, neste caso, `D` não será uma lista, mas sim um gerador.

Soma de cada elemento de duas listas


How is spike speed measured in volleyball?

Question: I've been eyeballing a volleyball match right now (apparently, it's world championships :), and have noticed that they show "spike speed" for spike replays. How is that speed measured? Is the ball stuffed with sensors or is there an array of hi-speed cameras to measure this? How much instrumentation is there for a high-profile match like this?
The main judge has three displays at his disposals, they look like three completely different things. At at least two times teams have contested a ruling, and a rudimentary 3D animation was shown on stream. It looked bit low-res, and definitely not like something the studio responsible for the transmission would do - so it must have originated from some kind of match-local instrumentation.
Answer: I'm not 100% sure if this particular system is used at the current World Championships, but Hawk-Eye has a system which works for volleyball as well, though it's mostly known for tennis. According to the Wikipedia page,

The system works via six (sometimes seven) high-performance cameras, normally positioned on the underside of the stadium roof, which track the ball from different angles. The video from the six cameras is then triangulated and combined to create a three-dimensional representation of the ball's trajectory.

So the ball has no sensors (which has the advantage that they can't influence the ball's trajectory); it's just that the system 'knows' how a ball looks like.
Though Hawk-Eye (and similar systems) are mostly used to check if a ball is in or not, and the 3D trajectory is definitely from such a system, it can measure ball speed as well. But for measuring the ball's speed, older systems, based on radar, exist.
Answer: In many gyms at bigger tournaments (World Championships, Championsleague)  radar guns (eg. Bushnell or Sports Ball Radar Gun) are used at the end of the court. They are used to measure serve speed and attacking speed. The problem with these numbers is, that they are only reliable if the serve or attack is directed at the speed gun as the measurements accuracy is dependent on the angle between the direction of the radar gun and the trajectory of the ball.
Anyway, although radar guns are not so accurate the Hawk Eye System is very rarly in use in Volleyball, the radar gun is much more wide spread.


Effect of linear transformation on the pdf

Question: I was hoping someone could explain the third line of the picture below. Why is it accurate to take the derivative of $F_X$ with respect to $x$ rather than with respect to $y$? I understand the chain rule but do not understand why the derivative of the second term is taken with respect to $x$. Am I missing something very basic?
Comment: Going from the third-to-last line to the last line is just the chain rule; the second-to-last line is showing an intermediate step of performing the chain rule.
Comment: How do we go from second to third line? Chain rule would suggest taking the derivative of the outer function, which is the Fx(y-b/a), wrt y and then multiplying by the derivative of the inner function (y-b)/a wrt y. Where did the derivative wrt x come from?
Comment: It's just someone else's notation for the process. If you can get from the second line to the fourth line already, the exact symbols they wrote in the third line aren't important.
Answer: You are essentially asking about the chain rule.
Example. Consider $X \sim \mathsf{Unif}(0,1),$ so that $f_X(x) = 1,$ for
$0 < x < 1$ is the density function of $X.$ In particular,
$P(0 < X < .1) = 0.1.$
Now, let $Y = g(X) = 3X + 10,$ so that $Y \sim \mathsf{Unif}(10, 13),$ so that $f_Y(y) = 1/3,$ for $10 < y < 13.$ Then
$$P(10 < Y < 10.3) = P(0 < X < .1) = 0.1.$$
In terms of $X,$ this probability is represented by a rectangle
with base $0.1$ and height $1.$ In terms of $Y,$ this probability
is represented by a rectangle with base $0.3$ and height $1/3.$
Derivation for example. Now for the calculus: Notice that $g^{-1}(x) = \left(\frac{y-10}{3}\right).$ So, for my specific example, an expanded version of the part you're asking about amounts to:
$$f_Y(y) = \frac{d}{dy}F_X(g^{-1}(x))
= \frac{d}{dy}(g^{-1}(x)) \times \frac{d}{dx}F_X(g^{-1}(x))\\
= \frac{d}{dy}\left(\frac{y-10}{3}\right) \times f_X\left(\frac{y-10}{3}\right)\\
= \frac{1}{3} \times 1 = \frac{1}{3},$$
where the second equality uses the chain rule, the third recognizes that the derivative of the CDF is the density function, and
the last uses $f_X(x) = 1,$ for $0 < x < 1.$
Simulation of example. A simulation illustrates the transformation:
<code>set.seed(2020)                 # for reproducibility
m = 10^6;  x = runif(m, 0, 1)  # sample 10^6 x-values
y = 3*x + 10                   # transform
par(mfrow=c(1,2))              # enable 2 panels per plot
  hist(x, prob=T, br = seq(0,1,by=.1), col="skyblue2",
       main="UNIF(0,1)")
    abline(v=c(0,.1), col="red", lwd=2)
  hist(y, prob=T, br = seq(10,13,.3), col="skyblue2",
       main="UNIF(10,13)")
    abline(v=c(10,10.3), col="red", lwd=2)
par(mfrow=c(1,1))              # return to single-panel plots
</code>


Find the derivative of a piecewise function.

Question:
I would just like to know if my proof here is valid. I know I left out some computational details, but I'm more concerned about the structure of the proof than those details.
Answer: It looks like you made a mistake in iii. That is not the left-hand limit you want to be looking at. The conclusion is correct, but the reasoning for the conclusion is not.
In ii. you can be a bit fancier and use the formula for a derivative of a polynomial. The point is that the derivative is a local calculation, so if your function is $x^2$ for $x>0$, then for the purpose of differentiation you can pretend your function is $x^2$ everywhere as long as you're differentiating at $x>0$.
Answer: For Case 3, where you are evaluating $\displaystyle\lim_{h\rightarrow 0^+}$, you should be clear that you are evaluating the limit of $\frac{(x+h)^2-x^2}{h}$ when $x=0$. As it is currently written, you are apparently evaluating both sides of the limit using the negative side of the function, which is invalid. You need to show that $\frac{d0}{dx}=\frac{dx^2}{dx}$ where $x=0$.
Besides that, your proof (outline) seems good.
Comment: Ok, so then I will have $\frac{x^2 + 2xh + h^2 - x^2}{h} = h$ when x = 0, so the limit as h goes to 0 from the right would be 0. Correct?


getOutputStream() has already been called for this response

Question: Criei duas páginas de erros iguais para dois sistemas que funcionam dentro do mesmo Tomcat.
Uma das páginas funcionam normalmente e a outra ocorre o erro a seguir.
Dentro do ambiente de desenvolvimento e homologação o erro não acontece. A versão do Tomcat de todos os ambientes é a mesma: 7.0.52
Grave: Exception Processing ErrorPage[exceptionType=java.lang.Exception, location=/template/dispatch-error.jsp] org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:585)at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:465)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
at org.apache.catalina.core.StandardHostValve.custom(StandardHostValve.java:460)
at org.apache.catalina.core.StandardHostValve.throwable(StandardHostValve.java:411)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:200)
at com.googlecode.psiprobe.Tomcat70AgentValve.invoke(Tomcat70AgentValve.java:38)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source) Caused by: java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:636)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at javax.servlet.ServletResponseWrapper.getWriter(ServletResponseWrapper.java:104)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:125)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:118)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:186)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:126)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:80)
at org.apache.jsp.template.dispatch_002derror_jsp._jspService(dispatch_002derror_jsp.java:236)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)

Página JSP :
<%@page contentType="text/html; charset=UTF-8" language="java" %> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%@ page isErrorPage="true" import="java.io.*"%>

    <c:choose>
        <c:when test="${pageContext.errorData.statusCode == '404' || pageContext.errorData.statusCode == '400' ||
                                    pageContext.errorData.statusCode == '0' }">

A Página ou arquivo solicitado não foi encontrado, clique no botão Voltar do seu navegador

        </c:when>
        <c:otherwise>

Ocorreu um erro. Clique no botão voltar do seu navegador

                <c:if test="${pageContext.errorData.statusCode == '500'}">

                                <%=exception.getMessage()%>
                                <%
                                    StringWriter stringWriter = new StringWriter();
                                    PrintWriter printWriter = new PrintWriter(stringWriter);
                                    exception.printStackTrace(printWriter);
                                    out.println(stringWriter);
                                    printWriter.close();
                                    stringWriter.close();
                                %>

                </c:if>
        </c:otherwise>
    </c:choose>

Answer: Parece que o problema está na quebra de linha entre as tags JSP. Ao interpretar o código JSP, alguns servidores de aplicação tentam escrever a quebra de linha entre as duas tags, o que resulta no erro. O link abaixo contém uma discussão antiga sobre o assunto.
http://www.guj.com.br/java/19660-javalangillegalstateexception-getoutputstream-has-already-been-called-for-this-response


dockerized jenkins failed building dockerfile work dir issue

Question: I have a jenkins container and a pipeline which consist of building docker images. I have mounted the necessary mounts (/var/run/docker.sock, /var/run) for jenkins to use docker commands. I also bind mounted a folder from my host to jenkins as its workspace directory (/var/jenkins_home/workspace).
Here is the Dockerfile which is part of my project:
<code>FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
 WORKDIR /app
 EXPOSE 80

 FROM microsoft/dotnet:2.1-sdk AS build
 WORKDIR /src
 RUN hostname && pwd
 COPY /storage/admin/jenkins/workspace/tremplinx_master-NAUVRHOZ5IJBBHVQ54PTEZJJL33WO7NMFUYS5BF3C5H3LBCDC3XA/SPA/SPA.csproj SPA/SPA.csproj
 RUN dotnet restore SPA/SPA.csproj
 COPY . .
 WORKDIR /src/SPA
 RUN dotnet build SPA.csproj -c Release -o /app
</code>
Running my pipeline fail with the following error:
<code>[tremplinx_master-NAUVRHOZ5IJBBHVQ54PTEZJJL33WO7NMFUYS5BF3C5H3LBCDC3XA] Running shell script

+ docker build -t spa:dev-0.0.1 SPA/

Sending build context to Docker daemon  4.536MB

Step 1/17 : FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base

 ---> 625b44243fbe

Step 2/17 : WORKDIR /app

 ---> Using cache

 ---> 8279155deb77

Step 3/17 : EXPOSE 80

 ---> Using cache

 ---> 574345928687

Step 4/17 : FROM microsoft/dotnet:2.1-sdk AS build

 ---> f6d6062f4612

Step 5/17 : WORKDIR /src

 ---> Using cache

 ---> b49549e644ac

Step 6/17 : COPY /storage/admin/jenkins/workspace/tremplinx_master-NAUVRHOZ5IJBBHVQ54PTEZJJL33WO7NMFUYS5BF3C5H3LBCDC3XA/SPA/SPA.csproj SPA/SPA.csproj

COPY failed: stat /var/lib/docker/tmp/docker-builder969545350/storage/admin/jenkins/workspace/tremplinx_master-NAUVRHOZ5IJBBHVQ54PTEZJJL33WO7NMFUYS5BF3C5H3LBCDC3XA/SPA/SPA.csproj: no such file or directory

script returned exit code 1
</code>
I can't figure out why docker is using /var/lib/docker/tmp/docker-builder969545350... folder whereas I have specified the full path containing my project.
I'm new to Jenkins so forgive me if I forgot to specify important information .
Thank you.
Answer: I've solved my issue. I had to change the way I call my Dockerfile and changing the WORKDIR inside.
Comment: Can you be more specific with the resolution? I have the same issue.
Comment: Files and directories from the COPY step should be within the build context. From the [Dockerfile reference/COPY section](https://docs.docker.com/engine/reference/builder/#copy) :

"The  path must be inside the context of the build; you cannot COPY ../something /something, because the first step of a docker build is to send the context directory (and subdirectories) to the docker daemon."


Getting undefined array type from Ajax call with JSON

Question: So I'm making a webapplication where you can play sudoku but the back-end is in Java. I made a servlet to communicate with my Jquery trough ajax.
I'm sending my generated array (the sudoku) to my webapp with this servlet trough Ajax. But when I do a typeof it seems to be undefined. Which means I cannot do any operations with the array
This is my Ajax call:
    $.ajax({
    url:"/2017_S2_Group_18/API/*",
    dataType:"json",
    success: function(data) {
        for(var i = 0; i<81;i++){
            originalSudoku[i] = $(data).attr("sudokuArray")[i];
            changedSudoku[i] = $(data).attr("sudokuArray")[i];
        }
    }
});

orginalSudoku is the array that cannot be modified and changedSudoku is the array that is going to be modified.
This is the output I get by browsing to the URL from my Ajax call.
{"sudokuArray":[7,6,8,1,9,2,3,4,5,1,9,2,4,3,5,6,7,8,4,3,5,7,6,8,9,1,2,8,7,9,2,1,3,4,5,6,2,1,3,5,4,6,7,8,9,5,4,6,8,7,9,1,2,3,9,8,1,3,2,4,5,6,7,3,2,4,6,5,7,8,9,1,6,5,7,9,8,1,2,3,4]}
How can I parse/change my type to either string or char or integer?
Comment: Which array are you trying to work with that seems undefined? originalSudoku, changedSudoku, or both? Also, what does the html for that look like? Cuz if 'data' is the json at the end of your question... I don't think $(data).attr() is what you want.
Answer: The issue is because data is an object, and you're trying to use jQuery's attr() method, intended for DOM elements, to access a property of it. That's not going to work.
Instead, you can access the properties of data as you would any normal object in Javascript. Try this:
success: function(data) {
  for (var i = 0; i < data.sudokuArray.length; i++) {
    originalSudoku[i] = data.sudokuArray[i];
    changedSudoku[i] = data.sudokuArray[i];
  }
}

Comment: Thank you very much! I've never worked with JSON before only with XML.


Inflating Map View repeatedly

Question: I am inflatng a mapview every time i call this function. And am also removing the view each time . but still i get an error saying the child already has a parent ,call removeview() first.
Any idea of how to solve this .
<code>      void getGeoView(Context context) {
        myRoot.removeAllViews();

       LayoutInflater inflater = (LayoutInflater) this
            .getSystemService(LAYOUT_INFLATER_SERVICE);
      View view = inflater.inflate(R.layout.geo_inflator, null);

       ((ViewGroup) view.findViewById(R.id.myMap)).removeAllViews();

      if (mapView == null) {
        mapView = new MapView(this, "0IEmqsWhwmo6Cu8hKdYn_VudUT8IpdKpXzMvQyw");
        ((ViewGroup) view.findViewById(R.id.myMap)).addView(mapView);
      } else {

        ((ViewGroup) view.findViewById(R.id.myMap)).addView(mapView);
      }
</code>
Answer: I'm not sure what you are doing but the simplest solution is to add this line:
<code>((ViewGroup) mapView.getParent()).removeView(mapView);
</code>
to wherever the error occurs. I guess that happens here:
<code>} else {
    ((ViewGroup) mapView.getParent()).removeView(mapView); // Add me
    ((ViewGroup) view.findViewById(R.id.myMap)).addView(mapView);
}
</code>

Inflating Map View repeatedly


Static Google Map in XML

Question: Hi I am having a problem when I check syntax of an xml document I am creating. I have been trying to put a link to a static Google Map with parameters. However when I check the syntax it gives me the following error:
"XML Parsing error at line 191: EntityRef: expecting ';'
Here is the line
<venue_location>http://maps.googleapis.com/maps/api/staticmap?center=90,0&zoom=16&size=512x512&maptype=hybrid&&markers=color:red%7Clabel:A%7C90,0&sensor=false</venue_location>

Any ideas?
Answer: & means "Start of entity" in XML. You can't just drop it in as data.
Represent it as & or use a CDATA block.
If you are creating this XML programatically, then use a proper XML library and don't mash strings together.

Static Google Map in XML


AS3 URLRequest Local File on multiple OS/Browsers

Question: Greatings!
I have yet another question concerning the loading of a .swf inside a existing one.
In my game. I have a introduction screen in which I load another .swf (which is a movie).
This all works fine and the URLRequest is this:
request = new URLRequest("Movie.swf");

As I said, this works fine. However when I copy my game.swf and movie.swf to a USB stick.
(I put them in the same directory to prevent other issues).
It doesn't seem to find the movie.swf.
Now I know that it has to do with the path given in the URLRequest and/or the publish settings. But I do not know how to make this so that it searches in the same directory
as the game.swf is in.
I hope you guys have an answer for this issue.
Thanks in advance,
Matti.
Comment: I'm sure it is due to the security error - do you have debug version of flash player? go to the [flash player settings manager](http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html) and add your USB location as safe/trusted location.
Comment: Thanks for your fast reply!
It didn't seem to work though.

Also I don't think this solves the issue I am having.
It's not only that I want it to play on my computer. But also on
other computers without installing/modifying things.
Comment: How are you loading the parent SWF when it is on the USB drive. If you are just double clicking the SWF than it will have a network security error. You need to post all code pertaining to the loading of the child swf.
Answer: Matti, I believe Lukasz's comment is correct about it being a security error.
You can avoid this security error by embedding Movie.swf instead of using a Loader.  If you do this, then at compile-time the Movie.swf needs to sit next to the Game.as file, and it will be included in the Game.swf (no need to deliver both files, just Game.swf).
The syntax is:
package
{
  import flash.display.Sprite;

  public class Game extends Sprite
  {

    [Embed(source="MyMovie.swf")]
      private var myMovieClass:Class;

    private var myMovie:DisplayObject;

    public function Game():void
    {
      myMovie = new myMovieClass();

      // Technically myMovie is now a Loader, and once
      // it's loaded, it'll have .content that's a
      // MovieClipLoaderAsset, and .content.getChildAt(0)
      // will be your MyMovie.swf main timeline.
    }
  }
}

Alternately, if you embed it as mimeType="application/octet-stream", you can get the bytes of the SWF and use it in your existing Loader's .loadBytes() method:
package
{
  import flash.display.Sprite;
  import flash.utils.ByteArray;

  public class Game extends Sprite
  {

    [Embed(source="MyMovie.swf", mimeType="application/octet-stream")]
      private var movieBytes:Class;

    private var myMovie:DisplayObject;

    public function Game():void
    {
      // Treat this loader the same as your current loader,
      // but don't call .load(url), call loadbytes():
      var l:Loader = new Loader();
      l.loadBytes(new movieBytes() as ByteArray);
    }
  }
}

Comment: This is not a fix to his issue.
Comment: Actually what Jeff Ward just posted is exactly what I needed.
I can't thank you enough for your help.
I tested it and it works.

Small thing though:
If other people find this helpful it may prevent them some problems. if you remove the ) in this line:

[Embed(source="MyMovie.swf"), mimeType="application/octet-stream")]
Comment: Indeed it's not a fix, it's a workaround of the security problem.  Glad it helped.  Fixed the copy/paste error, thanks!


How can I find all database schema changes introduced in a CiviCRM major version upgrade?

Question: I'm using CiviCRM with Drupal. When upgrading a site to a new CiviCRM major version, it's very useful to know all the database schema changes introduced in the new version, so that any custom code referring to database fields can be amended accordingly.
A case in point is civicrm_contribution_recur.next_sched_contribution -> next_sched_contribution_date in 4.3 -> 4.4 .
"You shouldn't be accessing database fields directly, you should be using the CiviCRM API", I hear someone say. Often that is the preferred approach but even so, API v3 is very closely tied to the database structure and the fields returned by an API call reflect the database field names, so the code would still need amending.
A really useful resource for CiviCRM would be an equivalent of Drupal's  Converting n.x modules to (n+1).x documentation.
Comment: Invoke `hook_schema()` for the modules you're interested in before the upgrade, save the result, then do the same thing afterwards. Diff the two, voila - that's what changed
Comment: Thanks Clive, however I believe CiviCRM does not use hook_schema. Being CRM-agnostic, it creates and updates its db schema itself.
That's a useful tip for other modules, however.
Comment: Ah, my bad I didn't realise that
Answer: One way to do it would be to pore through the CRM/Upgrade/ directory in the new version, looking for schema changes. However these are distributed across multiple files, depending on which alpha or beta version the change was introduced in. E.g. the next_sched_contribution_date change was introduced in this file:
civicrm/CRM/Upgrade/Incremental/sql/4.4.alpha1.mysql.tpl
Answer: An easier way of doing it from a pure structural perspective is to use a mysql schema diff tool, something like:
http://adamspiers.org/computing/mysqldiff/
However that might not give you all the changes, but i suspect will catch most changes. A lot better to do it in an automated way, IMO :)
Comment: The current version of mysqldiff (0.4.3) can't handle Civi dbs, it chokes on constraints - https://rt.cpan.org/Public/Bug/Display.html?id=48618 . I've had some success with mysqldbcompare http://dev.mysql.com/doc/mysql-utilities/1.5/en/mysqldbcompare.html however.
Answer: Another option would be to diff the xml schema between versions. The xml schema files are not shipped in the tar.gz releases, only in git, so it's not exactly the most user-friendly method, but it could be a good starting point.
You could also try:
git log -w -p tag1..tag2 xml/schema

For example:
git log -w -p 4.4.5..4.5.2 xml/schema

Not perfect, but semi-comprehensible.
Comment: The command syntax as given doesn't work, however this does:
"git log -w -p 4.3.0..4.4.0 xml/schema"
Thanks for pointing me in that direction. This approach results in pretty verbose output, e.g. including many commits that simply add comments, so it can be difficult to see the wood for the trees. The best approach I think would be to document and explain schema changes per major version but given that this doesn't seem to be done currently, your answer is very helpful, thank you.
Comment: Comparing 4.4.0 with 4.5.0 using this method produces 19061 lines of output - far too much to wade through and mostly not real schema changes, e.g. adding titles. So I opted for a mysql schema diff tool, mysqldbcompare, which produced 1400 lines. I have edited this down to a fairly compact summary and will happily document that somewhere if it's of interest.
Answer: I have now found a viable approach to identifying the changes, using  mysqldbcompare. I've added a couple of pages to the CiviCRM Wiki, under Developer Resources -> Reference Sheets -> Database Reference:
Database Schema Changes: CiviCRM 4.4 to 4.5
Database Schema Changes: CiviCRM 4.5 to 4.6
Note that there is now a CiviCRM Stack Exchange site, currently in beta. Should this question move there?


Input Cpf e telefone aceitar só numero

Question: Como posso fazer para que os input cpf e telefone do meu formulário aceitem apenas números, usando javascript, tentei colocar o type="number" mas eu achei muito ruim, e dependendo do navegador do usuário não funciona, quero uma resposta com javascript se possível.
<input type="text" id="frmCpf" name="frmCpf" maxlength="11" size="11" placeholder="Somente números"></input>

<input type="text" id="frmNumero" name="frmNumero" size="20" maxlength="9" placeholder="Somente números"></input>

Answer: Você pode usar o plugin JQuery InputMask. Com ele você consegue definir o formato dos dados de um input.
Para definir o formato do CPF, basta usar o seguinte código jQuery:
$("#frmCpf").inputmask({
  mask: "999.999.999-99"
});

Cada 9 indica que nessa posição só pode ter valores no intervalo [0, 9]. Se não quiser os . e o -, basta remover eles da máscara.
Outra forma de usar o InputMask é direto no html, com o atributo data-inputmask.
<input type="text" id="frmNumero" name="frmNumero" placeholder="Somente números" data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false"/>

Depois basta chamar $("#frmNumero").inputmask(); no JavaScript.
A propriedade repeat indica quantas vezes a máscara vai se repetir. No caso do input acima, podemos inserir valores no intervalo [0, 9] um máximo de 10 vezes. Já a propriedade greedy: false faz com que o plugin exiba a menor máscara que ele conseguir.
É importante que você dê uma lida na documentação se for criar novas máscaras.
Segue um exemplo executando:

$(function(){
  $("#frmCpf").inputmask({
    mask: "999.999.999-99"
  });

  $("#frmNumero").inputmask();
});

<input type="text" id="frmCpf" name="frmCpf" placeholder="Somente números"/>

<input type="text" id="frmNumero" name="frmNumero" placeholder="Somente números" data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false"/>

Se não estiver usando JQuery:

Você pode usar o VanillaMasker.
Para definir o formato do CPF, basta usar maskPattern, como no código a seguir:
VMasker(document.getElementById("frmCpf")).maskPattern("999.999.999-99");

A máscara funciona de forma semelhante ao que falei para o InputMask.
Para indicar que um campo é apenas numérico, basta usar o método maskNumber, como no código a seguir:
VMasker(document.getElementById("frmNumero")).maskNumber();

Segue um exemplo usando o VanillaMasker:

VMasker(document.getElementById("frmCpf")).maskPattern("999.999.999-99");
VMasker(document.getElementById("frmNumero")).maskNumber();

<input type="text" id="frmCpf" name="frmCpf" placeholder="Somente números"/>

<input type="text" id="frmNumero" name="frmNumero" placeholder="Somente números" data-inputmask="'mask': '9', 'repeat': 10, 'greedy' : false"/>
Comment: Será que ele está utilizando jQuery?
Comment: Obrigado por lembrar. Adicionei uma biblioteca sem `jQuery`.
Answer: Você pode usar esta função javascript abaixo:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

Resposta retirada deste link

Input Cpf e telefone aceitar só numero


asp.net vb.net app_code alternative

Question: I'm trying to find an alternative to the app_code folder to import my classes in my aspx files...
Should be fairly easy with Microsoft Visual Studio... but I don't have it, can not have it, will not have it even if I beg my boss...
We have 2 Servers 1 for the development and the other for the public, I don't really know why since I'm new at the place, but on the development server, each developer has a folder to its name.
Now, if I try to place my classes in app_code and I have a error, well I block all of the others programmers until it is fixed.
I'm taking any suggestions to how to proceed to import classes into an .aspx file that it is not a class, but mainly html with some aspx vb.net in <% %>...
Anyway, not the best working environment, but any help would be greatly appreciated.
Answer: If you want to reference a class in all your aspx files specify the namespace in web.config.
<add namespace="YourNamespace"/>

Look at a similar question.
EDIT:
To import a namespace in a singla aspx page do this:
<%@ Import Namespace="YourNamespace" %>

Related question
Comment: Not necessarily in all class, but trying to import any namepsace I define are considered empty, even if their is multiple public class defined in it...
Comment: Please look at my edit above mentioning how to add a namespace in a single aspx file.
Comment: Thank you for your help really, but like I said before, when I try to add namespaces they are not found... So unless their is random rules to namespace naming that I don't know, this solution doesn't seem viable for me...

asp.net vb.net app_code alternative