Training nnet and avNNet models with caret when the output has negatives

Question: My question is about the typical feed-forward single-hidden-layer backprop neural network, as implemented in package nnet, and trained with 'train()' in package caret. This is related to this question [Multi-layer neural network wont predict negative values ] but in the context of the nnet and caret packages in R.
I demonstrate the problem with a simple regression example where Y = sin(X) + small error:
(a) raw Y ~ raw X: predicted outputs are uniformly zero where raw Y < 0.
(b) scaled Y (to 0-1) ~ raw X: solution looks great; see code below.
library(nnet)
X <- t(t(runif(200, -pi, pi)))
Y <- t(t(sin(X)))           # Y ~ sin(X)
Y <- Y + rnorm(200, 0, .05) # Add a little noise
Y_01 <- (Y - min(Y))/diff(range(Y)) # Y linearly transformed to have range 0-1.
plot(X,Y)
plot(X, Y_01)
dat <- data.frame(cbind(X, Y, Y_01)); names(dat) <- c("X", "Y", "Y_01")
head(dat)
plot(dat)

nnfit1 <- nnet(formula = Y ~ X, data = dat, maxit = 2000, size = 8, decay = 1e-4)
nnpred1 <- predict(nnfit1, dat)
plot(X, nnpred1)

nnfit2 <- nnet(formula = Y_01 ~ X, data = dat, maxit = 2000, size = 8, decay = 1e-4)
nnpred2 <- predict(nnfit2, dat)
plot(X, nnpred2)

When using train() in caret, there is a preProcess option but it only scales the inputs. train(..., method = "nnet", ...) appears to be using the raw Y values; see code below.
library(caret)
ctrl <- trainControl(method = "cv", number = 10)
nnet_grid <- expand.grid(.decay = 10^seq(-4, -1, 1), .size = c(8))
nnfit3 <- train(Y ~ X, dat, method = "nnet", maxit = 2000,
        trControl = ctrl, tuneGrid = nnet_grid, preProcess = "range")
nnfit3
nnpred3 <- predict(nnfit3, dat)
plot(X, nnpred3)

Of course, I could linearly transform the Y variable(s) to have a positive range, but then my predictions will be on the wrong scale. Though this is only a minor headache, I'm wondering if there is a better (built-in?) solution for training nnet or avNNet models with caret when the output has negative values.
Thanks for any suggestions or insight you can provide!
Answer: Is the question related to the scale in which nnet predicts? Since Y is roughly between -1 and 1 you should also use linout = FALSE in your nnet and train calls.
Comment: linout was the key, though the default is FALSE so it is actually linout = TRUE that solves the problem. Thanks.
Answer: The pre-process options apply to the X variables, NOT the Y variable. There's currently no way to preProcess the Y variable (that I know of).  Perhaps there needs to be? Please post an issue to the tracker!


MaxListenersExceedWarning: Possible EventEmitter memory leak detected

Question: A similar issue to the following however I cannot seem to code my way out of it.
Link to similar issue
Possible EventEmitter memory leak detected without EventEmiter
Please find code underneath:
I suspect that the error handling in the 'input onchange' of CreateThread component are causing the issues but at this point I am really not sure about anything anymore. That being said it could be that a connect button in the header could be the culprit being that the console hints at the 'accountChanged Listeners' however I do not recall adding anything unusual. (Adding image for clarity)

Could anyone please shine their light on this issue?
I am already hugely appreciative!
CreateThread.js component
import { abi, contractAddresses } from "../constants";
import { useMoralis } from "react-moralis";
import { useEffect, useState } from "react";

export default function startThread() {
  const { chainId: chainIdHex, isWeb3Enabled } = useMoralis();
  const chainId = parseInt(chainIdHex);
  const threadAddress =
    chainIdHex in contractAddresses ? contractAddresses[chainId][0] : null;
  const [threadtitle, setthreadtitle] = useState("");
  const [threadpost, setthreadpost] = useState("");

  const { runContractFunction: createThread } = useWeb3Contract({
    abi: abi,
    contractAddress: threadAddress,
    functionName: "createThread",
    params: { _threadTitle: threadtitle, _threadPost: threadpost }, //these parameters should come from the input boxes (document.getElementById("threadtitle").value, etc.)
    msgValue: {},
  });

  async function Update() {
    const response = await createThread();
    console.log(response);
  }

 useEffect(() => {
    if (isWeb3Enabled) {
    }
  }, []);

  return (

Threadtitle

        <input
          className=" w-11/12"
          id="threadtitle"
          onChange={(e) => setthreadtitle(e.target.value)}
        ></input>

Threadpost

        <input
          className=" w-11/12 h-24"
          id="threadpost"
          onChange={(e) => setthreadpost(e.target.value)}
        ></input>

          <button
            className="bg-blue-500 hover:bg-blue-400 text-white font-bold py-2 px-4 border-b-4 border-blue-700 hover:border-blue-500 rounded"
            onClick={Update}
          >
            Create Thread
          </button>

  );
}

Header.js
import { ConnectButton } from "web3uikit";

export default function Header() {
  return (

        deAgora - Forum for the people, by the people

        <ConnectButton moralisAuth={false}></ConnectButton>

  );
}

Answer: The issue has seemingly been solved by not constantly rerendering the component which includes the web3uikit connectbutton (which in the above case is the header). I get the sense that on every render the connectbutton adds a listener every time the connectbutton is rendered and does not remove that listener on rerender (someone more with more knowledge on the matter should confirm tho).
I have moved the header out of the routing scheme to always show and therefore it does not rerender on every action performed in the front end (like browsing through the navbar). This seems to have solved the issue.


Why this error:: There is no row at position 0.?

Question: DataSet dsQues = obj.getQues();
txtQues.Text = dsQues.Tables[0].Rows[0]["Ques"].ToString(); //error here

Comment: Well, you haven't posted `getFAQ()` which makes it hard to say...
Comment: You should update the text in your original question (http://stackoverflow.com/questions/4301149) rather than posting another one...
Comment: @Jon :: Have corrected the mistake in my code..theer's no getFAq..its getQues() only
Comment: @Graham:: I have changed my SP! :( besides no one wud answer there and I need help bad
Answer: I think, you are not setting the value of @QuesID parameter in your code. And in the database there is no row having QuesID as NULL.
Answer: becoz
dsFAQ.Tables[0].Rows is a empty collection , please check your SP is returning some rows or not

Answer: Or that there is no column "FAQs".
Answer: Please check that your obj.getFAQ() is returning values.
Answer: It means that you have an empty DataSet (or that you're referencing an empty table in the DataSet).
I'm guessing the root cause is that the Stored Procedure backing you calls is returning zero rows. You're not passing any parameters to the Procedure, so you could try running this query by hand and seeing how many rows come back:
SELECT * FROM Admin.Ques WHERE QuesID = NULL

Comment: but why ? Is my Sp wrong or what? what's wrong anyway? Could u plz check my earlier code and tell me if that Sp was correct ?? :/
Comment: @Serenity - I updated my answer...you're not passing any parameters to the stored procedure so the query in my answer is what is being executed. I'm guessing that is incorrect.
Answer: Maybe try to execute in debug mode with a break point at the problematic line and try to see what is in your DataSet.. Probably  IT is empty!
Comment: Well apparently its empty so the error. i am asking why is it empty? What am i doing wrong here ?
Comment: Try to execute your stored procedure in a SQLCommandPrompt and see what is the result -- Yes HE is not the correct word!! Sorry :-)


Shuffle content of two json files in Vue.js

Question: I have two json files, list1.json and list2.json and I managed to concat them, but I have two roles:
Resulting list should contain only 10 random items from list1.json, all the items from  list2.json, and then I should display them in random order on the page.
How can I do that?
Answer: You can use lodash for this task.
_.sampleSize(list1.json, 10) will give you ten random items,
then _.concat(_.sampleSize(list1.json, 10), list2.json) will give you the desired result.
After you have a list containing the desired items, you can randomize its order by using the _.shuffle function.
You can read a bit more here:
https://lodash.com/docs#sampleSize and https://lodash.com/docs#concat
Off course both these functions work on JavaScript Arrays and not files, you would have to read/require these files and parse them first.
Answer: Solution with plain javascript (but I suggest too going with underscore or lodash as Gilad Artzi says).
function array_random_idx(arr) {
    var idx = parseInt(Math.random() * arr.length);
    return idx;
}

function remove_random(arr) {
    var idx = array_random_idx(arr);
    return arr.splice(idx, 1)[0];
}

function array_shuffle(a) {
    var j, x, i;

    for (i = a.length; i; i -= 1) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}

var result1 = []
for (var i = 0; i < 10; i++) {
    var elem = remove_random(list1.json);
    result1.push(elem);
}

var result = result1.concat(list2.json);
array_shuffle(result);

console.log(result);


Quantile Regression Median place within bounds

Question: In quantile regression I understand that I am estimating prediction intervals with an upper and lower quantile and that the .5 is supposed to be the median. However I have encountered a situation where the .5 quantile is not directly between my .05 and .95 quantiles.
Is that suspect or should I always expect the .5 to be 'exactly' between two upper and lower quantiles that match (eg +/- .05)?
Comment: By *not directly between*, do you mean $\hat y_{0.50}\neq\frac{\hat y_{0.05}+\hat y_{0.95}}{2}$ where hats denote point predictions and subscripts denote quantiles?
Comment: Yes, your mathematical definition matches what I am trying to convey.
Comment: What do you think of my answer?
Answer: By not directly between, do you mean $\hat y_{0.50}\neq\frac{\hat y_{0.05}+\hat y_{0.95}}{2}$ (where hats denote point predictions or end points of a prediction interval and subscripts denote quantiles)? If so, this is generally not a problem. For a symmetric distribution, you will have $y_{0.50}=\frac{y_{0.05}+y_{0.95}}{2}$, but for an asymmetric distribution, this need not be the case. Unless you somehow restrict your quantile regression model to produce fitted or predicted quantiles that are symmetric around the median, you may very well get asymmetric point predictions. This is one of the benefits of quantile regression; it will fit both symmetric and asymmetric distributions seamlessly.


Computing the total Pontrjagin class of quaternionic projective space

Question: This is Problem 20-A in Milnor-Stasheff's book Characteristic Classes:
Let $\tau$ be the tangent bundle of $\mathbb{P}^m(H)$, where $H$ is the quaternion algebra. $\gamma$ is the tautological bundle over $\mathbb{P}^m(H)$. Use the isomorphism $$\tau\oplus\text{Hom}_H(\gamma,\gamma)\cong\text{Hom}_H(\gamma,H^{m+1})$$
to show that $$p(\tau)=\frac{(1+u)^{2m+2}}{1+4u}$$
$u=c_2(\gamma)$ is a generator of $H^4(\mathbb{P}^m(H))$.
I'm not sure what's wrong with my proof: Take Pontrjagin classes on both sides of the isomorphism. Since $p(\text{Hom}_H(\gamma,H))=(1+u)^2$, we have $p(\text{Hom}_H(\gamma,H^{m+1}))=(1+u)^{2m+2}$. Because $\text{Hom}_H(\gamma,\gamma)\cong\epsilon^4$ is trivial bundle, $p(\tau\oplus\text{Hom}_H(\gamma,\gamma))=p(\tau)$. Therefore, $p(\tau)=(1+u)^{2m+2}$.
Where does $1+4u$ come from ? I appreciate any hints or answers.
Comment: Why is $\text{Hom}(\gamma,\gamma)$ a trivial bundle?
Comment: I think that's because $\gamma$ is a quaternionic line bundle and any quaternionic linear map from a quaternionic line to itself is left multiplication by an element in $H$.
Comment: But to do the characteristic class computation, you have to work over $\Bbb C$, no? Note that you yourself wrote $\epsilon^4$, not $\epsilon^1$.
Comment: Yes. My idea is that $\text{Hom}(\gamma,\gamma)$ is trivial quaternionic line bundle, which is isomorphic to trivial rank 4 real bundle $\epsilon^4$. Since trivial bundle has total Pontrjagin class $1$, the total Pontrjagin class is equal to that of tangent bundle.
Comment: No, definitely not a rank 4 real bundle. It is a.rank 4 complex bundle. I suggest you compute $p_1(V^*\otimes V)$ for a complex rank 2 bundle $V$.
Comment: I'm still confused. It is Hom over $H$ not Hom over $\mathbb{C}$. Shouldn't this imply that $\text{Hom}_H(\gamma,\gamma)\cong H$?
Answer: I think the misconception present in the question is that for a quaternionic vector space $V$, the endomorphism space $\mathrm{Hom}_{\mathbb{H}}(V, V)$ is a quaternionic vector space, just as $\mathrm{Hom}_{K}(V, V)$ would be a $K$-vector space for any vector space $V$ over a field $K$. If this was true, then it would indeed be canonically isomorphic to $\mathbb{H}$, as it has a canonical element, the identity endomorphism.
However, this is not true, due to non-commutativity of the quaternions. Think about how you would define this vector space structure, and you will notice that you only get a vector space structure over the center of $\mathbb{H}$, which is $\mathbb{R}$.
The upshot is that $\mathrm{Hom}_{\mathbb{H}}(\gamma, \gamma)$ is not a rank $1$ quaternionic vector bundle, but a rank $4$ real vector bundle (which actually has a canonical section, given by the identity elements, but this does not really matter).
Let us calculate its first Pontrjagin class.
(1) Recall that $\gamma$ itself is a rank $4$ real vector bundle with three almost complex structures $I$, $J$ and $K$ satisfying the quaternion relations. In particular, it has an associated rank $2$ complex vector bundle $\gamma_{\mathbb{C}}$ using the complex structure $I$.
(2) There is a canonical isomorphism
$$\mathrm{Hom}_{\mathbb{H}}(\gamma, \gamma) \otimes_{\mathbb{R}} \mathbb{C} \cong \mathrm{Hom}_{\mathbb{C}}(\gamma_{\mathbb{C}}, \gamma_{\mathbb{C}})$$
given by sending $A \otimes (a + bi) \mapsto a\cdot A + b\cdot AI$. To see that this map is an isomorphism, we show that it is injective (from which the claim follows from dimension reasons): The general element of $\mathrm{Hom}_{\mathbb{H}}(\gamma, \gamma) \otimes_{\mathbb{R}} \mathbb{C}$ has the form $A \otimes 1 + B \otimes i$. Hence if this gets sent to zero under our map, then we would have $A = - BI$. But $A$ commutes with the left $\mathbb{H}$-action, while $BI$ does not, unless $B=0$. But if $B=0$, then also $A=0$.
(3) We can now calculate
$$p_1\big(\mathrm{Hom}_{\mathbb{H}}(\gamma, \gamma)\big)
= -c_2\big(\mathrm{Hom}_{\mathbb{H}}(\gamma, \gamma) \otimes_{\mathbb{R}}\mathbb{C}\big) = -c_2\big(\mathrm{Hom}_{\mathbb{C}}(\gamma_{\mathbb{C}}, \gamma_{\mathbb{C}})\big) = -c_2(\gamma_{\mathbb{C}} \otimes_{\mathbb{C}} \gamma_{\mathbb{C}}^*).$$
(4) To get a formula for the Chern class of the tensor product, we can use the Chern character. The first terms of the Chern character are
$$\mathrm{ch}(E) = \mathrm{rk}(E) + c_1(E) + \frac{1}{2}\big(c_1(E)^2 - c_2(E)\big) + \dots.$$
If now $E$ and $F$ are two vector bundles of rank two with $c_1(E) = c_1(F) = 0$, then the formula $\mathrm{ch}(E \otimes F) = \mathrm{ch}(E)\mathrm{ch}(F)$ yields
$$ 4 - \frac{1}{2} c_2(E \oplus F) + \dots = \left(2 - \frac{1}{2} c_2(E) + \dots\right)\left(2 - \frac{1}{2} c_2(F) + \dots\right) = 4 - c_2(E) - c_2(F) + \dots$$
Hence $c_2(E \oplus F) = 2c_2(E) + 2c_2(F)$.
(5) Finishing off the calculation, we get
$$ p_1\big(\mathrm{Hom}_{\mathbb{H}}(\gamma, \gamma)\big) = -c_2(\gamma_{\mathbb{C}} \otimes_{\mathbb{C}} \gamma_{\mathbb{C}}^*) = - 2c_2(\gamma_{\mathbb{C}}) - 2c_2(\gamma_{\mathbb{C}}^*) = -4 c_2(\gamma_{\mathbb{C}}) = - 4u,$$
hence
$$p\big(\mathrm{Hom}_{\mathbb{H}}(\gamma, \gamma)\big) = 1 - 4u.$$
What's bugging me, though, is the sign difference. Are there different conventions at play here?
Edit:
I get $$p\big(\mathrm{Hom}_{\mathbb{H}}(\gamma, \mathbb{H}) \big) = (1-u)^2,$$
so it seems to me that the generator that Milnor-Stasheff refer to is $u = - c_2(\gamma)$.
Comment: Thanks a lot! I figured out where I did wrong. I thought the right multiplications by $i,j,k$ would give three sections of that hom bundle but actually they don't because we define the projective space by quotienting out left multiplication.


What are the benefits of feature scaling?

Question: Imagine you have two different datasets each having a feature representing people's ages. One dataset is gathered from teenagers the other is from elderly people.
# Feature 1:
ages_1 = [15, 15, 16, 17, 17, 18, 19, 19]

# Feature 2:
ages_2 = [75, 75, 76, 77, 77, 78, 79, 79]

If we scale these two features, we'll get exactly the same vector, meaning that we'll lose the information that they represent two completely different age groups. Furthermore, unless we store the parameters of the transformation (min/max or mean/std), this information will be irretrievable.
Another consequence of feature scaling is that features lose their interpretability. For example an age of 0.87 (after scaling) would just mean that it is belongs to one of the oldest people in the dataset (could be 18 in the first case or 78 in the second - there is no way we can tell).
Given that we have a lot to lose by scaling the features, why is feature scaling so popular in Machine Learning?
Comment: I guess when you have multiple features and you want to compare them but they are on different units of measurement, you need to standardize to make them comparable. take e.g. penalized regression where you give the same weight to all regression coefficients. in this case you need scaled variables otherwise your penalty will have different effect based on the unit of measurement
Answer: Some Machine Learning algorithms require all features to be in the same range to function properly, or they'll tend to pay more attention to some features rather than the other. An example of such algorithms are distance-based algorithms.
For example say you have a dataset where two features are:
age = [33, 35, 55, 67, 77, 78, 80, 83, 85, 93]
height = [1.67, 1.72, 1.73, 1.76, 1.8, 1.81, 1.83, 1.85, 1.88, 1.91]

The difference from the tallest to the shortest person is just 0.24 units, while the difference from the oldest to the youngest is 60 units. This means that this algorithm will treat the ages as far more important than the heights.
By normalizing the features to the same distance, you are ensuring that the algorithm treats them with equal importance.
You can also read this relevant post, with a more detailed answer on why normalization is required for k-NN.


Are there any naming conventions for helper functions in modules?

Question: I'm writing a module and I need to create an auxiliary (helper) function, but I don't know which is the best name to my function.
Should I name my function like:
function _MODULE_my_function

or:
function MODULE_my_function()

I usually use _MODULE_my_function() but there is a standard for this?
There is not reference about this in the Drupal Coding Standards or in the Naming your modules, functions, and variables article.
Comment: I've never heard of `auxiliary functions` what are they? Doing a google search, I couldn't find anything concrete.
Comment: @NoSssweat for my a function that is not a hook implementation
Comment: Ah ok, hmmm, I've seen both versions, and looks like you're right, there is nothing explicit in the docs.
Comment: @NoSssweat the name auxiliary it's fine?
Comment: http://stackoverflow.com/a/663368/295112
Comment: @Kevin thx kevin, but that's for **private [methods](http://stackoverflow.com/questions/4841605/what-is-a-difference-between-a-method-and-a-function)** not functions
Comment: There are two answers in there pertaining to Drupal, specifically. Its largely to hide the function from the rest of the system, and to prevent accidental hooking.
Comment: `the name auxiliary it's fine?` @AdrianCidAlmaguer probably, I actually don't know what the Drupal lingo is for them. Based on Aram's answer seems you're right, for Drupal they are called Helper/Auxialiary functions.
Answer: How to name a function is described in Naming Conventions which says:

Functions should be named using lowercase, and words should be separated with an underscore. Functions should in addition have the grouping/module name as a prefix, to avoid name collisions between modules.

That is valid for hooks and other functions implemented from the module.
For functions that are not hooks, you could also prefix them with an underscore, right before the grouping/module name. If you do it, you are saying to the developers of other modules that the function is not supposed to be called from other modules, but it is private for the module defining it.
This is a practice followed from PHP which is also followed from Drupal. For example, theme() had been renamed _theme(), before being removed, to make clear it was a private functions modules should not call. It's described in theme() renamed to _theme() and should not be called directly.

The direct callability of theme() was removed in favor of building render arrays consistently. It has been renamed to _theme() and is for internal use only. Build render arrays instead of using _theme() in your code for the following reasons.
Calling the _theme() function directly raises several issues:

It circumvents caching.
It circumvents defaults of types defined in hook_element_info(), including attached assets
It circumvents the pre_render and post_render stages.
It circumvents Javascript states information.
Comment: So, the best way is use an underscore?
Comment: The keyword being `could`, so it seems the conclusion is that it's up to you and there is no standard. `If you do it, you are saying to the developers of other modules that the function is not supposed to be called from other modules` is this somewhere in the docs? or where did you learn this from? Is this some sort of an unwritten rule? or is this PHP rule?
Comment: @AdrianCidAlmaguer There is no _best way_. If your functions are not supposed to be called from other modules, you add an underscore to their names.
Answer: I believe I have seen it on a few places that helper functions should be prefixed with an underscore. This is how you distinguish between them and other callbacks / main functions, plus you make it impossible to accidentally name something after a hook.
I've been using this system for years and is in my custom module boilerplate as well.
Hope this helps.
Comment: thanks Aram I will wait for other answer, for the moment I take your advice


Chord and diameter in circle

Question: Question:

In circle with radious $R$ we have diameter $AB$ and chord $CD$. The chord intersects $AB$ in point $M$ such that $\angle CMB = 45^o$. Show that $CM^2 + DM^2 = 2R^2$.

My attempt:
I'm sure there is nice solution, but all I can get to are some awful calucations. I know that $CM \cdot DM = AM \cdot BM$, but I'm not sure it will be any help.
Thanks for hints/solutions in advance.
Comment: Hint: Perpendicular bisector of chord passes through centre
Answer: Hint: Perpendicular bisector of chord passes through centre
Let $CM = a, DM = b  $
$AM=x, BM = 2R -x$
$x(2R-x) = ab $
and $(\frac{(a-b)}{2})^2 + (\frac{(a-b)}{2})^2 = (R-x)^2$
(Pythagoras theorem in triangle $OPM$, $O$ is centre, $P$ is midpoint of chord $CD)$
From these two equations you will get $a^2 + b^2 = 2R^2$
Answer: Maybe an algebraic argument could also be of some use.
We first show that $CM^2 + MD^2$ equals a constant wherever the chord $CD$ is placed, and then easily find the constant by considering the comy case when $CD$ is a diameter.
In a cartesian system centered at the centre of the circumference, points $C$ and $D$ are given by the intersection of the circumference
$$ x^2 + y^2 = R^2$$ and the line $$ y = x -d$$ where $d = \vert AM \vert$
One gets the quadratic equation $$ x^2 + (x-d)^2 = R^2$$ From here one can conclude immediately that $x_1^2 + x_2^2 = constant$: of course one could also perform a direct calculation check, by finding the roots $$x_{1,2} = \frac{2d \pm \sqrt{4d^2 - 8(d^2 - R^2)}}{4} $$
and verifying that $$x_1^2 + x_2^2$$ yield and expression where  all the terms containing $d$ cancel out.
$x_1^2 + x_2^2 = constant$ and $y_1$ and $y_2$ are determined by triangles similitude, even without calcualting the latter it is possible to conclude $$ CM^2 + DM^2 = constant_1$$  and we can find the value of the constant by convenienty looking at the case $M=O$, i.e. when the cord $CD$ is a diameter too.
It follows then trivially $$CM^2 + DM^2 = 2R^2 $$

Chord and diameter in circle


returning #disabled in ajax callback

Question: This is taken from the examples module(http://drupal.org/project/examples). More specifically in the 'Generate textfields' ajax section. The form attempts to demonstrate an ajax call by presenting 2 checkboxes and generating a textfield based on which checkbox was clicked.
This is the ajax callback. We have a textfield with key 'first_name'.
function ajax_example_autotextfields_callback($form, $form_state) {
  $a = $form['first_name'];
  $a['first_name']['#value'] = 'foobar';
  $a['first_name']['#disabled'] = TRUE;
 return $a;
}

The form rendered has value textfield with value 'foobar' as expected, but the textfield is not disabled? How come?
Answer: You can accomplish that using ajax_command_invoke.
Here is an example using your own code:
function ajax_example_autotextfields_callback($form, $form_state) {
  // $a = $form['first_name'];
  // $a['first_name']['#value'] = 'foobar';
  // $a['first_name']['#disabled'] = TRUE;
  // return $a;

  return array(
    '#type' => 'ajax',
    '#commands' => array(
      // First we add the disable attribute into the html input tag.
      // which makes the the input field inaccessible.
      ajax_command_invoke('#WRAPPER_SELECTOR input', 'attr', array('disabled','disabled')),
      // Then we grey it out by adding the form-disabled CSS class.
      ajax_command_invoke('#WRAPPER_SELECTOR .form-item', 'addClass', array('form-disabled')),
    ),
  );
}

You can instead grey out using CSS attributes by calling ajax_command_css
Comment: Awesome one !! very helpful.
Answer: I found another solution (if you don't want to use ajax commands).
function ajax_example_autotextfields_callback($form, $form_state) {
  $a = $form['first_name'];
  $a['first_name']['#value'] = 'foobar';
  $a['first_name']['#attributes']['disabled'] = 'disabled';
 return $a;
}

Comment: This seems to be way simpler than my solution. Thanks for sharing.

returning #disabled in ajax callback


How to connect to FTP via SOCKS5 proxy with Ruby?

Question: I'm trying to connect to FTP via SOCKS5 proxy using ruby's library Net::FTP. Documentation says to set env variable SOCKS_SERVER in order to connect through proxy (http://ruby-doc.org/stdlib-2.0.0/libdoc/net/ftp/rdoc/Net/FTP.html#method-i-connect), but it seems like it does not work.
Code I'm running is this:
irb(main):054:0> ftp = Net::FTP.new
=> #<Net::FTP:0x007efd08c73768 @mon_owner=nil, @mon_count=0, @mon_mutex=#<Thread::Mutex:0x007efd08c73718>, @binary=true, @passive=true, @debug_mode=false, @resume=false, @sock=#<Net::FTP::NullSocket:0x007efd08c736f0>, @logged_in=false, @open_timeout=nil, @read_timeout=60>
irb(main):056:0> ENV['SOCKS_SERVER'] = 'host:port'
=> "host:port"
irb(main):055:0> ftp.connect('test.rebex.net')
=> nil
irb(main):057:0> ftp.login('demo', 'password')
=> true
irb(main):058:0> ftp.ls
=> ["10-27-15  03:46PM       <DIR>          pub", "04-08-14  03:09PM                  403 readme.txt"]

When I look to proxy logs I can not see any requests going through.
What I'm doing wrong or does anybody have an example how to achieve that?
Comment: Does the `SOCKS_SERVER` environment variable need to be set _before_ you call `ftp.connect()`?
Comment: From the Ruby [Net::FTP source code](https://github.com/ruby/ruby/blob/trunk/lib/net/ftp.rb#L335), there's a check to see if `SOCKSSocket` is supported, in addition to the `SOCKS_SERVER` env var check.  And [this StackOverflow post](http://stackoverflow.com/q/9923704/4072843) suggests that your Ruby _might_ not be built with SOCKS support.
Comment: What do you mean 'it seems like it does not work'? What error message are you getting? Can you include the code you're using, what you're expected it to do, and what it is doing, so that there's a better chance that someone can help you out?
Comment: Copy paste error.. @Castaglia thanks for pointing this out.
Answer: If your on Windows computer you'll need to use dress_socks gem and Monkeypath:
$socks_server = '127.0.0.1'
$socks_port   = '9090'
require 'dress_socks'

class Net::FTP
  def open_socket(host, port) # :nodoc:
    # puts "opening socket #{@host}:#{port}"
    return DressSocks::Socket.new(@host, port,
        socks_server: $socks_server, socks_port: $socks_port)
  end
end


Installed Revisioning Module, how do you make it default to create new revision?

Question: I just installed the Revisioning module, but all my existing nodes are set to: "Modify current revision, no moderation", but I would like it to be set as create new revision by default. I don't want my users to manually click this when they are editing a node.
How do I make it by default to create a new revision for existing nodes?
Creating new nodes is not an issue as its already set by default to create a new revision.
Answer: You can alter the node edit form following the Revisioning's implementation.
<code>/**
 * Implements hook_form_alter().
 */
function myModule_form_alter(&$form, &$form_state, $form_id) {
  if (!empty($form['#node_edit_form'])) {
    if (isset($form['revision_information']['revision_operation'])) {
      $form['revision_information']['revision_operation']['#default_value'] = REVISIONING_NEW_REVISION_NO_MODERATION;
    }
  }
}

/**
 * Implements HOOK_module_implements_alter().
 *
 * Ensure our hook runs after revisioning_form_alter().
 */
function myModule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    $group = $implementations['myModule'];
    unset($implementations['myModule']);
    $implementations['myModule'] = $group;
  }
}
</code>


Como Alterar H1 usando Javascript?

Question: Eu tenho uma galeria de produtos e o lado existe alguns botões que são as categorias desses produtos (botões: gabinete, monitores, mouse, cadeiras, etc), quando eu clicar nessa categoria, um toggle ativa somente os produtos daquela categoria específica.
No entanto, eu quero que acima desses produtos contenha um título que inicialmente será assim: "Produtos" (esse é o padrão), mas quando eu clicar na categoria Gabinete, por exemplo, esse título será alterado para "Gabinetes". Deu pra entender?
Pois bem, eu quero que isso aconteça com todos os outros botões sempre alterando o título em tempo de execução.
Eu até tentei criar uma function ao clicar usando GetElementById junto com uma IF ELSE, mas ele aplica a primeira validação apenas.
Alguém que já fez algo parecido poderia me ajudar?
Importante: Eu estou pegando os botões do banco de dados, simplesmente eu fiz uma instrução WHILE que vai repetir os botões de acordo com a quantidade de categorias cadastradas no banco de dados, então não tem assim logo de cara, como adicionar uma função diferente para cada botão. Tem como, mas não tão facilmente.
Comment: Coloque na pergunta o código que você fez para olharmos o que pode estar errado.
Comment: Você está usando jquery?
Comment: Bem-vindo, importante ler esse post para obter sucesso nas suas próximas perguntas  https://pt.stackoverflow.com/help/mcve e marcar uma resposta como aceita https://i.stack.imgur.com/evLUR.png e porque marcar como aceita https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Comment: Olá @MarceloUchimura! Não estou usando o jQuery.
Comment: @AndersonCarlosWoss Então, como é um problema de um site de um cliente, meu gestor não permitiu divulgar parte do código, mas os amigos ali abaixo, responderam de acordo com o descritivo que dei e deu certo, mas em futuras perguntas, vou tentar postar o código ^^ Grato!!
Answer: Veja se isto é o que você precisa:

Produtos

Nonononononono nonono nonono.

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

<select id="s" onchange="esse_mudou(this.value)">
  <option>Produtos</option>
  <option>Gabinetes</option>
  <option>Sabonete líquido</option>
  <option>Ração para cágados</option>
  <option>Buzina de calhambeque</option>
</select>

<button onclick="botao_clicado(this)">Produtos</button>
<button onclick="botao_clicado(this)">Gabinetes</button>
<button onclick="botao_clicado(this)">Sabonete líquido</button>
<button onclick="botao_clicado(this)">Ração para cágados</button>
<button onclick="botao_clicado(this)">Buzina de calhambeque</button>

Comment: Então mano, eu usei seu código e deu supercerto também aqui no meu problema, rsrs.. vou usar o código do Léo ali em cima mas obrigado por tirar um tempo pra me ajudar. :D
Comment: vlw flw vlw flw
Answer: Uma alternativa usando Jquery

$(".btn").click(function(){
    var name = $(this).text();
    $("#meuh1").html(name);
});

Produtos

<button class=btn>Gabinetes</button>

<button class=btn>Processadores</button>

<button class=btn>Discos Rígidos</button>

<button class=btn>Memórias RAM e ROM</button>

text()- retorna o texto do elemento
$(this)

$() é a função construtora do jQuery.
this é uma referência ao elemento DOM invocado.
Então em $(this) você está passando this para a função $() como parâmetro, no caso em questão o texto do elemento text()

Mudando o H1 e apresentando o texto correspondente

$(".btn").click(function(){
    $('div[id^="div_"]').hide();
    var name = $(this).text();
    $("#meuh1").html(name);
    var id = $(this).attr('id');
    $("#div_"+id).show();
});

Produtos

<button id="bt1" class=btn>Gabinetes</button>

<button id="bt2" class=btn>Processadores</button>

<button id="bt3" class=btn>Discos Rígidos</button>

<button id="bt4" class=btn>Memórias RAM e ROM</button>

Gabinetes de várias marcas e modelos

Processadores de última geração

Discos Rígidos de até 4MB, rs :)

Memórias RAM e ROM

Comment: BOOA! Era isso mesmo que eu precisava, claro que precisarei fazer alguns ajustes quanto ao meu código, até porque, eu não posso de forma simples, inserir uma propriedade "id" pra cada button pois eu faço um While (php) e passo apenas um Gabinetes, os outros são gerados automaticamente pelo laço. Mas isso é outra questão, eu dou um jeito. O jQuery reduziu significativamente o código que eu já tinha pra tentar solucionar o problema, ia ser um pouco extenso. VLWWW
Comment: @LougansdeMatos, uai, só colocar um contador no laço e concatenar com o valor do id
Comment: Uhumm :D ^^ vlw man

Como Alterar H1 usando Javascript?


PHP Ratchet web socket send message workflow

Question: I'm developing a chat server by PHP Ratchet library and I have a doubt about sending message:
I have the two methods: onOpen(ConnectionInterface $conn) and onError(ConnectionInterface $conn, \Exception $e).
When a client connects to chat onOpen method is called and I would to send a response message, for this reason I do $conn->send($data).
if there is an error onError is called, but if there isn't error How do I know if everything has been successful since the flow continues anyway? (I do not have a success method).
I ask you the following question because I have to manage the following situation:
when I send the message to a client, if the "send" method goes wrong I have to save on a database the message that I could not send and try to postpone it later, while if the sending was successful I do not have to save anything. My problem is that if the "send" method goes wrong, the "onError" method is called and I only have the instance about the "ConnectionInterface" but not the message I could not send, so at that point how could I? do to recover it?
I hope I was clear in explaining the problem
Answer: Maybe, some like this...
@example:
// ...

/**
 * {@inheritDoc}
 */
public function onOpen(ConnectionInterface $connection)
{
    // ...

    $package = [
        'data'  => $data = [] // for example
    ];

    $json = json_encode($package, JSON_FORCE_OBJECT);

    $connection->currentMessage = $json;
    $connection->send($json);

    // $connection->send(null); // uncomment if you wanna simulate error (call onError())
}

// ...

/**
 * {@inheritDoc}
 */
public function onError(ConnectionInterface $connection, \Exception $e)
{
    $connection->currentMessage; <-- your current message

    // ... save message, etc, ...whatever you want :)

    $connection->close();
}

Have Fun!


C interrupts on Cortex M3

Question: I'm currently trying to implement interrupts on the STM32L152. I'm not using the standard peripheral libraries because I find them very confusing and difficult to get my head around. I'm not too competent with C for micro controllers yet.
I currently do everything through registers. Is there a way to implement interrupts in C through registers? There doesn't seem to be any information that actually makes sense out there. I did find learning C to be very inaccessible in the first place tbh.
Thanks
Comment: User manual, manufacturer's example code.  Over, and over, again, until you get something working.
Comment: @GeorgeWaller You can't deal with interrupts without understanding the  underlying mechanism, which is the Interrupt controller, along with interrupt vectors. The same apply to everything else involved with hardware-software interaction. Start here for interrupts, but make sure go over other sections as well: http://users.ece.utexas.edu/~valvano/Volume1/E-Book/C12_Interrupts.htm
Comment: What exactly do you mean by "implement interrupts"? Do you mean "register a functor to the interrupt vector table"? Do you simply mean enabling/disabling them? Do you want to know how to use interrupts generated by I/O pins that can cause them? Do you just want to know how to bind to things like timers? We need more details of what exactly you're trying to do.
Comment: Okay sorry for the lack of clarification.

I want to wake the processor up from a low power state once a button is pressed. I don't know where to start. How do I do this? I completely understand the concepts of interrupts - just find the documentation on actually how to do it either assumes you already no how to do it or doesn't exist.
Comment: the problem you are encountering has less things to do with C language than CPU architecture. maybe you can start with CPU manual first.
Comment: I also don't understand how to use vector tables.
Comment: What @EugeneSh. says - if you don't understand the hardware, you're shagged.  It's also true that, with embedded, even if you understand the hardware you can still be shagged for some time, even with a debugger, scope etc.
Comment: Sounds like you need an external INT or GPIO interrupt.  There is a LOT to set up - PINSEL, interrupt-mask for GPIO port, mask of VIC, enable of VIC, load of vector table.  You HAVE to understand what is going on, or you will probably never get it to work.
Comment: Thanks. @MartinJames could you link to something suitable? I would appreciate a lot.
Comment: The STM32L152 data sheet says that an external line can be configured as a wake-up pin, without using interrupts, but I cannot find a code example. Section 10.2.3 in http://www.st.com/web/en/resource/technical/document/reference_manual/CD00240193.pdf
Comment: In case you are talking of the NVIC, you need to look for ARM documents (e.g. DUI0552), because the NVIC is part of the ARM Cortex-M3 core. Though for the core it is IMHO better to use CMSIS instead of the raw registers.
Answer: Of course you can implement interrupts by setting registers.

The registers-values tell the STM how to deal with interrupts, which interrupt is enabled, how the interrupt-controller has to work.
You'll need an Interrupt-vector-table. When an interrupt occurs a the program-counter will be set to an specific address of program-memory. There you should place a jump-command (assembler jmp) to your interrupt-service-routine.

You should read chapter 10 in this reference manual.
Hope this helps.

C interrupts on Cortex M3


How to Stop user going back from receipt page using browser back button?

Question: I am implementing a checkout in React and I am using react router. Now the issue is if my user places the order successfully a receipt page shows up. However, user is able to go back to checkout page again by pressing browser back button.
I want if the user presses browser back button while they are on the receipt page, they should either stay on receipt page or redirects to profile page.
Currently, I am handling it using some localstorage checks. I setitem in local storage on successful checkout and as soon as receipt page loads I delete it. On checkout page I am using this condition.
useEffect(() => {
  getMyInfo();
  if (localStorage.getItem("sessipn")) {
  } else {
    history.push({ pathname: `/receipt/${orderid}` });
  }
}, []);

So, when user presses back button it redirects them to receipt page because there's no session in localstorage.
I feel this implementation is poor. Any better answers.
Answer: Use history.replace instead of history.push: https://reactrouter.com/web/api/history


Multivariate multi-level analysis in nlme

Question: The question
I have a dataset which I think requires a multivariate multilevel analysis. I am unsure both of the appropriate model and of how to fit it with R. I have come up with a tentative model, but my understanding of the math is so superficial that I cannot tell whether my analysis is "right" or whether it includes blatant errors. I would appreciate any insight on the model design or the model specification in R.
The study design
The question is whether the architectural design of a clinic will influence the outcome of a pathology for permanent residents in this clinic.
We have collected data on 13 symptoms for 8 patients per clinic in 21 clinics.
There is a patient-level IV medication and a clinic-level IV architecture. All variables are continuous-ish.
The 13 symptoms are correlated +.20 on average, which I think indicates a multivariate multilevel analysis is appropriate.
The data
To run the multivariate analysis with nlme I have standardized my DVs, stacked these 13 DVs in a single column, and added a categorical dummy variable to flag which row corresponds to which symptom.
It looks like this:
 Clinic Patient Symptom    Score    Medication  Architecture
 1            1   EP1      0.12         1               3.2
 1            1   EP2      0.11         1               3.2
 1            1   EP3      0.13         1               3.2
 1            2   EP1      0.56         4               3.2
 1            2   EP2      0.67         4               3.2
 1            2   EP3      0.23         4               3.2
 2            3   EP1      0.22         3               5.1
 2            3   EP2      0.25         3               5.1
 2            3   EP3      0.14         3               5.1
 2            4   EP1      0.78         6               5.1
 2            4   EP2      0.89         6               5.1
 2            4   EP3      0.11         6               5.1

The model design

To run the analysis as multivariate, I use both symptom and symptom:architecture as IVs and I remove the intercept in both the fixed and random parts of the model. I do not include the main effect of architecture as an IV.
The effect of medication should be the same within all clinics, so there is no random effect for this variable.
I do not want to constrain equality between the effect of architecture on the different symptoms.
Due to the multivariate nature of the analysis, I expect the residuals to be correlated, with different correlations between the 13 different symptoms; therefore I specify the covariance structure of residuals as corSymm (non-zero but unstructured, if I get this correctly).
I also expect heteroscedasticity between the different symptoms (there should be more variance on certain symptoms), so I add the option weights as (~ 1|symptoms).

The end result
This is the model I come up with:
model1 = lme(fixed = Score ~ symptom + medication:symptom + architecture:symptom + medication:architecture:symptom - 1,
+ random = ~ symptom - 1 | patient/clinic,
+ correlation = corSymm,
+ weights=varIdent(form= ~ 1|symptoms)
+ method = "ML")

In order to test the effect of the architectural variables, I would then compare this model to the following constrained model, dropping all the terms related to architecture:
model2 = lme(fixed = Score ~ symptom + medication:symptom - 1,
+ random = ~ symptom - 1 | patient/clinic,
+ correlation = corSymm,
+ weights=varIdent(form= ~ 1|symptoms)
+ method = "ML")

I would then run this comparison with the command anova(model1, model2) and compare the log-likelihood of the two models.
Overall, do these model design and r specification look correct to you?
Thank you so much for your help!
Answer: I am curious why you have mentioned it as a multivariate analysis, when 'Score' appears to be the only outcome in your model.
To answer your question, there are no right or wrong models. The model fit can be compared using log-likelihood. Personally, I feel that adding one term at a time, and checking model fit is a better strategy than comparing model fit of a 'full model' with terms that you desire to test, with a comparatively basic model. The effect of variable of interest (such as symptoms) can be checked one at a time.
Lastly, collinear variables will still be problematic in your above formulation.
Answer: Woah, I wasn't actually expecting an answer to that one anymore. Thank you for taking the time to reflect on this.
Of course, four years later the project is long buried, but here are some things I've learned along the way in case someone else comes across these issues:

This was indeed a multivariate analysis since Score represented the score on various symptoms, as indexed by the column "symptom" in the example. The patients completed several different measures for several different symptoms, which were then collapsed in a single "score" column to allow for simultaneous testing of the different symptoms. In essence, the multilevel framework is used to yield a multivariate analysis based on three measurement levels: type of measure within patient within clinic. This solution is suggested by Goldstein (multilevel statistical models, chapter 4). I never came across a published example of someone doing it that way; even if correct, it is counter-intuitive enough that it might be difficult to publish.
I'm still not sure why some sources recommend removing the intercept in the multivariate multilevel case. I think it is due to the way some of them use dummy coding to recode categorical variables. With more current software, where categorical variables can be imported as is, I would probably leave the intercept in the model.
I definitely agree with your strategy of progressively building more complex models, at least for initial model specification and sanity checking. In psychology though you'll often want to run the actual test of the hypothesis by comparing the most complex model with the most-complex-without-the-IV-model, so as to return to a familiar Type-III sum-of-squares framework. This complex model would have been a bit dangerous in the present case, however, given that some of the control variables were heavily unbalanced in terms of sample size - which would probably have messed up the test of the main effects of the predictors of interest.
If I had to redo this analysis now, I would definitely make the model less complex by removing the unnecessary gizmos that are only there to improve model fit: heteroscedasticity and correlated residuals. While I think they are theoretically useful in that case, they tend to impede model convergence with such a small sample size, and with multiple measures (which was the case here with 13 symptoms) they make computation time prohibitive even on very powerful computers.

Thanks for your feedback!


Is $\{\tau+\sigma<k\}\in \mathcal{F}_k$?

Question:
Let me assume that $\tau, \sigma$ are optional times w.r.t $\Bbb{F}:=(\mathcal{F}_t)_{t\geq 0}$ which means that for all $k\geq 0$ we have $\{\tau<k\}\in \mathcal{F}_k$ and $\{\sigma<k\}\in \mathcal{F}_k$. I want to show that $\{\tau+\sigma<k\}\in \mathcal{F}_k$.

My idea was as following. Let me first remark that $\{\tau\wedge\sigma<k\}=\{\tau<k\}\cup \{\sigma<k\}\in \mathcal{F}_k$.
Now let me define $\tau':=(\tau \wedge k)+1_{\{\tau<k\}}$  and $\sigma':=(\sigma \wedge k)+1_{\{\sigma<k\}}$. Then clearly $\tau', \sigma'$ are both $\mathcal{F}_k$-measurable by definition and hence $\tau'+\sigma'$ is also $\mathcal{F}_k$-measurable. It would be nice if one could say that $\{\tau+\sigma<k\}=\{\tau'+\sigma'<k\}$. But I see no way to prove this. Can someone give me a hint?
Edit I know in that $\{\tau+\sigma\leq k\}\in \mathcal{F}_k$ maybe this can also be helpful.
Answer: You can write $$\{\sigma+\tau<k\}=\bigcup_{q_{1},q_{2},\in\Bbb{Q}\cap[0,\infty)\,:\,q_{1}+q_{2}<k}\bigg(\{\sigma<q_{1}\}\cap\{\tau<q_{2}\}\bigg)$$
Now $\{\sigma<q_{1}\}$ and $\{\tau<q_{2}\}$ are both in $\mathcal{F_{k}}$ as $q_{1},q_{2}<k$ for all $q_{1},q_{2}$ . And hence so is the countable union.
(Try to recall the trick used to show that sum of two Borel measurable functions is Borel measurable. That's precisely what I am using here)
Comment: Sorry could you remind me of the trick I don't know it anymore
Answer: One way to demonstrate the condition is as follows:
Let's assume that $\tau$ and $\sigma$ are optional times with respect to the filtration $\mathbb{F} := (\mathcal{F}_{t})_{t \geq 0}$, which means that for all $k \geq 0$, we have ${\tau < k} \in \mathcal{F}_k$ and ${\sigma < k} \in \mathcal{F}_k$. We want to show that $\{\tau + \sigma < k\} \in \mathcal{F}_k$.
Since $\tau$ and $\sigma$ are optional times, we have:
$$\{\tau + \sigma < k\} = \bigcup_{n=1}^\infty \left(\left\{\tau < \frac{k}{2n}\right\} \cap \left\{\sigma < \frac{k}{2n}\right\}\right)$$
Note that $\{\tau < \frac{k}{2n}\} \in \mathcal{F}_{\frac{k}{2n}}$ and $\{\sigma < \frac{k}{2n}\} \in \mathcal{F}_{\frac{k}{2n}}$. Since $\mathcal{F}$ is a filtration, we have $\{\tau < \frac{k}{2n}\} \in \mathcal{F}_k$ and $\{\sigma < \frac{k}{2n}\} \in \mathcal{F}_k$ for all $n$. Therefore, $\{\tau + \sigma < k\} \in \mathcal{F}_k$.

Another way to show this is:
Let $k \geq 0$ be fixed. Since $\tau$ and $\sigma$ are optional times, we have that $\{\tau < k\} \in \mathcal{F}_k$ and $\{\sigma < k\} \in \mathcal{F}_k$.
Now, consider the set $\{\tau + \sigma < k\}$. For any $\omega \in \{\tau + \sigma < k\}$, there exists $n \in \mathbb{N}$ such that $\tau(\omega) \leq n$ and $\sigma(\omega) \leq k - n$. Thus, we have
$$\{\tau + \sigma < k\} \subseteq \bigcup_{n=0}^{k} \{\tau = n\} \cap \{\sigma < k - n\}$$
Since ${\tau = n} \in \mathcal{F}n$ and $\{\sigma < k-n\} \in \mathcal{F}_{k-n}$, it follows that $\{\tau = n\} \cap \{\sigma < k - n\} \in \mathcal{F}n \otimes \mathcal{F}_{k-n} \subseteq \mathcal{F}_k$, where $\mathcal{F}_n \otimes \mathcal{F}_{k-n}$ denotes the product $\sigma$-algebra.
Therefore, we have
$$\{\tau + \sigma < k\} \subseteq \bigcup_{n=0}^{k} \{\tau = n\} \cap \{\sigma < k - n\} \in \mathcal{F}_k$$, which implies that $\{\tau + \sigma < k\} \in \mathcal{F}_k$.
Since $k \geq 0$ was arbitrary, we have shown that $\{\tau + \sigma < k\} \in \mathcal{F}_k$ for all $k \geq 0$, which implies that $\tau + \sigma$ is an optional time.
To conclude, we have shown that if $\tau$ and $\sigma$ are optional times with respect to the filtration $(\mathcal{F}_t)_{t\geq 0}$, then $\tau+\sigma$ is also an optional time. This result has important applications in stochastic calculus and stochastic processes, where it allows us to show that certain stopping times are indeed well-defined and have the desired properties.
Particularly I prefer the first way
Comment: Why do you need the $A$ in the first way?
Comment: Sorry, I got confused and put extra thinking about something else
Comment: No problem. I have another question regarding to your first attempt. If I see it correctly you first attempt is similar to the second answer from @MrGandalfSauron. But if I take $q_1=q_2=\frac{k}{n}$ then $q_1+q_2=\frac{2k}{n}$ shouldn't it be in your answer $$\{\tau + \sigma < k\} = \bigcup_{n=1}^\infty \left(\left\{\tau < \frac{k}{2n}\right\} \cap \left\{\sigma < \frac{k}{2n}\right\}\right)$$
Comment: Yes, you are correct. If we choose $q_1 = q_2 = \frac{k}{n}$, then $q_1 + q_2 = \frac{k}{n} + \frac{k}{n} = \frac{k}{2n}$. Thus, we can refine the union in the proof to include all pairs $(q_1, q_2)$ with $q_1 + q_2 < k$, not just those with $q_1 + q_2 = \frac{k}{n}$. This gives us:

$$\{\tau + \sigma < k\} = \bigcup_{q_1+q_2<k} \left(\{\tau < q_1\} \cap \{\sigma < q_2\}\right)$$

Thank you for pointing out this error.
Comment: No problem. Maybe it would be nice if you could change it in your answer for other readers.


sorting rating by a unique filter using backbone.js

Question: I have a collection of items in backbone.js which one of it's attributes is "rating" ( the rating can be between 1 and 5)
I would like to filter the collection that the items which are first are with the rating "3" then "3.5" and so on up to "5" and afterwards "2,5", "2" down to "1".
I have managed to filter by rating and get it sorted from 1 to 5 and then spliced the sorted collection but that's as far as I got.
I wonder if there is a quick way in backbone/underscore to do so rather then do the following:

sort the collection from 1 to 5.
split the collection to 2 arrays (one will have items with rating of 3-5 and the second with the rating of 1-2)
reverse the second array
merge the first and the second arrays together

Thanks
Answer: I'll admit this is an odd use-case, but I guess if you want to do all of the sorting work in a single pass, I would use the underscore sortBy() method.  Assuming your collection contains models with a rating attribute do something like this:
_.sortBy(array, function(model) {
    var rating = model.get('rating');
    if (rating >= 3) {
        return rating;
    } else {
        return (rating * -1) + 10;
    }
});

Check out the documentation at http://underscorejs.org/#sortBy
Good luck!
Comment: By the way, if you've chosen to use lodash instead of underscore for Backbone, check out the docs here: http://lodash.com/docs#sortBy
Answer: You can try defining a sort function on the comparator property of the collection.
Try this:
var sort = function(a, b) {
    // Sort normally if both >= 3
    if (a >= 3 && b >= 3) {
        return a - b;
    // Sort in reverse if both < 3
    } else if (a < 3 && b < 3) {
        return b - a;
    // Keep values less than 3 after those >= 3
    } else if (a < 3 && b >= 3) {
        return 1;
    // Otherwise a is >= 3 and b < 3, so a comes before
    } else {
        return -1;
    }
}

See demo.
Except you would replace a and b with the actual attribute since the arguments will be objects instead of numbers.


Swapping Poisson process at fixed time

Question: Let $X(t)$ and $X'(t)$ be independent Poisson processes with rate $\lambda$. Fix a time $s\in \mathbb{R}$. Define
$$X''(t)=\begin{cases}
X(t) & t\leq s, & \\
X'(t)-X'(s)+X(s) & t>s.
\end{cases}$$
Is $X''(t)$ also a Poisson process with rate $\lambda$? I suspect it should be from the memoryless property of the exponential, though I can't seem to find this question in the literature and am unsure on how to prove it. I've seen similar questions where the switch occurs after some number of arrivals, but not at a deterministic time.
Answer: More generally, if $X(t)$ has rate $\lambda_1$ and $X'(t)$ has rate $\lambda_2$, then $X''(t)$ is a non-homogeneous Poisson process with rate step function $$\lambda(t) = \begin{cases} \lambda_1, & t \le s \\ \lambda_2, & t > s. \end{cases}$$  But in your case, if $\lambda_1 = \lambda_2$, then $\lambda(t) = \lambda$ is constant and therefore $X''(t)$ is homogeneous.  That the switching time is deterministic has no bearing because the rate has not changed.

Swapping Poisson process at fixed time


Alteração de tamanho do vetor em uma estrutura

Question: Eu tenho a seguinte estrutura:
struct Implicantes{
    int posicao;
    char binario[5];
    bool dontcare;
    bool tick;
    struct Implicantes *Next;
};

É possível alterar o tamanho do vetor de char "binario" de 5 para o tamanho de uma variável que viria como parâmetro de entrada para a estrutura (não sei se isso é possível também)? Preciso que o tamanho do vetor da estrutura mude durante o código mas não sei como fazer essa alteração.
Comment: Essa mudança (configuração das instancias da estrurura) precisa acontecer em tempo de compilação ou em tempo de execução? Todas as variáveis da estrutura terão sempre o mesmo tamanho do vetor ?
Comment: O seu programa é em C ou em C++. São linguagens diferentes e, portanto, soluções diferentes. Por exemplo, `bool` é algo que não existe em C
Comment: Quando vejo essas estruturas com um ponteiro chamado `Next`, já imagino que é trabalho pra faculdade/escola e listas encadeadas..., mas quando vejo o nome `Implicantes` imagino que alguém esteja fazendo um jogo hehe
Answer: Se fosse um vetor em C++ poderia. Um array em C, como foi usado, não pode. Se estiver usando C++, ou muda para vector (no caso de char pode usar string) ou em C ou C++ muda para ponteiro e arca com todas consequências disto, como cuidar da alocação (tem exemplo na resposta do Anthony Accioly, mas note que terá que cuidar disto sempre), talvez não seja o que deseja.
Em qualquer caso se tiver que limitar o tamanho terá que ser feito manualmente. Em C é possível criar algumas facilidades, mas o consumidor dessa estrutura terá que lidar com tudo por vontade própria. Em C++ é possível abstrair todo o controle de acesso, mas dá um pouco mais de trabalho.
Até é possível ter um array único no final de um estrutura sem tamanho definido em C, mas não é compatível com todos compiladores, poucas pessoas usam, não é tão recomendado e acaba funcionando como um ponteiro. Melhor nem tentar.
Answer: No c você geralmente resolve isso com um ponteiro do tipo char e malloc para reservar o espaço dinamicamente:
struct Implicantes {
    int posicao;
    char *binario;
    bool dontcare;
    bool tick;
    struct Implicantes *Next;
};

struct Implicantes imp;
imp.binario = malloc(50 * sizeof *imp.binario);
// 50 pode ser substituido por qualquer tamanho

// ou ainda, se tudo vai ficar em escopo comum
// char s[50];
// imp.binario = s;

No c++ eu simplesmente usaria uma string
struct Implicantes {
    int posicao;
    std::string binario;
    bool dontcare;
    bool tick;
    struct Implicantes *Next;
};

struct Implicantes imp = {};
std::string binario = "Essa e uma string chamada binario";

Answer: Vou cobrir uma solução em C++ para o seu problema:

É possível alterar o tamanho do vetor de char "binario" (...)

Não é possível alterar o tamanho de uma array durante a execução do programa (usei o termo array ao invés de vetor e já deixarei claro a razão disso). Você terá de usar de outro tipo de variável, como nos exemplos das outras respostas. Em C++, existe uma solução padrão para quando queremos um número variável de elementos do mesmo tipo (no seu caso, um número variável de char), e é uma classe chamada vector:
#include <vector>

struct Implicantes{
  int posicao;
  bool dontcare;
  bool tick;
  struct Implicantes *Next;
  std::vector<char> binario;
};

Agora sim: um vetor, de tamanho variável, de char. Se esse código lhe parece estranho, vou esmiuçar um pouco, mas acho que uma explicação completa sai do escopo da pergunta:
O std:: indica que estamos usando um elemento da biblioteca padrão do C++ (std é uma abreviação de standard), estes elementos ficam todos dentro de um namespace com esse nome. E o <char> indica que tipo de variável o vetor guarda, você pode criar um vector<int>, vector<bool>, vector<Implicantes>, vector<qualquer_classe>.
No seu exemplo, a variável binario tem tamanho cinco, fixo, e espaço reservado para os cinco chars(que é a razão pela qual seu tamanho não pode ser alterado), já o vetor pode ter qualquer tamanho, e por isso ainda não possui espaço reservado. O que leva a segunda parte da questão...

(...) de 5 para o tamanho de uma variável que viria como parâmetro de entrada para a estrutura (não sei se isso é possível também)

Imagino que você seja novo a linguagem e não conheça construtores. Construtores são exatamente funções que recebem parâmetros no momento da criação de um objeto. Por exemplo:
struct Implicantes{
  int posicao;
  bool dontcare;
  bool tick;
  struct Implicantes *Next;
  std::vector<char> binario;
  //construtor recebe parâmetro e define tamanho do vetor [binario]
  Implicantes(unsigned int quantos_binario)
  {
    //resize é um método que altera o número de elementos do vetor
    binario.resize(quantos_binario);
  }
};

Essa função com o mesmo nome da estrutura é um construtor, e agora para criar um Implicantes você vai ter de fornecer um número, como no exemplo:
int main() {
  //cria Implicantes com binario contendo 2 char
  Implicantes A(2);
  //cria Implicantes com binario contendo 7 char
  Implicantes B(7);
}

Se você ainda quer poder criar um Implicantes sem dizer quantos elementos binario deve ter, pode declarar um construtor sem parâmetros, e este será usado quando você não fornecer nenhum parâmetro:
struct Implicantes{
    int posicao;
    bool dontcare;
    bool tick;
    struct Implicantes *Next;
    std::vector<char> binario;
    //construtor recebe parâmetro e define tamanho do vetor [binario]
    Implicantes(unsigned int quantos_binario)
    {
        binario.resize(quantos_binario);
    }
    //construtor sem nenhum parâmetro, define tamanho de vetor [binario] para 5
    Implicantes()
    {
        binario.resize(5);
    }
};

E agora...
int main() {
  //cria Implicantes com binario contendo 2 char
  Implicantes A(2);
  //cria Implicantes com binario contendo 7 char
  Implicantes B(7);
  //cria Implicantes com binario contendo 5 char
  //através do construtor padrão
  Implicantes C;
}

Depois que você definiu o tamanho do vetor, é só usar normalmente como com as arrays:
int main() {
  Implicantes C;
  C.binario[0] = '0';
  C.binario[1] = '1';
  C.binario[2] = 'z';
  //etc...
}


modf function intpart is zero?

Question: What am I doing wrong I always get intpart equal to 0 when I enter any number ?
#include <stdio.h>
#include <math.h>

int main(int argc, char* argv[])
{
double x=0.,fraction=0.;
int intpart=0;
printf("read value of x :");
scanf("%lf",&x);
fraction=modf(x,&intpart);
printf("x=%f    intpart=%d   fraction=%f \n",x,intpart,fraction);
return 0;
}

Answer: modf() takes double* as its second argument. But you are passing an int*. So, it's undefined behaviour. The solution is to use a double*:
Change
int intpart=0;

to
double iptr = 0;

Compile with all warnings enabled. Clang produces the warning:

warning: incompatible pointer types passing 'int *' to parameter of
type 'double *' [-Wincompatible-pointer-types]

and gcc produces:

warning: passing argument 2 of 'modf' from incompatible pointer type
[-Wincompatible-pointer-types]

See C11 draft, 184.108.40.206, The modf functions.
Comment: @rondino You're welcome! It's great that you want to check the Standard! Btw, there's a thread on here somewhere that links to the final drafts of various C (and C++) versions in PDF form. I like to save these and text-search through them when looking for information, which sometimes works surprisingly well considering how big they are. ;-)
Comment: @rondino Show us where you think you cast any `double` to `int`. If you mean 'why doesn't the compiler infer what I really want and cast for me', then thankfully, because it isn't so presumptuous.
Comment: If you mean casting an `int*` to `double*` then no, it'll create aliasing problems. Why not simply use the right type and declare `intptr` as `double`: `double iptr;`?
Comment: @rondino The fact that pointers aren't implicitly converted - and with the exception of _to_ `char *` can't be explicitly converted and dereferenced - follows from the facts that (A) different pointers may have different representations, and (B) trying to access an object of one type via a pointer of another violates strict aliasing rules; see http://stackoverflow.com/a/7005988/2757035 More directly: `double *` and `int *` are different, incompatible types. The compiler will not automatically realise what you _really_ want and fix your code and/or cast between pointer types and cause aliasing.
Comment: can you give that part in the standard stating that please ? what about casting double to int why it didn't work ?
Comment: I do that only for educational purposes ! :) I will be really grateful if yougive me that part in the standard about your last comment !
Comment: @underscore_d thanks a lot for the explanation ! same for P.P  :)

modf function intpart is zero?


Subset of the Cantor set is perfect

Question: Is every closed non-empty subset of the Cantor set perfect?
Since the Cantor set itself has all the accumulation points within the set, I don't see why taking points away from the set would result in a non-perfect set, but I don't know how to prove this rigorously, or I might be totally wrong.
Comment: "Since the Cantor set itself has all the accumulation points within the set" -- but that's true of any closed set. The important thing here is  a perfect set has no isolated points.
Comment: For an infinite counterexample consider $\{0\}\cup\{3^{-n}:n\in\Bbb N\}$.
Comment: There are finite subsets.
Comment: As well as single point subsets.
Comment: I don't want to get fuzzy but if you think about it, a subset can be any collection of points.  What the superset is can't actually force any restrictions on what a subset must be.  A superset can force what a subset *can't* be but it can't force what a subset must be.
Answer: Consider a single point $x$ . . .
Answer: The set $\{0\} \cup \{ 1/3^n : n=1,2,3,\ldots \}$ is a closed subset of the Cantor set, but it has lots of isolated points.
Answer: Perfect sets (in Polish spaces) have cardinality $2^{\aleph_0}$. This means that countable (and finite) closed sets cannot be perfect.

Subset of the Cantor set is perfect


50% Load on 2 CPU is the same that 100% Load on One CPU?

Question: Very basic doubt: I have an application running on a VM with 2 vCPU.
The average load is a bit less than 50% on both CPUs.
Does that means that 1 CPU will be enough for my application?
Or more CPUs benefit from threads running in parallel?
Edit:
Here a real example from my system which consists of 8CPU, over a month.
The data are normalised to 100%=8CPU.
I wonder if this information is enough to solve my question, basically if the system is oversized.
Comment: What if you need to run some cron job?
Comment: I edited my answer about your graphs. I agree, they are confusing.
Answer: It's not quite that simple. With one thread or process that burns as much CPU as possible, it will max out at 50% CPU on a dual CPU system. Or, some systems will show it as 100% CPU, because the maximum is 200% CPU then.
If you have two threads running at 50% CPU of one core (so they don't max it out), maybe they will run about as fast on a single core, but then you will see 100%. (This is not taking into account that the machine has other things to do, and that context switching causes overhead.)
For instance, if you have two threads that sleep 50% of the time and calculate stuff the other 50% of the same, one CPU can alternate the sleeping and calculating of those two threads so that 100% of the CPU is used.
Edit:
I thought I'd show some example graphs that illustrate it.
This server runs 16 high-CPU processes, and some few hundred low-CPU. In March, I decided to upgrade it to 8 CPUs/cores (hence the jump to 800%), mainly because I had to run extra software on it for a while, which you can see.

For a large part from May through July, 4 cores could have been enough. However, I do know that some of my processes (doing batch processing) would have been delayed.
This is the accompanying load graph:

It correlates, but as you can see it's not just percentage/100.
You want such graphs to be able to make informed decisions.
Edit 2, about your graphs:
Interesting. What were these graphs made with? Both of them represent the data the opposite way I'm used to: it seems the CPU utilization goes to 100% for all cores in the system, instead of 100% per core, like my graphs. You can test it by running dd if=/dev/urandom of=/dev/null for a few hours; that will cause one core to max out, and you'll see the effect.
The load graphs shows load per core. I've never seen that before. uptime, htop, munin: they all show just load.
Comment: Well so for example If have 4 CPUs and the overall load average of the whole system is 0.2%, it looks to me like 0.2*4=0.8= almost one CPU. Could I safely assume that my system is oversized and maybe reduce CPUs to 2?
Comment: The concept of 'load' is something else. That is the amount of runnable processes. Depending on the OS, this may or may not include IOWAIT. This distinction is important, because if you have processes waiting for external IO, it's not burning CPU. In any case, what you should do, is collect CPU and load graphs with something like Munin, post them in your original question, together with the task description (because I still don't know how many threads you run), and then we can say if your server is oversized. Spoiler: answer may be yes, but I'm showing you the road towards the answer.
Comment: I added some pictures. thank you very much for your clear explanations
Answer: You can actually never understand the requirement just by looking at CPU usage,Modern CPU generate threads in a suitable fashion as per the requirements.
More the core more advantage an application can have to run threads.
Comment: To (likely) clarify the down votes: CPUs don't generate threads. It's really the software's job to do that. Even if you mean hyperthreading, the software still needs to have separate threads running.


WordPress WP_Query - Como mostrar apenas post pai?

Question: Boa noite a todos, tenho um CPT onde cada post tem seu filho, ao listar isso com o WP_Query, na página é mostrado todos os posts (pai e filho), porém eu quero mostrar só os posts 'pai', como posso fazer isso?
Desde já muito obrigado!
segue o código usado:

      <?php
       $args = array(
           'post_type' => 'novellist'
       );
       $novels = new WP_Query( $args );

       if( $novels->have_posts() ):
          while( $novels->have_posts() ): $novels->the_post();
       ?>

           <?php get_template_part('template_parts/content', 'archive-novel'); ?>

       <?php
            endwhile;
            wp_reset_postdata();
            endif;
       ?>

Comment: No título você diz *post pai*, no corpo da pergunta você diz * categoria pai e filha*. Quem tem filhos é o *CPT* ou a *categoria*? **São coisas bem diferentes**.
Comment: Peço desculpas pelo o erro, tenho um CPT chamado ''Novels List" e tenho uma taxomania chamada ''novels'' atrelado ao CPT. No CPT tenho o post pai (que recebe a categoria pai) e o post filho( que recebe a categoria filho). Editei o post inclusive
Answer: Para isso, você pode usar o parâmetro post_parent. Quando um post tem "0" como parent, significa que não tem pai, logo, não é post filho.
 $args = array(
   'post_type' => 'novellist',
   'post_parent' => 0
 );

(fonte)
Comment: @GustavoSiqueira editei a resposta depois que você esclareceu a ambiguidade.
Comment: acho que fiz algo errado, todos os post sumiram quando uso esse argumento
Comment: Peço desculpa pelo meu erro, acabei confundindo as taxomanias com os posts, muito obrigado pela ajuda!


Counting words of length $n$ from $k$-sized alphabet with no substring of $k$ consecutive distinct letters

Question: How many words of length $n$ are there, if we have an alphabet of $k$ distinct letters, but the words cannot contain any substring that is made of $k$ consecutive distinct letters, i.e, no $k$-length substring that consists of the entire alphabet?
Other than that, no restrictions apply: any amount of distinct letters may be used throughout the entire word, and any letter can be used as many times as we like, as long as every substring inside the length $n$ word complies with the rules above.
There is the obvious case of $k=2$ which results in $2$ words, for every $n$, because you can only start with either letter, and they alternate.
For the larger case, I have come up with a recursive formula:
$$C(n,k)=f(0,0,k)$$ $$f(i,d,k)=\begin{cases}\displaystyle(k-d) \cdot f(i+1,d+1,k) + \sum_{c=1}^df(i+1,c,k) & i<n,d<k\\ 1 &i=n,d<k\\ 0 &i>n\\ 0 &d\geq k
\end{cases}$$
With $d$ being the current length of consecutive distinct letters, and $i$ the current word length.
At every step, we can either use a letter other than the previous $d$ letters, in which case the length is increased by one, and the chain-length $d$ of distinct consecutive letters is also increased by one. In this case, there are $(k-d)$ such letters we can use at the stage, each subsequently resulting in the same contribution.
Or, we can use a letter already in the last $d$ letters. In this case, the position of the letter matters. If we use the last of the $d$ letters, a whole new chain begins. If instead we use the second last $d$ letter, then a chain of length $2$ of consecutive distinct letters begins. The $3$rd last would result in a chain of length $3$ and so on.
I was wondering if there is a another way to count the amount of such words, perhaps using matrices or combinatorics?
Comment: you can build an automaton that accepts it. Chomsky-Schutzenbergers theorem tells you how to count it.
Comment: what are the possible constraints for $n$ and $k$?
Comment: @Yorch Well, it's theoretical, but say $k$ is relatively small I would say, up to $10$, and $n$ is really large, up to $10^{10}$
Comment: @Phicar Can you please elaborate? I went through the wikipedia entry and a few other sources. Did not understand how to apply it here exactly
Comment: @Matan I will over the weekend, sorry for delay.
Comment: @Phicar Thank you, looking forward to it
Answer: This might not provide a full answer, but here is some direction if you are familiar with generating functions. I believe that this type of ideas for counting problems on words was first introduced by Guibas and Odlyzko.

Imagine that the alphabet is $\Sigma=\{1,\ldots, k\}$.
Let $F(z)$ be the generating function of strings with no permutation of $\Sigma$ as a substring (let's call them "good strings"), and $G(z)$ be the generating function of strings with no permutation of $\Sigma$ as a substring, except the last $k$ letters which are $1, \ldots, k$ (in that order). (By symmetry, you would get the same generating function if you replace $1, \ldots, k$ by any of its permutations in the definition of $G$.)
Now by counting what happens when you add one letter to the right of good string,
$$F(z)+k!G(z)=1+kzF(z)\tag{1}.$$
By another counting argument on the concatenation of good string and the sequence $1, \ldots, k$,
$$F(z)z^k=G(z)\sum_{i=0}^{k-1} i! z^i\tag{2}$$
After solving the linear system (1) and (2), we get
$$F(z)=\frac{P(z)}{k!z^k+(1-kz)P(z)},$$
where $P(z)=\sum_{i=0}^{k-1} i! z^i$. You can check the series expansion for $k=2$.


Cannot download generated files

Question: I have a site (Linux/Drupal/Apache) that generate a .xlsx file from custom code and its saved to files, but after that I cannot download it from drupal, it give permission denied.
<code>Forbidden
You don't have permission to access xxxxxxx.xlsx on this server.
</code>
The upload file is saved with -rw------- or 600 permission, and the user/group from Apache.
If I chmod the file to 644 it works.
How can I made that any file generated in that way, will be -rw-r--r-- or 644 ?
Comment: What upload method are you using?
Comment: File not uploaded, its generated from code. Question edited.
Comment: Ok, so provide the code you're using to generate and save the file.
Comment: I think you should modify the permissions of the folder containing the files. The files should inherit access rights from the parent folder.
Comment: container folder have 755 permissions, but the newly created file its not inheriting permissions, as its being created as 600.
Comment: Have you tried changing the folder permissions recursively?
Comment: That will not fix future generated files...
Comment: If the access rights and file / folder owners are properly configured the files should inherit the rights of the parent folder
Comment: If I create a file manually on that directorie, the file inherit permissions properly, also check with umask, but files created with PHP are not follow that, and create files with 600 insted of 644.
Comment: Okay so the access rights are not the problem. Can you describe how you create the file? Maybe provide a code example?
Answer: A few things to check:

make sure there is no .htaccess rule that is preventing the download
(it may be inherited).
If using file entity check: /admin/config/media/file-settings and make sure .xls is allowed.
Could be blocked by server security like modsecurity rules, check the apache logs...
Answer: Execute a drush status-report and see if you have any problems that Drupal detected.
If not comfortable with drush, navigate to [yoursitename]/admin/reports/status and see if you have any action items (highlighted in red)

How can I made that any file generated in that way, will be -rw-r--r--
  or 644 ?

You can check your default perms by executing umask (http://en.wikipedia.org/wiki/Umask). It is usually 0022. If it is something like 0077, then you will have to change it, if it isnt then dont worry about it right now.

Cannot download generated files


fullscreen modal for chat in css

Question: I downloaded this modal popup script from this link https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal2
I want to use it to build a modal popup chat that will be responsive to all mobile devices.
I have set the chat header to 10%, chat footer to 15%.
Please how do I:
1.) set the chat body to ensure that chat messages does not push down the modal footer once the messages exceeds the body may be adding scroll bar in the body since the remaining height percent is 75
2.)it will be responsive on mobile devices
Thanks
Below is what i have done
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

Animated Modal with Header and Footer

<button id="myBtn">Open Modal</button>

      ×

Modal Header

chat messages goes here

chat messages goes here

chat messages goes here

chat messages goes here

Chat: <input type="text" placeholder="Chat Message" class="form-control">

Files Goes Here

Answer: You can set the max height of the modal-body so it won't push the footer and add overflow auto so you can scroll when needed only in the modal-body.
CSS
.modal-body {
    padding: 2px 16px;
    max-height: 75%; /* 10% header and 15% from footer */
    overflow: auto;
}

Comment: Why "max-height: calc(100% - 25%);" you can say direct max-height: 75%;
Comment: Yes, of course just in case there's the need to perform some calculation based on something else. Edited makes more sense.
Answer: According to your ideas, if you want auto height div with overflow and scroll when needed, this article will be the solution for you

fullscreen modal for chat in css


How to find the closed form of a multiple integral

Question: I want to find the closed form of the following $$\int\limits_{t<t_p<\cdots<t_1<1} t_1^{n_1-1}\cdots t_p^{n_p-1}dt_1\cdots dt_p,$$
where $p,n_j\ (j=1,2,\ldots,p)$ are positive integers.
Answer: Let $F(\{n_1,\cdots,n_p\},t)$ denote the integral. Then we have the following recursive formula:
$$ F(\{n_1,\cdots,n_p\},t) = \int_{t}^{1} \tau^{n_p-1} F(\{n_1,\cdots,n_{p-1}\}, \tau) \, \mathrm{d}\tau, \qquad F(\varnothing, t) = 1. $$
If we write $s_k = n_1 + \cdots + n_k$ and $s_0 = 0$, then

$$ F(\{n_1, \cdots, n_p\}, t) = \sum_{k=0}^{p} \frac{t^{s_p - s_k}}{\prod_{j\neq k} (s_k - s_j)}. \tag{*} $$

Indeed, $\text{(*)}$ is trivial if $p = 0$, and assuming $\text{(*)}$ for $p$,
\begin{align*}
F(\{n_1,\cdots,n_{p+1}\},t)
&= \int_{t}^{1} \tau^{n_{p+1}-1} F(\{n_1,\cdots,n_p\}, \tau) \, \mathrm{d}\tau \\
&= \int_{t}^{1} \left( \sum_{k=0}^{p} \frac{\tau^{s_{p+1} - s_k - 1}}{\prod_{j\neq k} (s_k - s_j)} \right) \, \mathrm{d}\tau \\
&= \sum_{k=0}^{p} \frac{1 - t^{s_{p+1} - s_k}}{(s_{p+1} - s_k) \prod_{j\neq k} (s_k - s_j)} \\
&= \sum_{k=0}^{p} \frac{1}{(s_{p+1} - s_k) \prod_{j\neq k} (s_k - s_j)} + \left( \sum_{k=0}^{p} \frac{t^{s_{p+1} - s_k}}{\prod_{j\neq k} (s_k - s_j)} \right)
\end{align*}
The sum in the constant term can be shown to be $1/\prod_{j=1}^{p} (s_{p+1} - s_j)$, and so, $\text{(*)}$ holds for $p+1$. Now the desired claim follows the induction on $p$.


Derivative of elementwise operation

Question: I was trying to take the derivative of $$1^T((AA^T) \circ (AA^T))1$$ with respect to $A$, where $A$ is a $m$ by $n$ matrix. I was trying to use the chain rule, but it doesn't work and I know the derivative will have dimension $m$ by $n$, but I cannot get this result. Are there anyone who knows how to approach this question?
Comment: If $1, 1^T$ are the identity matrices, the multiplication by those matrices is useless. Unless those are not the identity matrices. If so, what are they?
Comment: @mathcounterexamples.net I suspect they are vectors of 1s. Now, OP, you can definitely use the chain rule. You have to differentiate the composition $X \mapsto a^\intercal X^2 a$ with $X = AA^\intercal$ with respect to $A.$
Comment: What does $\circ$ mean?
Answer: $
\def\o{{\tt1}}\def\p{\partial}
\def\L{\left}\def\R{\right}
\def\LR#1{\L(#1\R)}
\def\BR#1{\Big(#1\Big)}
\def\vecc#1{\operatorname{vec}\LR{#1}}
\def\trace#1{\operatorname{Tr}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\c#1{\color{red}{#1}}
$For ease of typing, define the all-ones matrix
$J=\o\o^T,\,$ the symmetric matrix $S=AA^T,\,$  and the Frobenius $(:)$ product $-$ which is a concise notation for the trace
$$\eqalign{
A:B &= \sum_{i=1}^m\sum_{j=1}^n A_{ij}B_{ij} \;=\; \trace{A^TB} \\
A:A &= \big\|A\big\|^2_F \\
}$$
and (conveniently) commutes with the Hadamard product
$$\eqalign{
(A\circ B):C &= A:(B\circ C)
 \;=\; \sum_{i=1}^m\sum_{j=1}^n A_{ij}B_{ij}C_{ij} \\
}$$
Use the above notation to write the cost function.
Then calculate its differential and gradient.
$$\eqalign{
\phi
 &= \BR{(S\circ S)\o}:\o \\
 &= (S\circ S):J \\
 &= S:S \\
d\phi &= 2S:dS \\
 &= 2S:(dA\,A^T+A\,dA^T) \\
 &= 2(S+S^T):(dA\,A^T) \\
 &= 4S:(dA\,A^T) \\
 &= 4AA^TA:dA \\
\grad{\phi}{A} &= 4AA^TA \\\\
}$$

Derivative of elementwise operation


Error in php snippet using tokens: Show profile field if it isn´t empty

Question: I have this core profile field in Drupal7: profile-curso-basico.
I want it to be shown in the user´s profile  only if the field has information in it (it´s a deprecated field, but some old users have data in it, and migrate modules didn´t import it properly, because it´s a hardcoded list).
I´m using panels, token and Display Suite modules.
At the profile page, I have this panel with a special coded DS field, that has dinamic information using tokens.
If I just paste: Mi Curso: %user:profile-curso-basico I get the field information properly, but I want to show it only if profile-curso-basico field isn´t empty.
So I thought of this (the input type is PHP, so I can paste some php code):
<?php if (!empty(%user:profile-curso-basico)): ?>
%user:profile-curso-basico
<?php endif; ?>

And I´ve got this error:
Parse error: syntax error, unexpected T_LNUMBER, expecting T_PAAMAYIM_NEKUDOTAYIM in /home/liga/public_html/modules/php/php.module(80) : eval()'d code on line 9

What´s wrong with that snippet? Maybe I shouldn´t add tokens into (!empty( )) ?
How may I change that in order to work? Thanks!!
Comment: Drupal tokens are not valid PHP-code. Your code simply isn't valid.
Answer: You must refer to the actual field in your snippet. Try something like:
<?php
global $user;
if (isset($user->profile-curso-basico[LANGUAGE_NONE][0]['value'])) {
  echo $user->profile-curso-basico[LANGUAGE_NONE][0]['value'];
} ?>


Apache 2.2 Change HTTP Request Method From POST to GET

Question: Is there a way I can change the HTTP Request Method from POST to GET using apache modules such as mod_rewrite or 3rd party module ?
The reason I'm doing this is to minimize server side changes as I'm doing this for a demo.
Comment: If you are talking about `mod_rewrite`. This is a server side change. Also, not all POST requests can be changed to GET. The URL has a maximum allowed length. For example, this is not possible if you posting files.
Comment: no the POST data will be zero. so no problem with max allowed length. I just want to change the request method from POST to GET from apache config if possible
Answer: You could simply issue a 302 (temporary) redirect to the same URL and the browser will automatically change the request to GET. Naturally any POST data will be lost, but you say there is no POST data.
You could use the following in the Apache config (or .htaccess):
RewriteEngine On

RewriteCond %{REQUEST_METHOD} =POST
RewriteRule ^/?url-to-change-post-to-get$ %{REQUEST_URI} [R=302,L]


about spark remote submit app confuse

Question: my situation as follows:
i have a spark cluster  ,  it is on Linux Systems .
but i test my app on Windows , now i submit it to remote spark cluster , it is not work and always print flollows log :
<code> 15/08/04 19:33:09 WARN ReliableDeliverySupervisor: Association with remote system [akka.tcp://sparkMaster@h1:7077] has failed, address is now gated for [5000] ms. Reason is: [Disassociated].
</code>
my code :

who know this problem ?
Answer: After two days of exploration , I have found the way to solve the problem.
the most direct cause is that scala version is inconsistent , i found spark1.4.0 depend scala2.11.x , so i need recomplie spark source to suuport scala2.11.x
Follow the steps outlined below:
1 => dev/change-version-to-2.11.sh
2 => mvn -Pyarn -Phadoop-2.6 -Dscala-2.11 -DskipTests clean package
3 => make sure client scala version the same to server scala version

about spark remote submit app confuse


How long can a goalkeeper wait for opponent to come get the ball?

Question: On soccer it is common to see winning teams wasting time. Goalies have their own techniques to run out the clock.
A situation that intrigues me is when a goalkeeper is allowed to get the ball but chooses not to. He places both hands near the ball without touching it. He waits for an opponent to get close enough and then he proceeds to pick up the ball. Thus wasting 5 seconds of everyone's life ;-)
So, every time that a situation like this happens, an opponent runs towards the ball to force the goalkeeper to pick it up. If instead of running towards the ball all the opponents let the keeper run out the clock, how long can a goalie wait before picking up the ball?
EDIT
I will accept the answer indefinitely, because according to the rules that is the answer to my question.
But I was also interested on the practical effect of such ruling. Are there any real examples of players ever letting the goalie waste as much time as he wanted to? I cannot believe that everyone would just look at each other for 5 min...
Comment: Not sure why you'd expect there to be a rule against it. It's up to the opponents to force the issue. A goalie not using his hands is effectively a normal defender and if an outfield defender stood in his own box with the ball at his feet, unchallenged, would you expect a ruling against him?
Answer: In football, indefinitely.
The relevant offence is on page 37 of the 2014/15 FIFA Laws of the Game (emphasis mine):

An indirect free kick is awarded to the opposing team if a goalkeeper, inside his
  own penalty area, commits any of the following four offences:

controls the ball with his hands for more than six seconds before releasing it from his possession

...

As an aside, the powers that be at FIFA seem to agree that it's something that ruins the pace and excitement of the game. In futsal, FIFA's indoor game, which is designed to be as attacking and fast-paced as possible (and requires minimal effort to change the laws), it is illegal to do this with hands or feet.
Page 40 of the 2014/15 FIFA Futsal Laws of the Game (emphasis mine):

An indirect free kick is awarded to the opposing team if a goalkeeper commits any of the following four offences:

Controls the ball with his hands or feet in his own half of the pitch for more than four seconds

...
Comment: just remember the ['Disgrace of Gijon'](http://en.wikipedia.org/wiki/Disgrace_of_Gij%C3%B3n). I think in this game a goalie could have been walking (ball of his foot) through his penalty area for hours before grabbing it because an opponent's player wants to get the ball.
Comment: The referee would probably have no grounds to tell any of the players to get the ball. It's perfectly legal for both teams to play for a draw and eat up the clock. However, the referee would definitely be submitting a report to the competition authority after the game to ensure there wasn't anything untoward happening - ie. collusion to affect the competition table, match-fixing, etc.
Comment: But wouldn't the referee tell the goalie to get the ball? Or tell one of the opponents to go get the ball? Wouldn't both attitudes be considered unsporting behaviour?
Comment: @GabrielOshiro Why would the opponent (who presumably wants to score, as they're presumably down) not get the ball on their own?  Unless it's a tie that everyone is happy with, I guess, but that's relatively rare.


Let $f:E\to \Bbb{R},\;p\mapsto f(p)=\int_{0}^{1}p^3{(t)}dt$. Then $f$ is differentiable and we can compute $f'(u)$

Question: I have been faced with this problem. Let $$f:E\to \Bbb{R}$$
$$p\mapsto f(p)=\int_{0}^{1}p^3{(t)}dt.$$
I want to prove that $f$ is differentiable and also compute $f'(u).$ $E=R_n[x]$ is provided with the following norm $\Vert p\Vert=\sup|p(t)|,\;\;\forall\;t\in [0,1]$
Here is what I've done:
$f(p) = \int_{0}^{1}p^3{(t)}dt, \tag 1$
we have
$f(p + h) = \int_{0}^{1}(p + h)^3{(t)}dt  \tag 2$
for any $h \in E; \tag 3$
we may expand the right-hand side as follows:
$(p + h)^3 = (p + h)(p + h)(p + h) = (p + h)(p^2 + ph + hp + h^2)$
$= p^3 + p^2 h + php + ph^2 + hp^2 + hph + h^2 p + h^3; \tag 4$
thus
$$f(u + h) - f(u) = \int_{0}^{1}(p^2 h + php + ph^2 + hp^2 + hph + h^2 p + h^3){(t)}dt$$
$$=  \int_{0}^{1}(p^2 h + php + hp^2 + ph^2 + hph  + h^2 p + h^3){(t)}dt; \tag 5$$
$L(u)(h) = \int_{0}^{1}(p^2 h + php + hp^2){(t)}dt; \tag 6$
and
$$\Vert h\Vert \varepsilon(h)= \int_{0}^{1}( ph^2 + hph  + h^2 p + h^3){(t)}dt $$
$$ \Vert \varepsilon(h)\Vert= \frac{\Vert \int_{0}^{1}( ph^2 + hph  + h^2 p + h^3){(t)}dt \Vert}{\Vert h\Vert}. \tag 7$$
My question is: How do I force (7) to $0$? Please, can anyone help out?
Comment: Is there a reason why you distinguisd $hp$ and $ph$?
Comment: @Hagen von Eitzen: I thought $E$ does not form a commutative algebra.
Answer: Use
$$\left|\int_a^b u\,\mathrm dt\right|\le (b-a)\|u\|$$
$$\|u+v\|\le\|u+v\|$$
and
$$\|uv\|\le\|u\|\|v\|$$
Comment: I thought of that! Anyway, is my solution correct?


requestAnimationFrame - browser support issues

Question: http://jsfiddle.net/xwF6E/14/
Above is a JSfiddle of an animation i'm trying to create. It's works 100% fine in Chrome, however having various issues in other browsers.
It appears that in firefox it doesn't render the animation. As per the the Mozilla Dev Network docs @ https://developer.mozilla.org/en-US/docs/DOM/window.requestAnimationFrame , i believe i've added cross browser support but perhaps i'm doing something wrong.
In IE (8 + 10, at least) it does not render the animation, nor my radial gradient (also a side issue if anyone can help).
IE gives me a IndexSizeError error on this line of code
var imageData = context.createImageData(context.canvas.width, context.canvas.height);

But i'm not sure what that means specifically, and I can't find much regarding that error/that method.
Anyone able to enlighten me please?
Cheers
Answer: I'm guessing you figured this out by now, but for anyone else that might be interested, the cause is this code that's trying to get the window size:
context.canvas.width = document.width;
context.canvas.height = document.height;

You'll want to do something more like this:
context.canvas.width = document.body.clientWidth;
context.canvas.height = document.body.clientHeight;

Though it can actually be a little more complicated than that. See this for more information on finding window height and width:
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
Here's the modified fiddle: http://jsfiddle.net/shaunwest/MALN2/
Comment: Thankyou very much for this! Was actually surprised to get an answer to this one.
My fault for not updating, the application of it I used actually didn't require the window dimensions, so I avoided the problem entirely.
Cheers


auto-int floats when writing into an array

Question: import numpy as np

A=np.array([[-2,  1, -4, -9], [ 1, -3, -2,  3]])

print(A[1] - A[0] * A[1, 0] / A[0, 0])

A[1] = A[1] - A[0] * A[1, 0] / A[0, 0]
print(A[1])

it returns:
A
>>> array([[-2,  1, -4, -9],
       [ 1, -3, -2,  3]])

print(A[1] - A[0] * A[1, 0] / A[0, 0])
>>> [ 0.  -2.5 -4.  -1.5]

A[1] = A[1] - A[0] * A[1, 0] / A[0, 0]
print(A[1])
>>> [ 0 -2 -4 -1]

Why do these outputs different? It seems numpy automatically turn floats to intergers when writing into an array
Comment: That's the expected behaviour. You have an integer array, so whatever value you try to assign to one of each elements, it will be cast to an integer. The first print shows a float array because the arithmetic computations create a new array. But when you try to assign said values back to the original array, that -2.5 will become -2.
Comment: Is there some solutions to auto-create a float array except for `dtype = float`?
Comment: `np.array` tries to be smart and figure out the smallest type that can accommodate all the data. If you have a list of lists full of integers, it will be an integer array by default. If at least one of them is float (or complex), the respective type will be used instead. Nothing wrong with using `dtype=float` to be explicit, or to be sure you'll have the right type regardless of input.
Answer: Thanks @Reti43, I should add dtype = float like:
A=np.array([[-2,  1, -4, -9], [ 1, -3, -2,  3]], dtype = float)


My (Lua) Door script Doesn't work at all (I am VERY new)

Question: So I Coded a D O O R script to when MouseClick open door to coord, then click go to (OG) coord.
I have tried to re-write the code, I made some things capital and not capital, I checked the (.) and (:) and now I cant see any errors.
Here Is My Code
local Door = script.Parent
local TweenService = game:GetService("TweenService")
local TweenStyle = TweenInfo.new(0.5, Enum.Easingstyle.Elastic.Out,0,false,0.)

local DoorOpen = {CFrame = CFrame.new(-54.66, 9.5, -9.056)}
local DoorClose = {CFrame = CFrame.new(-51.75, 9.5, -11)}

local OpenTween = TweenService:Create(Door,TweenStyle,DoorOpen)
local Closetween = TweenService:Create(Door,TweenStyle,DoorClose)

script.Parent.ClickDetector.MouseClick:Connect(function()
    OpenTween:Play()
    wait(2)
    Closetween:Play()
end)

SS of my code
Comment: "doesn't work at all" is not a useful description. explain the expected and observed behaviour of your code. are there any error messages? as is your post cannot be answered. do some own debugging. you could for example make sure your mouseclick is acutally handled by putting a print into the handler.
Comment: @Piglet What I expect to happen is when I click on the door then it would slide to X coords then when I click it again it would slide back. What I got is when I clik it I get a sound (door opening sound) but it doesnt move. And I've resolved all the errors but I cant find where I messed up, I'll try and llok for a vid on it now. Thanks for the help
Answer: There was a syntax error in your code, you didn't write the right arguments in the "TweenInfo" at the third line. I fixed the code for you:
local Door = script.Parent
local TweenService = game:GetService("TweenService")
local TweenStyle = TweenInfo.new(0.5, Enum.EasingStyle.Linear, Enum.EasingDirection.Out, 0, false, 0)

local DoorOpen = {CFrame = CFrame.new(-54.66, 9.5, -9.056)}
local DoorClose = {CFrame = CFrame.new(-51.75, 9.5, -11)}

local OpenTween = TweenService:Create(Door,TweenStyle,DoorOpen)
local Closetween = TweenService:Create(Door,TweenStyle,DoorClose)

script.Parent.ClickDetector.MouseClick:Connect(function()
    OpenTween:Play()
    wait(2)
    Closetween:Play()
end)

For more information about "TweenInfo" check the API reference:
https://developer.roblox.com/en-us/api-reference/datatype/TweenInfo
Comment: Did you find my answer useful?


Characterize the elements $\beta$ $\in$ $S_n$such that $\beta=\alpha^2$ for some $\alpha$ $\in$ $S_n$

Question:
Characterize the elements $\beta$ $\in$ $S_n$ such that $\beta=\alpha^2$ for some $\alpha$ $\in$ $S_n$.

I did the following: suppose that $\beta=\alpha^2$,then $sgn(\beta)=sgn(\alpha^2)=sgn(\alpha)^2=1$, so $\beta$ is an even permutation. Is there a more complete description?
Comment: Not every element in $A_n$ is a square; you have a necessary condition, but it is not sufficient, so you have not "characterized" the elements yet.
Comment: What happens with a single cycle if you square it? Why can the even permutation $(1,2)(3,4,5,6,7,8)$ not be a square, but $(1,2,3,4)(5,6,7,8)$ is?
Answer: More detailed hints.

If $\alpha$ is a cycle of odd length, then $\alpha^2$ is a cycle of the same length.

If $\alpha$ is a cycle of length $2k$, then $\alpha^2$ is the product of two cycles of length $k$.

Let $\alpha$ be the product of independent cycles.  Then and only then is $\alpha$ the square of some permutation when for every integer $k\geq1$ the number of independent cycles of length $2k$ is even (possibly equal to $0$).