How to approximate MAE of monthly values from MAE of daily values?

Question: Suppose I have the Mean Absolute Error (MAE) of daily values for a period of, say, 1 year. Assume the errors are normally distributed.
The value for a month is equal to the sum of the values for each day in that month.
Can I approximate the MAE of what the monthly values would be given the MAE of the daily values?
Based on how we can scale variance to bigger time periods, I believe it may be doable by multiplying the daily MAE by $\sqrt{30}$, assuming 30 days per month. Would this be valid? Why/Why not?
Answer: I've assumed that when you say the errors are normally distributed you mean the daily values (and so the monthly values) are normally distributed. I've also assumed that by MAE you mean the mean difference between each value and the mean of the values distribution,(i.e. the mean absolute deviation or MAD), rather than the mean difference between each value and an estimate of the value.
If these assumptions are correct, then your method of estimating the monthly MAE (or MAD) is valid. According to Wolfram MathWorld, the MAD of the normal distribution is $\sqrt{\frac 2 \pi} \sigma$, so as $\sigma_m = \sqrt{30} \sigma_d$ (where $\sigma_d$ and $\sigma_m$ are the standard deviations of your daily and monthly distributions, respectively), $MAD_m$ will also be $\sqrt{30} MAD_d$.
Comment: Thank you for your answer. It was helpful to confirm my understanding around scaling variance. I do mean the Mean Absolute Error; the absolute difference between an actual vs expected value (not MAD).


Showing a proposition of sequence

Question: How would I show the following
If limit
$j\rightarrow \infty$ for the sequence $b_j=B$  and B<0 then there exist an
number N in natural number such that when j>N then $b_j<0$
Would I start off doing
$|b_j-(-B)|<\epsilon$
Answer: Since $B < 0$, then $\varepsilon := -B/2 > 0$. So since $\lim_{j\to \infty} b_j = B$, there exists a natural number $N$ such that $|b_j - B| < \varepsilon$ for all $j > N$. Show that $|b_j - B| < \varepsilon$ implies $b_j < B + \varepsilon = B/2$.
Comment: I see so epsilon is -B/2 because it must be greater than zero. I think.
Comment: Right, I want particular choice of $\varepsilon$, but is has to be positive. Here I set $\varepsilon$ equal to $-B/2$.
Comment: Ok I understand it thanks

Showing a proposition of sequence


Could not read properties if it contains dollar symbol (${var})

Question: I have property file with following content:
INVALID_ARGUMENT=Field ${fieldName} is invalid or missing.

I read this using spring configuration:
@PropertySource("error_messages_en.properties")
@Configuration
public static class ErrorMessagesEn {
     @Value("${INVALID_ARGUMENT}")
    private String invalidArgument;
}

But after application start I see:
Could not resolve placeholder 'fieldName' in value "Ïîëå ${fieldName} íåêîððåêòíî çàïîëíåíî èëè ïðîïóùåíî."

I need ${fieldName} because I want to use repacer: https://stackoverflow.com/a/3655963/2674303
How to avoid this error?
Comment: Is not clear to me where you change the placeholder. I think you miss to explain this part.
Comment: @Mario Santini I do it in java code. Library I use for this linked in question
Comment: The link is about another answer and didn't explain how you use it in your code.
Comment: I want to read value to string with content **Field ${fieldName} is invalid or missing.** and then replace **${fieldName}** with value from runtime
Comment: Does this answer your question? [Escape property reference in Spring property file](https://stackoverflow.com/questions/13162346/escape-property-reference-in-spring-property-file)
Answer: You should escape ${fieldName} as it is not defined as a Spring property.
You could have a look at this question: Escape property reference in spring property file and the associated answer.
You should write this instead:
INVALID_ARGUMENT=Field #{'$'}{fieldName} is invalid or missing.

Comment: Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'INVALID_ARGUMENT' in value "${INVALID_ARGUMENT}"
Comment: I have tested and I do not produce this issue. Are you sure it is linked? If you set `INVALID_ARGUMENT=foo` are you getting the issue too?
Comment: looks like encoding issue, but I am not sure
Answer: If you are using a yaml file you need to surround the value with quotes
argument: "Field #{'$'}{fieldName} is invalid or missing."


A new sabermetric baseball statistic?

Question: Let's award a batter
2 points for a single,
3 pts for a double,
4 pts for a triple, and
5 pts for a homerun.
To complete the statistic, let's award the batter
1 point for a walk, and
1 point if he is hit by the pitch.
Call it "Advanced Batting Index".
If we calculate a batter's average Advanced Batting Index, is this equivalent to OPS?
Comment: I'm wondering if this is an accurate simplification of OPS or did I miss something in my calculation.
Answer: Not quite. The denominators are different for SLG and OBP, which makes combining the numerators more complicated than you're making it:
<code>SLG = TB / AB

OBP = (H + BB + HBP) / (AB + BB + SF + HBP)
</code>
Take a look at the equations.
Answer: OPS is on-base percentage + slugging/ at bats.
Slugging gives 1 for single, 2 for double, three for triple, four for HR.
On base percentage give 1 for all those, 1 for walk and 1 for HBP.
So yours is OPS*At Bats.
Comment: So if we calculate a batter's average Advanced Batting Index (average meaning we divide by AT BATS), would you agree it is OPS?

A new sabermetric baseball statistic?


How can a linear regression model give a low root mean square error but have a non well-behaved residuals vs fits plot?

Question: According to this criteria, a good residuals vs fits plot should look like this:

A plot like this:

would not be considered a good linear model. Why would the model still give a low root mean square error on the training set?
Comment: what is the scale on the y-axis? that's what really matters for the calculation of the RMSE.  But you should certainly fix these problems before concluding the model is good ...
Answer: If the second plot has the residual on the y-axis then the difference between it and the first plot is that in the first there appears to be no relationship between the spread (variance) of the residuals and the fitted value (or predicted response). In the second chart the residuals appear to have low variance (vertical spread is low) so the RMSE will be low but there's a relationship between what you're predicting and the residuals.
This usually indicates the model is misspecified in some way, perhaps you're missing a predictor that explains this relationship or perhaps there's autocorrelation such that the next output is dependent on previous outputs.
Most of the statistics such as confidence intervals of the coefficients assumes independent identically distributed residuals.


Probability distribution: finding 'a'

Question: Consider the random variable X with probability distribution,
$$
P(x) =
\begin{cases}
x^2/a & -2,-1,0,1,2 \\
0 & \text{otherwise}
\end{cases}
$$

a) Find $a$ and $E(X)$.
b) What is the probability distribution of random variable $Z = (X - E[X])^2$?
c) Using part b), compute the variance of $X$.

I think I understand parts b, c, and the second part of a, but I'm not sure how to find $a$. Maybe there's a formula I'm missing?

a) a = 10, E(X) = 0
b) $$P(Z = z) =
 \begin{cases}
      0 & z = 0 \\
      \frac{2}{10} & z = 1 \\
      \frac{8}{10} & z = 2
  \end{cases}$$
alt. b) $$P(Z = z) =
 \begin{cases}
      \frac{2}{5} & z = 1 \\
      \frac{4}{5} & z = 4 \\
      0 & otherwise
  \end{cases}$$
Comment: You might find [the meta thread on how to use MathJax/LaTeX useful](https://math.meta.stackexchange.com/a/5025/437127).
Answer: We know that the sum of all the probabilities has to be $1$. Therefore:
$$\frac{(-2)^2}{a}+\frac{(-1)^2}{a}+\frac{(0)^2}{a}+\frac{(1)^2}{a}+\frac{(2)^2}{a}=1$$
Does that give you a push in the right direction?
Comment: Yes! So I got a = 10, and E(X) = 0?
Comment: I also got $a=10$. Considering the distribution is symmetric, and centered at $0$, that makes sense for the expected value.
Comment: What are your thoughts on my probability distribution for part b in the original post (updated)?
Comment: That seems right, yeah.
Comment: Would part c be 2? If so, there is actually a part d that says use the actual formula instead of the answer from part b and I'm not getting the same answers...
Comment: Well, the expected value of $Z$ is certainly $2$. The formula I usually use for variance is $E(X^2)-E(X)^2$. That seems to be $3.4$, if I'm not making an error.
Comment: @Hello Your answer for (b) is not *quite* right, so the answer for (c) is erraneous too.
Answer:
a) a = 10, E(X) = 0

Yes. $
{~\\{P_X(x) =
\begin{cases} 0/a^2 & : & x=0 \\ 1/a^2 &:& x\in\{-1,1\} \\ 4/a^2 & : & x\in\{-2,2\}\\ 0 & : & \text{otherwise}
\end{cases} }\\~\\ {\therefore ~a=10, \mathsf E(X)=0}}
$

b) ${P(Z = z) = \begin{cases}
      \frac{1}{5} & z = 0 \\
      \frac{2}{5} & z = 1,4
  \end{cases}}$

No, but close. Try again.
Having found $a=10$ and $\mathsf E(X)=0$ you know know that $Z=X^2$ and can find $P_Z(z)= P_X(+\surd z)+ P_X(-\surd z)$  since: $$
P_X(x) =
\begin{cases} 0 & : & x=0 \\ 1/10 &:& x\in\{-1,1\} \\ 4/10 & : & x\in\{-2,2\}\\ 0 & : & \text{otherwise}
\end{cases}
$$
Therefore ...

c) Hint $\mathsf {Var}(X)=\mathsf E((X-\mathsf E(X))^2)$ and $Z=(X-\mathsf E(X))^2$ so...
Comment: So we have P(0) = 0, P(1) = (1/10) + (1/10), and P(2) = (4/10) + (4/10)?
Comment: I am a little confused by your hint for part b. For part c, I did notice that but did get led to the wrong answer since part b is incorrect. Is the probability distribution for part b supposed to include the constant a?
Comment: @Hello No. You already know $a=10$, and we have substituted that into the expression for $P_X(x)$ above.  You just need to evaluate $P_Z(z)$, which is $P_X(\surd z)+P_X(-\surd z)$, for $z\in\{0,1,4\}$.
Comment: Of course. @Hello
Comment: Is my updated edit to the original post correct?
Comment: Yes.  Did you find the variance okay using it?
Comment: Is it 0*0 + 1 * (2/10) + 2 * (8/10) = 1.8?
Comment: Given the answer to Problem 4.6 from [this link](https://robotics.eecs.berkeley.edu/~wlr/126SP07/HW/h4Sol.pdf), why would my answer not be similar to the "alt. b)" answer I provided above?
Comment: Because clearly: $\mathsf E(Z) = 0\cdot f_Z(0)+1\cdot f_Z(1)+4\cdot f_Z(4)$
Comment: Can you elaborate? I'm sorry
Comment: The support for $Z$ is $\{0,1,4\}$ with the given probability mass function. So $0\cdot 0+1\cdot (2/10)+4\cdot(8/10) = 3.4$
Comment: Oh, okay. Is 1.8 the correct variance?

Probability distribution: finding 'a'


Equivalent definition of Schwartz space

Question: Please tell me about the equivalent definition of schwartz space.
Definition of Schwartz space is the following.
$$ f(x) \in \mathcal{S} \overset {\mathrm{def}} {\Leftrightarrow} \displaystyle \sup_{x \in \mathbb{R^d} } \left|x^\alpha\partial^\beta_x f(x)\right| < \infty $$
$\forall$$\alpha,\forall$$\beta$ $\in$ $\mathbb{Z^d_+} $ ($\alpha,\beta$ is multi-index notation)
My textbook is written the following statement.
$$ \displaystyle \sup_{x \in \mathbb{R^d} } \left|x^\alpha\partial^\beta_x f(x)\right| < \infty\Leftrightarrow \displaystyle \sup_{x \in \mathbb{R^d} } \left|\partial^\alpha_x (x^\beta f(x))\right| < \infty $$
I have proved $\Rightarrow$ by using Leibniz's rule. But I haven't proved $\Leftarrow$. Please tell me proof $\Leftarrow$.
Answer: To keep notation simple I will sketch the idea in 1D.
1) With $\alpha = 0$ you have $\sup_{x \in \mathbb R} |x^\beta f(x)| < \infty$ for all $\beta$.
2) With $\alpha = 1$ you have $\sup_{x \in \mathbb R} |\beta x^{\beta - 1} f(x) + x^\beta f'(x)| < \infty$ for all $\beta$. You already know from 1) that $\sup_{x \in \mathbb R} |x^{\beta - 1}f(x)| < \infty$, so it follows that
$$
\sup_{x \in \mathbb R} |x^\beta f'(x)| < \infty.$$
3) Do the same with $\alpha = 2$, etc.

Equivalent definition of Schwartz space


Proving the equation $4x^3+6x^2+5x=-7$ has has only one solution using Rolle's or Lagrange's theorem

Question:
Prove the equation $4x^3+6x^2+5x=-7$ has only one solution.

Hello all. It is easy to prove this by defining the function $f(x)=4x^3+6x^2+5x+7$ and claiming it is a monotonic increasing function at $\mathbb{R}$, and since it is continuous at $\mathbb{R}$, and $f(-2)\le 0, f(-1)\ge 0$ then based on the MVT there exists a point $c\in[-2,-1]$ such that $f(c)=0$.
How do I prove there's only one real root using Rolle's theorem or Lagrange? Thanks in advance :)
Comment: What's the difference between Lagrange's theorem and MVT? I've learnt they are the same
Comment: If it's a monotonically increasing function on ℝ, it can only ever have one root.
Answer: For example, let's assume that $p(x)=4x^3+6x^2+5x+7=0$ has $2$ solutions $x_1<x_2$ such that $p(x_1)=p(x_2)=0$. Then, by Rolle's theorem, there must be $c \in (x_1,x_2)$ such that $p'(c)=0$. But $p'(x)=12x^2+12x+5=0$ has no zeros, since $\Delta=12^2-4\cdot 5\cdot 12=-96<0$.
Comment: beat my by 60 seconds...
Comment: Only because it's morning and I just woke up :)
Answer: If a polynomial has two distinct roots (say $a<b$) then it's derivative has a root at some $x\in (a,b)$ (why? This is where you apply the theorems you mentioned). But it easy to see that the derivative has no root, hence $f$ at most one. That such a root exists follows from its behavior at $\pm \infty$
Answer: Assume it has two roots.
$$f (a)=f (b)=0$$
then by Rolle's Theorem there will exist $c\in (a,b) $ such that
$$f'(c)=0=12c^2+12c+5$$
but the reduced discriminant is
$$\delta'=36-60 <0$$
Done.


how to calculate the probability that a specific series will not show

Question: Question:
I have a stack of 30 cards numbered from 1 to 30.
I start to pull out of the stack of cards one by one.
what is the probability that each one of those series:
$$ 1,2,3,...,10$$
$$11,12,13,...,20$$
$$21,22,23,...,30$$
will not show up in the pulling order.
Answer:
first the probability space size is $\left |\Omega   \right |=30!$
Now I want to calculate the probability that one of those series will show up as the complement to the probability I'm looking for.
Let's call the type of series that I'm looking for "bad series", we have 3 possible arrangements to a "bad series".
Now I handle the "bad series" as 1 item, so the total number of items I have in the deck is 21. with 21! ways to order them.
The probability to find the "bad series" in the pulling order is:
$$P=\frac{21!}{30!}$$
but the number of "bad series" we have is 3, so the total probability is:
$$P_{total}=\frac{3\times 21!}{30!}$$
so the probability that each of those "bad series" will not show up is:
$$P_{final}=1-\frac{3\times 21!}{30!}$$
Is my way of thinking correct? are there any other ways to approach those types of problems?
Answer: The first part is correct but you forget that there are sequences where two or all three of your series show.
Therefore you need to account for $3\times\frac{12!}{30!}$ for the ones where there are two of your series and $\frac{3!}{30!}$ for when there are all three. In total you get
$$P_{final} = 1-\frac{3\times21!}{30!}+\frac{3\times12!}{30!}-\frac{3!}{30!}$$
Comment: @knight5478 See [this article](https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle) for an
introduction to Inclusion-Exclusion.
Then, see [this answer](https://math.stackexchange.com/questions/4427605/inclusion-exclusion-principle-what-is-1n1/4427645#4427645) for an explanation of and justification for the Inclusion-Exclusion *formula*.  Analogizing, $~S_1, ~S_2, ~S_3,~$ are the subsets that respectively contain each of the three series.
Comment: why do you add the value of $\frac{3\times12!}{30!}$?
Comment: Thank you very much


Popup not waiting for response to close

Question: When I open popup in my application.And do some changes and closes it without saving.It displays a confirmation message and popup windows does not closes.
var r = confirm("There are some unsaved changes, do you want to quit?");

And further execution goes on user confirmation, Yes or cancel.(Native jquery buttons).
My need was to have three buttons,Yes ,No and Cancel. I did that like this.
 var question = "There are some unsaved changes, do you want to quit?";
            confirmation(question).then(function (answer) {
                // var ansbool = Boolean.parse(answer.toString());
                var r = answer.toString();
                alert(r);
                if (r == "true") {
                   .....
                    return true;
                }
                else {
                   ....
                    return false;
                }
            });

function confirmation(question) {
    var defer = $.Deferred();
    $('

')
        .html(question)
        .dialog({
            autoOpen: true,
            modal: true,
            title: 'Confirmation',
            buttons: {
                "Yes": function () {
                    defer.resolve("true"); //this text 'true' can be anything. But for this usage, it should be true or false.
                    $(this).dialog("close");
                },
                "No": function () {
                    defer.resolve("false"); //this text 'false' can be anything. But for this usage, it should be true or false.
                    $(this).dialog("close");
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            }
        });
    return defer.promise();
};

It shows me the message having these three buttons.But also closes the main popup window.I want it when user clicks on Yes ,No ,then it closes.After clicking.
Thanks in advance.
Comment: When are you calling `confirmation`?
Comment: @FritsvanCampen please see the second line of my code.  confirmation(question).then(function (answer) {..
Comment: This happens, since your dialog in the second snippet is not really modal. If you're calling the "modal dialog" in an `onbeforeunload` eventhandler, the page's closing process doesn't wait the modal to be executed, instead it terminates the page.
Comment: I think issue is not with the confirmation.It is just that first i have a confirm and now i have a dialog box.Confirm stops the execution until ant button is pressed.But this case is not with dialog.
Comment: @Teemu can you please edit my code or give an example.
Comment: `confirm()` is really executed modal, i.e. it does block the execution of the script untill it's closed, custom dialogs are not. Use `showModalDialog()`, if you need more content to the dialog than you can get in confirm box. However, using any box, you can't directly prevent the page to close, you can only trigger another prompt asking user if he wants to leave the page.
Comment: The native `confirm` blocks execution, like `alert`. Is that what you mean?
Comment: @FritsvanCampen I want dialog box to work like confirm.
Comment: @EHS You can't, in JS there's no way to create a `div` which could block the execution of the rest of the script.
Comment: @Teemu so how can I solve my problem.
Comment: @EHS You could use [`showModalDialog()`](https://developer.mozilla.org/en-US/docs/Web/API/Window.showModalDialog), but you can't automatically prevent the page to be closed. It's simply not allowed by browsers due to the security reasons.
Comment: ok thx all..I work on it
Answer: This happens because your confirmation call just drops through, it doesn't wait for an answer.  The only way I know of to do this is to place the action inside the confirmation:
UI.confirmDialog('Record will be removed...Continue?').done(function () {
            //perform the desired function here
            return false;
        }).fail(function () {
            return false;
        });

Comment: Can you please edit my code.Because I am not getting and getting confused in this that how I will put these three buttons in UI.ConfirmDialog.
Comment: Leave your confirmation function alone and then:

    confirmation("There are some unsaved changes, do you want to quit?").done(function(answer) {
      if (answer === "true") {return true };
      elseif (answer === "false") { return false };
    }).fail(function() { return false;
    });

Or something like that, play around with the combination until it works.  Main thing is to use the "done" attribute.

Popup not waiting for response to close


Display two Views blocks with equal height

Question: I have created two Views Blocks "NEWS" and  "BLOG", which resides side by side on my front page.
Both the views have 20 contents (but can be any number) in it and a pager. How do I display contents in views block, so that the both views end up with equal height regardless of number of contents displayed.
Comment: Displaying dynamic number of contents in views? why do you think this is off topic?
Comment: @Rupesh Since there is a module that could be used, I would leave the question open, as there is a Drupal-specific answer. The suggested module cannot be used on WordPress, so the answer is not as generic as merely using CSS styles.
Comment: This would normally be a HTML/CSS question, but one of the answers that was here by the time I handled the flag pointed to a Drupal-specific answer that may serve  future readers, so I am going to leave it.
Answer: Try using the equal heights module

This module implements a jQuery Equal Heights plugin that can equalize
  the height of the elements of the specified class.
To use it, give the elements the same class, then go to the
  administration interface and add this class (separate multiple classes
  by a space). By default, it sets the height to the height of the
  tallest element but you can also specify minimum and maximum height.

To use the just give both the blocks the same class and add the admin name in the admin interface of the module and then js will do the rest.
Comment: You may need to combine this with Block Class to get the classes onto the blocks that views creates.
Comment: @MPD  "equal height" + "Block class"  great solution Thank you.
Answer: Installing module to achieve small task is bit too much in my opinion.
I would rather apply equal heights JS library https://github.com/mattbanks/jQuery.equalHeights and following script to the main JS file.
<code>$('.yourelements').equalHeights();
</code>
This function will calculate the tallest container of the N-containers and apply in-line css height attribute to all the containers to match equal heights. So you don't have to set height as you can't predict the actual height.
Answer: Get the css ID of blocks using Firebug write css like
<code>#block-search-form, #block-system-navigation {
    height: 200px;
}
</code>
Answer: If you don't want to use a Module or Plugin I completed this with Jquery. Your views need to have the same class and the below simply looks at each of them, decides which one is higher and sets both their height to the highest value.
<code>  function equalHeight() {
   var height = 0;
   var $items = $('.item-blocks');
   $items.each(function() {
    if($(this).height() > height) {
      height = $(this).height();
    }
  });

  $items.css('height', height);
 }
</code>


How can I alter Easy Breadcrumb?

Question: I want to remove certain element of breadcrumb on certain condition. I tried theme_preprocess_breadcrumb($variables). The condition and logic works fine here but doesn't reflect on viewing page. I tried this module_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb) – same issue. Code here doesn't reflect on viewing page, though printing variables in both methods gives me expected result but not on viewing page. I need help.
function theme_preprocess_breadcrumb($variables) {
// Removing last element of breadcrumb
if ( $variables['breadcrumb'] ) {
$currentUrl = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$key = 'find this';
$countElements = count($variables['breadcrumb']);
if (strpos($currentUrl, $key) == true) {
  unset($variables['links'][$countElements-1]);
  unset($variables['breadcrumb'][$countElements-1]);
  kint($variables['breadcrumb']);kint($variables);die;
}
}
return $variables;
}

Comment: You are not passing variables by reference. So the array is not being modified.
Comment: Maybe start by explaining what breadcrumb you have right now, and what breadcrumb exactly you want. Then also include the code that didn't work. Please edit your question accordingly. Many thanks
Comment: You should read the documentation for PHP's `strpos` function
Comment: Again, you need to add the & pass by reference, NOT a return. https://drupal.stackexchange.com/questions/209231/breadcrumb-preprocess-from-module
Comment: @Kevin thanks it worked. for now
Comment: I am using https://www.drupal.org/project/easy_breadcrumb i want to remove some element on certain condition logic is build and works well if i use above mention hooks and print the variable there. But it doesnt applies on viewing the page.
Comment: This this out https://drupal.stackexchange.com/questions/288635/getting-call-to-a-member-function-getname-on-null-in-custom-breadcrumb/288639#288639 there is two ways to alter breadcrumb, otherwise if you have specific use case, as @leymannx mentioned in comment add your code that doesn't work !
Comment: I want to remove the breadcrumb last element on the condition mentioned in the function above what wrong i am doing here?
Comment: But when i am printing the variable in the last line it gives me desired result here.
Comment: It doesn't matter there, you need to specify the argument as &$variables as the hook documentation states. There is no return, it is modified in place.
Comment: As far as I remember Easy Breadcrumb offered a setting to exclude the current page from the trail, no?
Comment: @leymannx Yes but i want wanted it to exclude on certain condition not for all pages.
Answer: As it mentioned in the comment section the $variables should passed by reference take a look at hook_preprocess_HOOK documentation page.
And also read about strpos to adapt your condition, here is an example of code to remove the last breadcrumb element in case url contain the word article for instance.
/**
 * Implements hook__preprocess_HOOK().
 */
function YOURTHEMENAME_preprocess_breadcrumb(&$variables) {
  // Removing the last element of the breadcrumb
  if ($variables['breadcrumb']) {
    $current_path = \Drupal::service('path.current')->getPath();
    // Get the real path even if it has an alias.
    $real_path = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
    $key = 'article';
    if (strpos($real_path, $key)) {
      // Remove the last element.
      array_pop($variables['breadcrumb']);
    }
  }
}

How can I alter Easy Breadcrumb?


Is value "in" some other values, in objective-c

Question: Coming from an extremely spoiled family upbringing (turbo pascal, python, ruby) I'm a bit puzzled when it comes to doing all the household chores myself.
Yesterday was one of these days where I just did not find myself a solution. I had to check whether a value matches one of some other values.
 x = some_function_return_value();
 if x in (1,4,17,29,35):

That's how I used to write it. Now with Objective-C I obviously can't do that. And I searched the  old google, but found no answer, and the old manual, and nothing there, so how do you do this in Objective-C, without doing something cranky like the following?
 if (x == 1 || x == 4 || x == 17 || x == ...) {

Edited: in this case it is an (int), I know for NSArray and NSString there are methods for this
Comment: Yeah, an NSSet is probably the closest thing -- still pretty clunky compared to the Pascal `in` (which none of the major C-based languages support).
Answer: If it's about integer values, you can use switch:
switch (x) {
    case 1:
    case 4:
    case 17:
    case 29:
    case 35:
        do_something();
        break;
}

Do not forget that in C/C++/Objective-C, the cases fall through to the next by default. You need to add break; statements to prevent that.
For non-integer values, you have to do long if statements with a lot of repetition as C doesn't provide syntactic sugar or features that many scripting languages have to abbreviate this.
Another way would be for example to prepare an array and then do:
if ([myArray containsObject:[NSNumber numberWithInteger:x]])

or even better, use an NSSet for that. This will work for most objects, for example it will also work with strings.
Comment: You beat me to it. One addition is that you can also use `...` to do things like `case 4 ... 8:` to include the range from 4 to 8.
Comment: I see... the switch is not shorter than the multi-comparison, and the object oriented style would go into something like this:

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], .... ... nil];
if ([myArray containsObject:[NSNumber numberWithInteger:x]]) {

both not more concise, aren't they?
Comment: No, neither is as concise as, say, Ruby or Python in this respect. Not even close.
Answer: There is a fast enumeration syntax in objective C that uses "in" to loop over collections, however given it requires converting your int values to NSNumbers, it's probably easier to use C here
BOOL success = NO;
int size = 5
NSInteger numbers[size] = {1,4,17,29,35};

for (int i = 0; i < size; i++) {
    if (yourValue == numbers[i]) {
        success = YES;
        break;
    }
}

if (success) {
    /* do your stuff */
}

admittedly not as nice as python...
Comment: Problem with this is that the compiler can't optimize it as nicely as a `switch` or large `if`. But it sure would be faster than an `NSArray` or `NSSet` lookup.
Comment: As for the ANSWER: I chose this one, since jbat100 admitted it's not as concise as in e.g. python (and DarkDust said the same), never can be. Though he tried to solve the question with the (int) in mind. I admit: the only way I could come up with this question is due to the fact that I did not fully comprehend the nature of Objective-C. If I would have, I probably would not have run into my problem in the first place. So as it is, it seems there is no short solution. Instead, one would have to find save grounds in the heavens of proper NS Objects.
Answer: Here's my silly program of the day:
bool int_exists_in_array(const int n, const int a[], const size_t elementCount) {
    return (0 != elementCount) &&
      (n == a[0] || int_exists_in_array(n, a + 1, elementCount - 1U));
}

so this:
if x in (1,4,17,29,35):

becomes:
const int a[] = { 1, 4, 17, 29, 35 };
if (int_exists_in_array(x, a, sizeof(a)/sizeof(a[0]))) {
  ...
}

Comment: First I have to say: you guys are amazing. I live on the countryside and nobody here has any understanding what I am doing in my work. That means I never talk to any of my pals or relatives about what I am doing in my work, not once in the last 10 years. However, here I can post a question and within 10 Minutes I have 7 (or so) professionals, from all over the world, who engage in a lively discussion. In this VERY brief time we create a rich page with valuable information. Very impressing.
Comment: how would you call this one? int_exists_in_array(const int [1,2,4,67])? maybe I can put this in a convenience helper section of the class ...
Comment: @me1974 oh, i added an example afterwards. this is c so the array's size must be managed by you. you can use the sizeof in some cases, or you must pass around an element count or a struct which represents an array.
Comment: +1, quirky ;-) Though the recursion bothers me (at least it's a tail recursion that the compiler might optimize).
Comment: @DarkDust yup - it should be tail optimized, and i did say it was silly =) it could be easily converted to a loop if recursion were an issue.
Answer: You can use NSSet in addition with NSValue.


Prove the maximum of two integrals of functions is less than or equal to the integral of the maximum of two functions

Question: Prove that on an interval $[a,b]$, if $f$ and $g$ are integrable, than $\max(f,g)$ is integrable and
$$\max(\int_a^b f(x)dx, \int_a^b g(x)dx) \leq \int_a^b \max(f(x), g(x))dx. $$
I proved the first part by
$$\max(a,b)=\frac{a+b+|a-b|}{2}$$
so
$$\max(f(x),g(x))=\frac{f(x)+g(x)+|f(x)-g(x)|}{2}$$
The absolute value, the sum, and the difference, and the multiplication by a constant of Riemann integrable functions are all Riemann integrable, hence the max is also integrable.
Can anyone help with the second part? Many thanks!
Answer: We have
\begin{align*}
f\leq f\vee g,
\end{align*}
so by taking integrals both sides, we have
\begin{align*}
\int f\leq\int f\vee g,
\end{align*}
similarly,
\begin{align*}
\int g\leq\int f\vee g,
\end{align*}
so
\begin{align*}
\int f\vee\int g\leq\int f\vee g.
\end{align*}
Comment: @Riaz, try $f(x)=x$ and $g(x)=-x+1$ on the interval $[0,1]$.
Comment: $\vee$ means $\max$ here.
Comment: Can we have strict inequalities in some cases?


How to get the reference of a cell based on two filters in Google Sheets?

Question: I am parsing JSON data from a FB Ads Campaign through Graph API in Google Sheets. I have multiple sheets for different ad insights based on a timeframe (today, yesterday, 7 days, 30 days) and a dashboard that shows a snapshot of the most important data like the # of conversions and cost-per-conversion for each campaign.
On the dashboard page, I want to match the Adset ID with the value next to cells that contain 'complete_registration' on an insight page.
This is the current formula I have
=INDIRECT(INDEX("h"&filter(ROW('Todays Insights'!G1:G901),'Todays Insights'!G1:G901="complete_registration")),1)
This works for referencing the first time 'complete registration' is used... but I want the value for each Adset
For example -> IF Column A has Adset_ID and Column B has Complete registration then index value in C
What formula would accomplish this in Google Sheets?
Picture Example
Comment: Hi. Would you share a sheet with this example? It's hard to help without it.
Comment: I have added a picture. Thank you!   https://i.stack.imgur.com/fT95w.jpg
Answer: O.K. I think I get it. You want to get 2 coulmns as a result - B and column H when C is registration_complete.
Try:
<code>=filter({'Todays Insights'!a1:a,'Todays Insights'!h1:h},'Todays Insights'!c1:c="complete_registration")
</code>
Comment: Thank you! I tried your formula, but it didn't seem to pull the right info. Here is the formula that ended up working for me: =DGET('Sheet Name'!$A$1:$N$500,"Actions Value",{"Adset ID","Actions Action Type";C24,"lead"})
Answer: Here is the formula I used that works:
=DGET('Sheet Name'!$A$1:$N$500,"Actions Value",{"Adset ID","Actions Action Type";C24,"lead"})


Exercises for reducing dependency on metronome

Question: On this site, we often tell intermediate musicians to slow things down and practice with a metronome to establish a good sense of time. I have the opposite problem. I spent my college years practicing everything with a metronome and writing down the tempo of each exercise in a practice journal. As a result, I feel a little stranded without it, and when I sat down to play my scales this morning, I was surprised to find that I couldn't "remember" my comfortable speed without referring back to the metronome.
What generic exercises can advanced musicians use to reduce their dependency on the metronome?
I have occasionally done the one where you set the metronome to cut out for a bar and try to come back in on the beat, but the main purpose of this exercise is to improve your sense of "external" time (your ability to match an externally imposed meter and play in time with other musicians).
I am looking rather to improve my "internal" time, i.e. the ability (in a rubato context) to traverse between tempos in a way that's expressive and controlled and (in a nonrubato context) to start out at the right tempo without referring to a reference beat.
Comment: Is the problem the same on all instruments? What sort of music? Playing with others, it mght be they who are losng time not you! Been there too often!
Comment: What instrument, and what are you like when playing with others?
Comment: I'm a multi-instrumentalist and looking for generic exercises based on scale patterns, rhythms, etc that can be applied to any instrument. When playing with others I... am not satisfied with my sense of time. I lose precision easily if someone is playing behind or ahead of the beat, or if the drummer tries something fancy.
Comment: Dupe possiblity - 'How can I improve my sense of time?'
Comment: Yes, I had a look at that question--the top answer includes the metronome cutout exercise I mentioned. But the half of my question that I feel hasn't been answered yet has to do with developing expressive capacity through tempo, including (perhaps especially) in a rubato context.
Answer: This may come over as weird.
Continue using the metronome!
But (there's usually a but...) Use it in several different ways - which maybe you haven't yet.Take a song at, say, 120bpm. Set the metronome at 60 instead. Set it at 30. Play the song as normal, but there won't be as many reference points t follow.
Back to the 120. This time, don't think the click is on the beat, but it's the '&' in between. Drop it down to 60. Or 30. At those points, come to a decision what a click actually represents. At 60, it could be beat 2, or the & between 3 and 4. There are many many specific bits of the bar it could be! Down to 30, and there's very little holding you together, but decide where in the bar that one-click-per-bar it is, and count, out loud if needed, for that to remain the same throughout.
This could be done with simple rhythm patterns with chords on guitar, with a single note pattern on most other instruments.
Another idea is to take the rhythm/tempo on with your body. Some tap a foot, some nod a head, some are virtually dancing while playing - a joy to watch, and it sure keeps their timing good.
EDIT: to address your 'rubato' concern. I don't know how this can happen. When we stretch and squash the timing, it's out - by definition - anyway. Doing that with others may well throw them, unless you're the vocalist, and they're all keeping strict time and you're in and out. You can do that, but you must be aware of where beat one in the bar is at all times.(Shades of my metronome reference). Stray too far, and it does sound like you don't know what you're doing!
Answer: If the problem is to remember absolute speeds without getting a reference speed from a metronome, my trick for that is to utilize well-known songs that have lyrics. For example, there's a song I remember well that's about 100 bpm and starts immediately with lyrics - I sometimes think about the beginning of that song to calibrate my speed to about 100 bpm. Or there might be a particularly fast sung passage in a song - before counting-in the song I think about the lyrics of that passage to make sure that's the upper speed limit.
Maybe you remember some of these songs: (tempos might be off a couple of ticks, but you get the idea)

Show Must Go On: 84 bpm
Rosanna: 86 bpm
Africa: 93 bpm
Take My Breath Away: 96 bpm
Big in Japan: 99 bpm
Never Gonna Give You Up: 114 bpm
Long Train Runnin': 115 bpm
I Should Be So Lucky: 116 bpm
You're My Heart, You're My Soul: 120 bpm
Living on a Prayer: 123 bpm
YMCA: 126 bpm
Black Friday (Steely Dan): 130 bpm
Runaway (Bon Jovi): 154 bpm

Build your own list. :)
Edit. After reading your follow-up comments, I think what you aim for is a better sensitivity to using tempo as an artistic device. Music is about delivering and inducing emotions, and tempo is an important aspect in that, but you feel that it's not completely in your control - you sometimes inadvertently deliver or support a tempo that's inappropriate for the piece or the situation. When you get the speed given as a numerical tempo, or from other musicians' playing speed, you're able to follow, but you'd like to be more active and considerate with tempo.
Pay attention to the feelings that playing the piece with that particular tempo creates. For me, lyrics and how fast they're pronounced create emotions quite naturally, because there's a relation to spoken language, which is (supposedly) tightly connected to emotions. Similar "reference feelings" can be had by trying to dance to the music. You could think about your playing motions as dancing, if you can't actually dance along. ;) How relaxed are your motions? Can you add groovy ghost notes? The point is to try to live the music with your body, and not look at it as a purely intellectual thought process.
In my opinion being a good "conductor" with tempo is not an easy thing to master. Many times when listening to a recording of a gig, I've got second thoughts - did we play this too fast or too slow after all? It felt good on the stage... It's the same with all communication - for some people it's very difficult to sense what kind of emotions their actions are inducing in other people.
Comment: My problem is a little more abstract than this, actually: recalling a song at a certain tempo is just another way of getting a "reference speed." Rather, I'm trying to develop greater *sensitivity* to tempo differences, so without any numbers ever entering the picture, I'd like to become more accurate at remembering "What tempo did we play this at in rehearsal yesterday?" Often, I find that when I sit down to practice alone material that I'd been working on with a band, I find the music sits at a different tempo. Nonetheless, +1 for a well-written post that partially addresses the question.
Answer: There's a software tool that might help you. It's called "Absolute Time Trainer", it's 100% free, and you can use it to:
A) Listen to a beat, and learn to detect the exact speed
B) Learn to tap precisely at any given speed (with visual feedback)
The overall purpose of the tool is to help you develop an "instinct" of what is the actual speed of any beat you hear, and also to be able to beat any given time with good precision, without an external cue.
This tool is included in the "Musician Training Center" software ("Tools" section in the main menu). It can be downloaded at http://www.micrologus.com/download
I have personally worked on creating this software, so I'm probably biased, but I think you might find it useful and this particular tool is free anyway. Here's a screenshot of when you are practicing "time leading" i.e. tapping at a given speed.
Answer: I work--worked, thanks Coronavirus--in a "strict tempo" band where we had to stay within a couple of beats per minute of several tempos.
I use several methods to maintain correct tempo--including using a metronome.
First method: I would set a metronome on my phone when I'm walking and walk to the beat.  We all tend to walk at a particular tempo but we can change this tempo.  First, I learned my natural tempo.  Then I would change my gait to match different tempos.  When I play music, I always tap one foot.  Walking to tempo trains me to tap my foot to different tempos.
Second method: Certain often-played reference tunes have a tempo that I can recall.  To establish tempo, I would play the reference tune in my head and start tapping my foot to that tempo. Frequently the reference tempo is the chorus to a song I sing a lot. Singing in my head coordinates both my breathing and my foot so there's two sources for the tempo.
Third method: I have an Android phone and use the liveBPM tempo detector to detect the beat as I'm playing.  I play songs over and over again with the liveBPM app on and adjust my playing so that I'm playing at the required tempo.  Then I start looking away from the app for longer and longer periods of time, checking my tempo less and less. Eventually the tune and the tempo become so linked that I have another tempo reference tune.
Comment: Worked for decades in strict tempo bands. Get a good drummer, off we go! If he can't get it right, no-one can! Never really found the secret though...
Answer: I've played the Drums for almost 10 years and I started playing the guitar about 2 years ago. To me it's kind of easy to keep the Tempo, probably because of playing the drums. But what really helps me keeping the tempo is always tapping my feet. A habit which I learned while playing the drums. You always keep your Hi-Hat Tapping so you always have your Tempo. Start listening to a Metronome in a certain tempo for a few bars and then Tap your feet along with it. And most importantly count to it. 1, 2, 3, 4, 1, 2, 3, 4. You can then restart the Metronome on the 1 and see if you kept the tempo. And what I think would also work is, as already mentioned above, pick out a song that you're able to play and listen to it first. Get a feel for the Tempo and then try it with tapping your feet along with it. Hope I could help you out with that!


Contradiction between memorylessness of random walk to straight forward calculation

Question:
A drunk person is in place $x=0$ in time $t=0$. Every second he moves
  forward one meter in a probability of $\frac{1}{2}$ or stays in his
  place in a probability of $\frac{1}{2}$ (his decisions are
  independent). In addition, every second he can pass out in a
  probability of $\frac{1}{2}$ (also independently).
Mark: $X$ - the distance he reaches.

A. Find the expected value of $X$.
B. Given he reaches at least 2 meters, find the expected value of $X$.
My solution:
A. $Y$ - number of seconds until he passes out. $Y\sim Geo(\frac{1}{2})$
$X|Y\sim Bin(y,\frac{1}{2})$
Therefore: $E(X)
=E(E(X|Y))=E(\frac{Y}{2})=\frac{1}{2}\cdot E(Y)=\frac{1}{2}\cdot2=1$
B. Since it is a random walk, $E(X|X\ge2)=E(X)+2=3$
But:
$P(X=0)=\sum_{y=1}^{\infty}P(X=0|Y=y)\cdot P(Y=y)=\sum_{y=1}^{\infty}(\frac{1}{2})^{y}\cdot(\frac{1}{2})^{y-1}\cdot(\frac{1}{2})=\sum_{y=1}^{\infty}(\frac{1}{2})^{2y}=\frac{1}{3}$
$P(X=1)=\sum_{y=1}^{\infty}P(X=1|Y=y)\cdot P(Y=y)=\sum_{y=1}^{\infty}\binom{y}{1}\cdot(\frac{1}{2})^{y-1}\cdot(\frac{1}{2})\cdot(\frac{1}{2})^{y-1}\cdot(\frac{1}{2})=\sum_{y=1}^{\infty}y\cdot(\frac{1}{2})^{2y}=\frac{4}{9}$
$\Rightarrow P(X\ge2)=1-\frac{1}{3}-\frac{4}{9}=\frac{2}{9}$
$E(X)=\sum_{x\in Rx}x\cdot P(X=x)=E(X|X=0)\cdot P(X=0)+E(X|X=1)\cdot P(X=1)+E(X|X\ge2)\cdot P(X=2)$
So, $1=0+\frac{4}{9}+\frac{2}{9}\cdot E(X|X\ge2)$ and $E(X|X\ge2)=2.5$.
Where is my mistake?
Comment: Does he pass out before or after the move (if any)?
Answer: Let us assume the person passes out (or not) after the move, so the game has at least one move.  Now, when the person reaches $X=2$, there is a 50% probability that the game ends immediately, as he will pass out immediately after reaching $X=2$; if he doesn't, then, as you have realized, the game effectively restarts at $X=2$.  So, we have:
$$\mathbb{E}X|X\geq2 = 2 + {1 \over 2}\mathbb{E}X = 2.5$$
which matches your second derivation.
If, on the other hand, the person passes out before the move, there is, essentially, one extra "pass out" check at the beginning of the game.  After that, the game proceeds as in the first case - move decision, pass out check, move decision, etc.  Consequently, the expected distance the person travels is half what it is in the first case:  $\mathbb{E}X = 1/2$, but the expected distance the person travels conditional upon reaching $X=2$ is still $2.5$.


Proving $\{a\}$ is a set

Question: I recently came across the following post Proving $\{a\}$ is a also set given that $a$ is a set. Introduction to Set Theory..
While I understand the answer given I am still unsure whether or not the proof given in the OP is correct, i.e. if it is legitimate to use the axiom of extensionality. It seems to me that the answer given only suggests that there is no need to use the axiom of extensionality, not that this is not permitted.
Any help would be appreciated. Many thanks!
Comment: How do you define $\{a\}$?
Comment: Ah! I see it now! The axiom of extensionality is what makes the notation $\{a\}$ well-defined. That is I need the axiom of extensionality to prove that there is *only* one set whose only element is $a$. Is this correct?
Comment: Well, yes, but that's not everything. You need to use the axiom of pairing too.
Comment: Axiom of pairing tells me that there is a set whose only element is $a$ and the axiom of extensionality tells me this set is unique. Do you mean that I need the axiom of pairing for uniqueness?
Comment: Are you satisfied by the linked proof that $\{ a \}$ is a set? If so, how you want to prove uniqueness? If $a=b$, then $\{ a \} = \{ b \}$?
Comment: By the axiom of pairing there is a set whose only element is $a$. Let $x,y$ be two such sets. Then by extensionality $x=y$. Hence we can define $\{a\}$ to be this set.
Comment: Correct. More specifically, Pairing axiom gives a pair-set for each $a,b$ and by Extensionality we prove that it is unique. Thus, we can "name" it **the** pair $\{ a,b \}$. Applying this to the pair $\{ a,a \}$, we define $\{ a \}= \{ a , a\}$.
Answer: A set can be defined in three ways:
1- By extension
2- By comprehension
3- By Venn diagram.
In your case $ \{a\} $ is a set defined by extension. it contains only one element which is $ a$.
In set Theory, same objects can be seen as sets or as elements.
$$\{a\} \text{ is an element of the set } \{\{a\}\}$$
Comment: Venn diagrams don't define sets.
Comment: Also in set theory **everything** is seen as a set.
Comment: @AsafKaragila Every set is an element.
Comment: Yes, but that goes without saying.
Comment: @AsafKaragila I am fan of Liverpool : You will never walk alone.

Proving $\{a\}$ is a set


Proof of theorems (First Order Logic)

Question: Considering the list of axioms:
$(A1)$ - All Tautologies.
$(A2)$ - $(\forall x(\alpha \rightarrow \beta) \rightarrow (\forall x \alpha \rightarrow \forall x \beta)) $.
$(A3)$ - $(\forall x \alpha) \rightarrow [\alpha]^{t}_{x} $ if x is free for t in $\alpha$.
$(A4)$ - $\alpha \rightarrow (\forall x \alpha) $ if x is not free in $\alpha $.
$(A5)$ - $ x = x$
$(A6)$ - $(x=y) \rightarrow (\alpha \rightarrow \beta)$ if $\beta$ if obtained by substitution of at least one occurrence of x free for y in $\alpha$.
I am trying to write a proof for some theorems. However, I am a little confused.
$ \vdash (\forall x_1(R_1^1(x_1) \lor R_2^1(x_1))) \rightarrow (R_2^1(x_1) \lor R_1^1(x_1))  $
For this one, could I use (A3), given that $\forall x_1$ on the left side of $\rightarrow$?
$ \vdash R_1^1(c_1) \rightarrow (R_1^1(c_2) \rightarrow  (R_1^1(c_1) \land R_1^1(c_2))) $
For this one, could I use the tautology $\alpha \rightarrow (\beta \rightarrow(\alpha \land \beta))$, given that $R_1^1(c_1)$ is the same relational symbol, but applied to different constants?
$ \vdash \forall x_1(\forall x_2(R_1^1(x_1) \rightarrow (R_1^1(x_2) \rightarrow R_1^1(x_1))))$
Same question as before (combining the first ones), could I use the tautology $\alpha \rightarrow (\beta \rightarrow \alpha)$ and then (A4)?
Answer: First: Yes, though you have to combine (A3) with a tautology in order to get to swap the $R_2^1$ and $R_1^1$ disjuncts in the conclusion.
Second: Yes, this is an instance of (A1).
Third: No, (A3) will let you remove a $\forall$ from something you've already proved, not add it. In fact I'm almost sure your axioms are not enough to prove this, if all you have is Modus Ponens. Specifically, the axioms would all be true under a variant semantics where $\forall x\alpha$ always evaluates to false when $x$ is free in $\alpha$ (and MP preserves this truth). Since your goal is not true in this that variant semantics, it can't be proved.
Are you sure you don't have a separate Generalization rule in addition to your axioms and MP?
Comment: Sorry, i meant (A4) on that one, will edit. So, even with A4, I can't use it there, do I need the Generalization Theorem (GT) on that one? Considering the first, (A3) should change $x_1$ to $x_1$, is that correct?
Comment: @LuizS.: I'm not exactly sure what your "Generalization Theorem" says, but if it says what it sounds like it ought to, then it _is not true_ if all you have is tha axioms you have shown here plus MP.
Comment: It says: Let $\Gamma$ be a subset of formulas of a first order logic language such that the variable x is not free in all formulas of $\Gamma$. Then $\Gamma \vdash \alpha$ whenever $\Gamma \vdash \forall x \alpha$
Comment: @LuizS.: Ah, that looks true, but it goes in the wrong direction -- it _also_ requires you already to have proved $\forall x\alpha$ before it applies. (In fact what it states is just a simple application of A3 with $t=x$).
Comment: So I can't use it directly on the third case?
Comment: @LuizS.: No -- I strongly suspect you must have misquoted or forgotten something here. (For example when you wrote "whenever" above, did your source actually say "if and only if"? That would yield a claim you can use, but on the other hand I don't think it would be _true_).
Comment: These are the axioms presented by Enderton (A Mathematical Introduction to Logic). There, Generalization Theorem says that If $\Gamma \vdash \phi$ and x do not occur free in any formula in $\Gamma$, then $\Gamma \vdash \forall x \phi$, is that different for what I've said before? Here, $\Gamma$ would be $\emptyset$ ?Thanks.
Comment: @LuizS.: What you said before was that if $\Gamma\vdash\forall x\phi$ then $\Gamma\vdash \phi$. I'm curious how he proves that theorem -- it is true for the usual first-order logic, but (as I keep saying) the rules you have quoted here do not seem to be strong enough for it to be true in _this_ system.

Proof of theorems (First Order Logic)


Access Violation ao Selecionar o arquivo XML - NFe

Question: Estou tentando selecionar os nós, mas está dando erro de Access Violation, o que eu poderia melhorar nesse código para não haver nenhum erro?
procedure TfrmDataB.sbtnAbrirClick(Sender: TObject);
var
  xmlNCab, xmlNItm : IXMLNode;
  //Nota Fiscal
  cNF, nNF, dEmi, verProc, serie : String;
  //emit + enderEmit
  cnpj, cpf, xNome, xFant, IE,
  xLog, nro, xBairro, cMun, xMun, uf, cep, cPais, xPais,
  fone : String;
  //prod
  cProd, xProd, uCom, qCom, vUnCom, vProd : String;
  function funcvarXML(xmlNTag : IXMLNode): WideString;
  begin
    if not (xmlNTag.ChildNodes.First = nil) then
      Result := xmlNTag.ChildNodes.First.Text;
  end;
begin
  //
  if not (opndlg_nfe.FileName = '') then Exit;
  // Lendo o arquivo pelas TAGs...
  if opndlg_nfe.Execute then
  xmldoc_nfe.LoadFromFile(opndlg_nfe.FileName);

  xmldoc_nfe.Active := true;
  // Leitura Dados da Nota Fiscal...
  xmlNCab := xmldoc_nfe.DocumentElement.childNodes.First.ChildNodes.FindNode('ide');
  if not (xmlNCab.ChildNodes.First = nil) then
  begin
    cNF := funcvarXML(xmlNCab.ChildNodes['cNF'        ]); // Código sequencial NFe
    nNF := funcvarXML(xmlNCab.ChildNodes['nNF'        ]); // Número da Nota Fiscal
    dEmi := funcvarXML(xmlNCab.ChildNodes['dEmi'      ]); // Data Emissão Nota Fiscal
    verProc := funcvarXML(xmlNCab.ChildNodes['verProc']); // Descrição da Nota Fiscal
    serie := funcvarXML(xmlNCab.ChildNodes['serie'    ]); // Série da Nota Fiscal
  end;

  // Leitura Dados do Fornecedor...
  xmlNCab := xmldoc_nfe.DocumentElement.childNodes.First.ChildNodes.FindNode('emit');
  if not (xmlNCab.ChildNodes.First = Nil) then
  begin
    cnpj := funcvarXML(xmlNCab.ChildNodes['CNPJ'   ]); // CGC Fornecedor
    cpf := funcvarXML(xmlNCab.ChildNodes['CPF'    ]); // CPF Fornecedor
    xNome := funcvarXML(xmlNCab.ChildNodes['xNome'  ]); // Razão Social do Fornecedor
    xFant := funcvarXML(xmlNCab.ChildNodes['xFant'  ]); // Nome Fantasia
    IE := funcvarXML(xmlNCab.ChildNodes['IE'     ]); // Inscrição Estadual
    // Leitura Dados Endereços do Fornecedor...
    xmlNItm := xmlNCab.ChildNodes['enderEmit'];
    if not (xmlNItm.ChildNodes.First = Nil) then
    begin
      xLog := funcvarXML(xmlNItm.ChildNodes['xLgr'   ]); // Logradouro
      nro := funcvarXML(xmlNItm.ChildNodes['nro'    ]); // Número
      xBairro := funcvarXML(xmlNItm.ChildNodes['xBairro']); // Bairro
      cMun := funcvarXML(xmlNItm.ChildNodes['cMun'   ]); // Código Município IBGE
      xMun := funcvarXML(xmlNItm.ChildNodes['xMun'   ]); // Nome Município
      uf := funcvarXML(xmlNItm.ChildNodes['UF'     ]); // Unidade Federação
      cep := funcvarXML(xmlNItm.ChildNodes['CEP'    ]); // CEP
      cPais := funcvarXML(xmlNItm.ChildNodes['cPais'  ]); // Código Pais BACEN
      xPais := funcvarXML(xmlNItm.ChildNodes['xPais'  ]); // Nome Pais
      fone := funcvarXML(xmlNItm.ChildNodes['fone'   ]); // Telefone
    end;
  end;

  // Leitura Dados Itens da Nota Fiscal...
  xmlNCab := xmldoc_nfe.DocumentElement.childNodes.First.ChildNodes.FindNode('det');
  while not (xmlNCab = Nil) do
  begin
    xmlNCab.ChildNodes.First.ChildNodes.FindNode('det');
    xmlNItm := xmlNCab.ChildNodes['prod'];
    if not (xmlNItm.ChildNodes.First = Nil) then
    begin
      cProd := funcvarXML(xmlNItm.ChildNodes['cProd'  ]); // Código do produto CFOP
      xProd := funcvarXML(xmlNItm.ChildNodes['xProd'  ]); // Nome do produto
      uCom := funcvarXML(xmlNItm.ChildNodes['uCom'    ]); // Sigla unidade da embalagem
      qCom := funcvarXML(xmlNItm.ChildNodes['qCom'    ]); // Quantidade do produto (4dec,S/M)
      vUnCom := funcvarXML(xmlNItm.ChildNodes['vUnCom']); // Valor unitário do produto (4dec,S/M)
      vProd := funcvarXML(xmlNItm.ChildNodes['vProd'  ]); // Valor total do produto (2dec,S/M)
    end;
    xmlNCab := xmlNCab.NextSibling;
  end;

end;

Erro nesta linha if not (xmlNCab.ChildNodes.First = nil) then
Segue estrutura do .XML
- <ide>
    <cUF>00</cUF>
    <cNF>0000000</cNF>
    <natOp>--------------------</natOp>
    <indPag>0</indPag>
    <mod>55</mod>
    <serie>1</serie>
    <nNF>1455</nNF>
    <dEmi>2012-07-28</dEmi>
    <tpNF>1</tpNF>
    <cMunFG>0000000</cMunFG>
    <tpImp>1</tpImp>
    <tpEmis>1</tpEmis>
    <cDV>2</cDV>
    <tpAmb>1</tpAmb>
    <finNFe>1</finNFe>
    <procEmi>0</procEmi>
    <verProc>22.214.171.124</verProc>
  </ide>
- <emit>
    <CNPJ>00000000000000</CNPJ>
    <xNome>SUPER. xxxxxxxx</xNome>
    <xFant>SUPERMERCADO xxxxxxxxx</xFant>
  - <enderEmit>
      <xLgr>ALGUEM</xLgr>
      <nro>163</nro>
      <xBairro>CENTRO</xBairro>
      <cMun>000000</cMun>
      <xMun>XXXXXXXXXX</xMun>
      <UF>XX</UF>
      <CEP>00000000</CEP>
      <cPais>1058</cPais>
      <xPais>BRASIL</xPais>
      <fone>0000000000</fone>
    </enderEmit>
    <IE>20000000</IE>
    <CRT>3</CRT>
  </emit>
- <dest>
    <CNPJ>00000000000000</CNPJ>
    <xNome>xxxxxxxxxxxxxxxxxxxxxxxx</xNome>
  - <enderDest>
      <xLgr>xxxxxxxxxxxxxxxxxxxxxxxxxxx</xLgr>
      <nro>163</nro>
      <xBairro>xxxxxxxxx</xBairro>
      <cMun>0000000</cMun>
      <xMun>xxxxxxxxxx</xMun>
      <UF>xx</UF>
      <CEP>00000000</CEP>
      <cPais>1058</cPais>
      <xPais>BRASIL</xPais>
      <fone>0000000000</fone>
    </enderDest>
    <IE>200852949</IE>
    <email>email@example.com</email>
  </dest>
- <det nItem="1">
- <prod>
    <cProd>00000000001</cProd>
    <cEAN />
    <xProd>LARANJA</xProd>
    <NCM>08109000</NCM>
    <CFOP>5102</CFOP>
    <uCom>KG</uCom>
    <qCom>1.0000</qCom>
    <vUnCom>1.2000000000</vUnCom>
    <vProd>1.20</vProd>
    <cEANTrib />
    <uTrib>KG</uTrib>
    <qTrib>1.0000</qTrib>
    <vUnTrib>1.2000000000</vUnTrib>
    <indTot>1</indTot>
  </prod>

Comment: Você debugou? Em qual instrução exatamente ocorre o erro?
Comment: Antes de começar esta instrução, eu clico, e o Open Dialog abre, porem, antes de executar a instrução, ele para. Vou debuggar novamente, para apresentar a linha.
Comment: @Filipe.Fonseca, coloquei a linha do erro no final da pergunta...
Comment: @Filipe.Fonseca, retirei os ifs e ele apresentou o mesmo erro, porem, nesta linha `cNF := funcvarXML(xmlNCab.ChildNodes['cNF'        ]); // Código sequencial NFe`
Comment: Posta a estrutura desse xml por favor.
Comment: @Filipe.Fonseca, a estrutura está na pergunta.
Answer:
Erro nesta linha if not (xmlNCab.ChildNodes.First = nil) then

Esta linha contém 3 objetos. Um deles está nil;
xmlNCab ou ChildNodes ou First está nil.
Você pode testar todos pra ver qual é.
Depois reveja a sua lógica, pra resolver o problema antes de chegar nesta linha.
Comment: O erro está exatamente aqui, ta retornando o access violation `xmlNCab.ChildNodes.First`
Comment: Tentei dar um showmessage para mostrar o que ele tava pegando nesta linha que comentei, e ele pegou isso `Element "NFe" does not contain a single text node`
Comment: de fato, tinha algo errado, pois tenho que selecionar todos os nós para então fazer algo para selecionar os valores, eu estava atropelando essas condições e por isso estava dando erros, vou postar a resposta.
Answer: Segue a resposta, código funcionando :
procedure TfrmDataB.sbtnAbrirClick(Sender: TObject);
var
  xmlNCab, xmlNItm, NoPrinc, NoXML , NoPai : IXMLNode;
  //Nota Fiscal
  cNF, nNF, dEmi, verProc, serie : String;
  //emit + enderEmit
  cnpj, cpf, xNome, xFant, IE, xLog, nro, xBairro,
  cMun, xMun, uf, cep, cPais, xPais, fone : String;

  //prod
  cProd, xProd, uCom, qCom, vUnCom, vProd : String;
begin
 //
  if not (opndlg_nfe.FileName = '') then Exit;

  // Lendo o arquivo pelas TAGs...
  if opndlg_nfe.Execute then
  xmldoc_nfe.LoadFromFile(opndlg_nfe.FileName);

  xmldoc_nfe.Active := true;

  //ShowMessage(xmlNTag.ChildNodes.First.Text);
  NoXML :=  xmldoc_nfe.DocumentElement.ChildNodes['NFe'];
  NoPrinc := NoXML.ChildNodes['infNFe'];
  // Leitura Dados da Nota Fiscal...
  xmlNCab := NoPrinc.ChildNodes.FindNode('ide');
  //ShowMessage(xmldoc_nfe.DocumentElement.ChildNodes.First.Text);

  cNF := xmlNCab.ChildNodes['cNF'].Text; // Código sequencial NFe
  nNF := xmlNCab.ChildNodes['nNF'].Text; // Número da Nota Fiscal
  dEmi := xmlNCab.ChildNodes['dEmi'].Text; // Data Emissão Nota Fiscal
  verProc := xmlNCab.ChildNodes['verProc'].Text; // Descrição da Nota Fiscal
  serie := xmlNCab.ChildNodes['serie'].Text; // Série da Nota Fiscal

  // Leitura Dados do Fornecedor...
  xmlNCab := NoPrinc.ChildNodes.FindNode('emit');

    cnpj := xmlNCab.ChildNodes['CNPJ'].Text; // CGC Fornecedor
    //cpf := funcvarXML(xmlNCab.ChildNodes['CPF'    ].Text; // CPF Fornecedor
    xNome := xmlNCab.ChildNodes['xNome'].Text; // Razão Social do Fornecedor
    xFant := xmlNCab.ChildNodes['xFant'].Text; // Nome Fantasia
    IE := xmlNCab.ChildNodes['IE'].Text; // Inscrição Estadual
    // Leitura Dados Endereços do Fornecedor...
    xmlNItm := xmlNCab.ChildNodes['enderEmit'];

      xLog := xmlNItm.ChildNodes['xLgr'   ].Text; // Logradouro
      nro := xmlNItm.ChildNodes['nro'    ].Text; // Número
      xBairro := xmlNItm.ChildNodes['xBairro'].Text; // Bairro
      cMun := xmlNItm.ChildNodes['cMun'   ].Text; // Código Município IBGE
      xMun := xmlNItm.ChildNodes['xMun'   ].Text; // Nome Município
      uf := xmlNItm.ChildNodes['UF'     ].Text; // Unidade Federação
      cep := xmlNItm.ChildNodes['CEP'    ].Text; // CEP
      cPais := xmlNItm.ChildNodes['cPais'  ].Text; // Código Pais BACEN
      xPais := xmlNItm.ChildNodes['xPais'  ].Text; // Nome Pais
      fone := xmlNItm.ChildNodes['fone'   ].Text; // Telefone

  // Leitura Dados Itens da Nota Fiscal...
  xmlNCab := NoPrinc.ChildNodes.FindNode('det');
  while not (xmlNCab = Nil) do
  begin
    xmlNCab.ChildNodes.First.ChildNodes.FindNode('det');
    xmlNItm := xmlNCab.ChildNodes['prod'];

      cProd := xmlNItm.ChildNodes['cProd'  ].Text; // Código do produto CFOP
      xProd := xmlNItm.ChildNodes['xProd'  ].Text; // Nome do produto
      uCom := xmlNItm.ChildNodes['uCom'    ].Text; // Sigla unidade da embalagem
      qCom := xmlNItm.ChildNodes['qCom'    ].Text; // Quantidade do produto (4dec,S/M)
      vUnCom := xmlNItm.ChildNodes['vUnCom'].Text; // Valor unitário do produto (4dec,S/M)
      vProd := xmlNItm.ChildNodes['vProd'  ].Text; // Valor total do produto (2dec,S/M)
      xmlNCab := xmlNCab.NextSibling;
  end;
end;

Obrigado pela ajuda pessoal!


Permanently remove interface ipv6 address

Question: I am running Ubuntu servers 16.04.5 LTS in virtual box. The servers are connected with an internal network to which want to assigne an IPv6 address range fd01:2345:6789:abcd::/64. The interface connected to this internal network is enp0s8.
To the interface enp0s8 on Server 1 I have assigned the address fd01:2345:6789:abcd::1/64, and it also has another IPv6 address which I have not assigned myself which is fe80::a00:27ff:fe64:5805/64.
 enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:64:58:05 brd ff:ff:ff:ff:ff:ff
    inet6 fd01:2345:6789:abcd::1/64 scope global
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe64:5805/64 scope link
       valid_lft forever preferred_lft forever

I would like to permanently remove the address fe80::a00:27ff:fe64:5805/64, but if I remove it with sudo ip addr del fe80::a00:27ff:fe64:5805/64 dev enp0s8, after rebooting the address is there again.
I have checked if there is dhcp running but it does not seem to be on the enp0s8 interface:
:~$ ps -aux | grep dhcp
root       827  0.0  0.2   6012  2544 ?        Ss   11:28   0:00 /sbin/dhclient -1 -v -pf /run/dhclient.enp0s3.pid -lf /var/lib/dhcp/dhclient.enp0s3.leases -I -df /var/lib/dhcp/dhclient6.enp0s3.leases enp0s3

This is how I have configured enp0s8 in /etc/network/interface:
# The local intnet1 network interface
auto enp0s8
iface enp0s8 inet6 static
    address fd01:2345:6789:abcd::1/64
    network fd01:2345:6789:abcd::

I encounter the same problem also on the other virtual machine.
How can I permanently remove the IPv6 address I don't want?
Comment: Your ULA address of `fd01:2345:6789:abcd::1/64` is obviously not using the required random 40-bit Global ID.
Comment: Thanks for the comment Ron. I m just testing localy on VMs for school assignment, and that is the address I m required to use for the moment.
Answer: The addresses in fe80::/10 subnet are IPv6 LINK-LOCAL addresses and ARE REQUIRED for correct IPv6 operation (they are for example used for neighbor discovery).
You probably cannot remove it and definitely SHOULD NOT remove it if you want to have operational IPv6.


GNU screen: set name or title

Question: I have many screen sessions open and I cannot recognize which one is which.
I start screen with:
# screen -d -m -t "myscreen" ./myscript.sh

but screen -ls just shows this:
# screen -ls
There are screens on:
    1167..lh18758   (04/13/2012 09:20:49 PM)        (Detached)
    32040..lh18758  (04/13/2012 09:20:05 PM)        (Detached)
    27775..lh18758  (04/13/2012 09:18:27 PM)        (Detached)
    27751..lh18758  (04/13/2012 09:18:27 PM)        (Detached)
    26604..lh18758  (04/13/2012 09:18:01 PM)        (Detached)
    6879..lh18758   (04/13/2012 09:10:28 PM)        (Detached)
    6347..lh18758   (04/13/2012 09:10:15 PM)        (Detached)
    6371..lh18758   (04/13/2012 09:10:15 PM)        (Detached)

It is possible to set names to screen session to not see the 6371..lh18758 but a title or name?
Comment: possible duplicate of http://stackoverflow.com/q/3202111/1030301
Answer: You can specify names when you create the sessions.
From the manpage:

-S sessionname
When  creating  a  new  session, this option can be used to specify a meaningful name for the session. This name identifies the
  session for "screen -list" and "screen -r" actions. It substitutes the
  default
    [tty.host] suffix.

So you would make the command line
$ screen -d -m -t "myscreen" -S "MeaningfulName" ./myscript.sh

GNU screen: set name or title


How to hide the text format field set using css?

Question: I followed several recommendations and decided to go with using CSS to hide the text format. I don't want to use another module to do something minor like this. Just want to hide text format for this particular form.
When I look at source I see:
<fieldset class ="filter-wrapper form-wrapper" id="edit-conditions-format">
blah blah blah
</fieldset>

Then on top of my form render function I do:
drupal_add_css('
        #edit-conditions-format {
            display: none;
        } ',
      array('group' => CSS_THEME, 'type' => 'inline'));

I have cleared cache and the text format is still available. Any tips?
Answer: Your code is correct. Just add it to a custom module, and it will work. Most likely it doesn't work because the admin theme is not the same as your front end theme.
Your module would take as little as this:
YOUR_MODULE.info:
name = Your module.
description = Description.
package = Custom
core = 7.x
version = 7.x-1.0

YOUR_MODULE.module:
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'ID_OF_THE_FORM_YOU_WANT_TO_ALTER') {
    drupal_add_css('
      #edit-conditions-format {
          display: none;
      } ',
    array('group' => CSS_THEME, 'type' => 'inline'));
  }
}

That's it. You can fetch the empty boilerplate here or if you want to do it properly, have a main custom module where you do all the extra customizations. You can have a look at mine here.
Or you could create a child theme of the admin theme, but that will likely take as much effort as creating a custom module.
Answer: i guess you don't use the same theme for everything, and you're using a custom theme. so - this code won't affect the 'backend'.

you need to alter the admin theme, or the theme you use to edit content.

so hack your admin theme, or better sub-theme it, and add your css there. then set this to your new admin theme here: admin/appearance
Comment: The sub-theme part of your answer is good, but it's generally not good to suggest to hack the theme/module.


Pergunta simples de PHP , preciso de uma estrutura, caso o curso tenha nome , não pode excluir!

Question: Fala pessoal beleza então o seguinte , em excluir curso deve ser respeitar a ideia que , onde não podem ter nome vinculados com aquele curso, ou seja, se tiver nome que tenha aquele curso, não poderá ser excluído,como montaria a estrutura , tentei algumas , mais ta complicado, sou iniciante.
abaixo como esta montado curso excluir até o momento!
<?php

include "../includes/conexao.php";

   $id = $_GET['id'];

   $sql = "DELETE  FROM curso where id = $id";

   $query = mysqli_query($conexao, $sql);

if($query){
    header("location: curso.php?mensagem=sucesso");
}else{
    header("location: curso_excluir.php?mensagem=erro");
}

?>

Comment: Evite imagem, edite sua pergunta e cole nela seu código
Comment: "onde não podem ter nome vinculados com aquele curso" ... Nao entendi direito. O nome que vc se refere é um campo da tabela curso?
Comment: Isso, é como se ao inserir o curso da ''tabela curso'' em usuario, o mesmo não pode ser excluído na tabela curso , pois o mesmo esta cadastrado um usuario .
Comment: @ManchadoManoel posta a tabela usuário do curso
Answer: Deixe-me ver se entendi. Você tem 2 tabelas:
Cursos
Participantes Cursos
Você quer que o curso só possa ser excluído se não houver nenhum participante para o curso em questão?
Se for isso, você tem 2 maneiras de fazê-lo:
1 - Integridade Referencial no Banco de Dados.
2 - Via Código PHP
Como você se diz iniciante, vou te dar a sugestão via código que eu acho de mais simples entendimento, porém, não acho que seja a mais adequada.
Você deverá fazer uma consulta na tabela de participantes e ver se há ou não participantes cadastrados.
Ex:
$consulta_participantes = mysqli_query($conexao, "SELECT blablabla FROM participantes_cursos WHERE id_curso = '$idcurso'");

$qtd_participantes = mysqli_num_rows($consulta_participantes);

Com a quantidade de participantes em mãos, através da variável $qtd_participantes, faça um IF para ver para onde será encaminhado.
Ex:
if($qtd_participantes == "0"){
    header("location: exclui_curso.php?id=$idcurso");
} else {
    header("location: lista_cursos.php?mensagem=Não foi possível excluir o curso pois já há participantes inscritos");
};

Foi um exemplo bem simplista mas que irá te ajudar a entender e resolver seu problema.
Comment: Isso mesmo, mas fiz o que disse, e esta dando erro, será que não esta apontando corretamente as tabelas.
Comment: Mostre o código completo e a estrutura das tabelas, ai fica mais fácil de verificar.
Comment: ok!vou deixar em cima,


Multiple aliases for a namespace?

Question: Is it possible to have a namespace that has all the declarations of more than one other namespace? Like this:
namespace std {...};
namespace glm {...};

namespace mynamespace = std; //mynamespace is an alias for std
namespace mynamespace += glm; //mynamespace will hold glm functions as well.

Answer: Sure
namespace mynamespace
{
   using namespace std;
   using namespace glm;
}

Comment: support for correct braces ;D! +1
Answer: You can use using to achieve this:
namespace mynamespace {
    using namespace std;
    using namespace glm;
}

Comment: Omg, there is a braces-war going on here! Voting for your answer :-P
Comment: I feel that the original one with a semicolon was more beautiful, expressing a sense of symmetry with classes and structs, perhaps as to say that aggregating these identifiers all serve a similar vein of grouping things together under one umbrella -- a world united through braces ending in a semicolon. The only finishing touch necessary would be a semicolon at the end of each function. Ignore the compiler warnings -- the compiler doesn't understand *art*.
Comment: Obviously voting for the braces that don't look totally disgusting.
Comment: Downvoted for ugly braces

Multiple aliases for a namespace?


"Knights and Knaves" puzzle to solve using equivalences.

Question: Context for the puzzle:
You are on an island inhabited by knights and knaves. Knights always tell the truth, knaves always lie. You meet 5 natives:

Carl says "I am the same type as Peter".
Zippy says "Carl is a Knave or Jack is a Knight".
Jack says "I am a knight and Bill is a Knave".
Peter says "Bill is a Knight".
Bill says "I am a Knight and so is Carl"

From this, I have formulated the following equivalences:

C ≡ P
Z ≡ ¬C ∨ J
J ≡ J ∧ ¬B
P ≡ B
B ≡ B ∧ C

I am trying to deduce which of the people are knights and which are knaves, however, after doing some substitution and manipulation using logical laws, I get to a point where I cannot make any more simplification and hence get stuck.
Could someone please point me in the right direction towards solving this problem?
Thank you.
Answer: It's not $C ≡ P$ - that would be true in the case of both $C$ and $P$ being knaves. You want $C ≡ (C ≡ P)$, which simplifies to simply $P$.
Comment: Is ≡ the right symbol here? It feels like we should simply be using =.
Comment: Thanks for your help. I have reached the conclusion that C,P,B are true and Z,J are false - Carl, Peter and Bill are knights while Zippy and Jack are knaves. Would that be correct?
Comment: Looks right to me.


How to determine the size of chunks in a deque

Question: I am trying to write a deque class in cpp by link list, however, I have no idea about how to decide the length of the chunks (buffers) when creating the deque.
Choose a good size for chunks will help to cut down the complexity of random visit in the deque.
Should I write a function that when a new element is pushed, it adjust the size of chunks dynamiclly, but i find it will have a high complexity in time since maybe it will move enormous data.
How should i deal with this problem.
Comment: Why don't you look at how the pros do it?
E.g. _"Microsoft choose values of 16 or smaller for the number of elements in a block. (Search for _DEQUESIZ)."_  - https://stackoverflow.com/a/46724521/2920343
Comment: Possible duplicate of [What the heque is going on with the memory overhead of std::deque?](https://stackoverflow.com/questions/4088999/what-the-heque-is-going-on-with-the-memory-overhead-of-stddeque)
Answer: Check out the code for <code>_DEQUESIZ</code> (number of elements per block):
<code>#define _DEQUESIZ   (sizeof (_Ty) <= 1 ? 16 \
: sizeof (_Ty) <= 2 ? 8 \
: sizeof (_Ty) <= 4 ? 4 \
: sizeof (_Ty) <= 8 ? 2 : 1)    /* elements per block (a power of 2) */
</code>
The larger the element grows, the smaller the number of element goes down to. You'll get expected percentual decrease of overhead with increase of element size only for elements that are larger than 8 bytes in size.
Check out the original answer here.


Converging Possibility of Being Chosen by a Skipping and Forgetful Machine

Question: Suppose that there is a machine that is actually broken: there is a line of people, for the first $r$ people, it will randomly choose one from them with equal possibility and then forget all people before the person it chose, and then choose the next person from the next $r$ people in line.
For example, when $r=2$, for the first choice, it has $\frac{1}{2}$ possibility of choosing #1 or #2 in line. If we are calculating the possibility of the #5 person in line to be chosen, the possibility $P_5$ can be considered as the possibility of choosing $P_3$, skipping #4 and directly reaching #5 or choosing $P_4$, then reaching #5. Therefore,
$$P_5=\dfrac{1}{2}(P_3+P_4).$$
Using the same idea, (by programming) we can see that the possibility $P_i$ of being chosen as $i$ increase converges to a certain value $\frac{2}{3}$.
Plot of Possibility Converging for $r=2$
Similarly, trying a few other examples with different $r$, we can get that the possibility is slowing converging to $\frac{2}{r+1}$, but why? Is there a theoretical explanation?
Comment: @true blue anil: The random selection occurs at each step. For example, $P_1=\frac{1}{r}$, but for $r > 1$ we have $P_2=\frac{1}{r}+\frac{1}{r^2}$.
Comment: @user2661923: The main recursion starts at $n=r+1$. The initial values $P_1,...,P_r$ can be computed via a different recursion (or by brute force). For example, using $r=3$, the initial values are
$$
P_1=\frac{1}{3},\;\;\;P_2=\frac{4}{9},\;\;\;P_3=\frac{16}{27}
$$
and then by the main recursion we get
$$
P_4=\frac{37}{81},\;\;\;P_5=\frac{121}{243},\;\;\;P_6=\frac{376}{729},\;\;\;P_7=\frac{1072}{2187}
$$
Comment: When you say "...for the first *r* people, it will randomly choose one from them with equal possibility..", $Pr = \frac{1}{r}$ for each of the first *r* ?
Comment: I share the confusion of @trueblueanil as to how the algorithm works.  Please, very carefully detail the exact math involved, under the assumption that $~r = 3~$ for example, of the probability that Person #6 will be chosen, and the probability that Person #7 will be chosen.  Personally, I need these examples in order to very carefully scrutinize your posting.
Answer: Fix a positive integer $r$.

First we show that $\lim_{n\to\infty}P_n$ exists.

Since for $n > r$, we have the linear recursion
$$
P_n=\sum_{k=1}^r \frac{1}{r}P_{n-k}
$$
it follows that $\lim_{n\to\infty}P_n$ exists if and only if all roots of the characteristic equation
$$
x^r=\sum_{k=1}^r \frac{1}{r}x^{r-k}
$$
have absolute value at most $1$.

If instead there is some $x\in\mathbb{C}$ with $|x| > 1$ satisfying the above characteristic equation, then
\begin{align*}
&
x^r=\sum_{k=1}^r \frac{1}{r}x^{r-k}
\\[4pt]
\implies\;&
|x^r|=\left|\sum_{k=1}^r \frac{1}{r}x^{r-k}\right|
\\[4pt]
\implies\;&
|x|^r\le\sum_{k=1}^r \frac{1}{r}|x|^{r-k}
\\[4pt]
\implies\;&
|x|^r\le\sum_{k=1}^r \frac{1}{r}|x|^{r-1}
\\[4pt]
\implies\;&
|x|^r\le|x|^{r-1}
\\[4pt]
\implies\;&
|x|\le 1
\\[4pt]
\end{align*}
contradiction.

Hence $\lim_{n\to\infty}P_n$ exists.

But we can write another recursion for $P_n$ based on the observation that for person $n$ not to be selected, the final skip must overshoot person $n$.

It follows that
$$
1-P_n=\sum_{k=1}^{r-1}\frac{r-k}{r}P_{n-k}
$$
hence, letting $L=\lim_{n\to\infty}P_n$, we get
$$
1-L=\sum_{k=1}^{r-1}\frac{r-k}{r}L
$$
which yields $L={\Large{\frac{2}{r+1}}}$.
Comment: I don't really understand this step
"Since for $n>r$, we have the linear recursion $P_n=\sum^r_{k=1}\frac{1}{r}P_{n−k}$, it follows that $\lim_{n\to \infty}P_n$ exists if and only if all roots of the characteristic equation $x^r=\sum_{k=1}^r\frac{1}{r}x^{r−k}$ has absolute value at most 1", would you mind explaining how did you deduce the roots of characteristic equation from the linear recursion? Thanks!
Comment: @Stephanie Yao: https://en.wikipedia.org/wiki/Linear_recurrence_with_constant_coefficients#Characteristic_polynomial_and_roots


Can't add a custom filter criteria

Question: I try to add a new filter criteria to my views with a custom module.
I manage to display my new filter on the filter criteria list but when I select it and go to "Add and configure filter criteria" I have an error saying:

The handler for this item is broken or missing. The following details
  are available:
Enabling the appropriate module may solve this issue. Otherwise,
  check to see if there is a module update available.

Here is my content_search.module :
function content_search_views_data_alter(&$data)
{
    $data['node']['content_search_filter'] = [
        'title' => t('Content search filter'),
        'filter' => [
            'title' => t('Content search filter'),
            'help' => 'Filters nodes on its content',
            'field' => 'nid',
            'id' => 'content_search_filter',
        ]
    ];
}

And here is my ContentSearchFilterPlugin, placed in content_search/src/Plugin/Filter/ContentSearchFilterPlugin.php
namespace Drupal\content_search\Plugin\Filter;

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\FilterPluginBase;

/**
 * Filters nodes on on their content
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("content_search_filter")
 */
class ContentSearchFilterPlugin extends FilterPluginBase {
  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Content search filter');
  }

  public function query() {
    parent::query();
    // TODO: custom query here
  }

}

What am I missing ?
Answer: I think you have a problem with plugin file organization. It should be :
content_search/src/Plugin/views/filter/ContentSearchFilterPlugin.php

...instead of
content_search/src/Plugin/Filter/ContentSearchFilterPlugin.php

And the namespace for this file should be
namespace Drupal\content_search\Plugin\views\filter;

Answer: This works for me in Drupal8:
Name of custom module: custom_modulename
Name of table in SQL: name_of_sql_table
Selecting the ID for filtering
function custom_modulename_views_data_alter(array &$data) {
  $data['name_of_sql_table']['custom_modulename'] = [
    'title' => t('Title shown'),
    'group' => t('abc'),
    'filter' => [
      'title' => t('Filter'),
      'help' => t('Self made'),
      'field' => 'id',
      'id' => 'string'
    ],
  ];
}

Hint: If you want to use options etc. then it is much more complicated. Use a Class for that.

Can't add a custom filter criteria


How to setup openfire with haproxy

Question: I am trying to set an Openfire cluster of 2 nodes by using the hazelcast plugin (Both using 3.9.3 version of openfire).
one of them running on 192.168.1.2 and other on 192.168.1.22 and both uses the common Mysql DB which is running on 192.168.1.2 .
I have installed Haproxy on machine with ip 192.168.1.13 using apt -get install haproxy and configured it for load balancing.
I am stuck when i try to login at admin console of openfire using haproxy at 192.168.1.13:9090 , it doesn't allow me to login. i am unable to recognize what's happened as i am a beginner for clustering so please advise me if i am doing something wrong. below is my haproxy.cnf file
<code>global
        log /dev/log   local0
        log 127.0.0.1   local1 notice
        maxconn 4096
        user haproxy
        group haproxy
        daemon

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        retries 3
        option redispatch
        maxconn 2000
        contimeout     5000
        clitimeout     50000
        srvtimeout     50000

listen openfire
    bind 192.168.1.13:9090
    mode http
    stats enable
    stats uri /haproxy
    balance roundrobin
    option httpclose
    option forwardfor
    server openfire_rahul 192.168.1.22:9090 check
    server openfire_girish 192.168.1.2:9090 check
</code>
"Thanks in advance"
Answer: Now i understand what exactly was going on. because i have used mode http , so http is a stateless protocol and server closes the connection after every response to dedicated request.
by using the tcp mode i got rid off this problem.

How to setup openfire with haproxy


Help with understanding this linear functionals argument

Question: Now I have come across a few proofs that all involved a similar argument involving linear functionals and I don't understand how it works. Can someone please help me understand it? The argument goes like this:
If $f(a) = f(b)$ for all $f \in A^\ast$ ($a,b \in A$) where $A$ is a Banach space it follows that $a=b$.
Of course for any linear map $T$, if $Ta = Tb$ then $Ta - Tb = T(a-b)=0$. This doesn't imply $a-b=0$ since the map $T=0$ is continuous and linear. Therefore the  step in the argument that I am missing is: why if it's true for all $T$ then indeed $a-b=0$ is deducible.
Answer: This follow from the Hahn-Banach extension theorem, which can be stated as follows:

Theorem. Given a normed space $X$, a closed subspace $U \subseteq X$ and a linear continuous $u^* \in U^*$. Then there is an extension $x^* \in X^*$ of $u^*$ with the same norm, that is $x^*|_U = u^*$ and $\def\norm#1{\left\|#1\right\|}\norm{u^*} = \norm{x^*}$.

From this fact, we can deduce the following:

Corollary. Let $X$ be a normed space and $x \in X-\{0\}$. Then there is an $x^* \in X^*$ with $x^*(x) \ne 0$.

Proof. Define $U := {\rm span}\, \{x\}$, and $u^*(\lambda x) = \lambda\norm x$.Then $u^*\in U^*$ and $\norm{u^*} = 1$. Let $x^*$ be a Hahn-Banach extension, then $x^* \in X^*$ and $x^*(x) = u^*(x) = \norm{x}\ne 0$.
If now $x,y\in X$ are different points, then $x-y\ne 0$, and the above Corollary gives an $f \in X^*$ with $f(x-y) \ne 0$, that is $f(x) \ne f(y)$.
Hence if $f(x) =f(y)$ holds for all $f \in X^*$, we must have $x=y$.
Comment: I'm sorry for taking so long. Could it be that the $U$ in the theorem does not necessarily have to be closed?
Comment: And I have one more question: you define $u^\ast(\lambda x) = \lambda \|x\|$. I believe this is not linear since $u^\ast (x + y ) \le \|x\| + \|y\|$. No? I would like to suggest the following fix: If $\mathbb K$ denotes the base field of the normed space then fix any $k \in \mathbb K \setminus \{0\}$ and define $u^\ast (\lambda x) = \lambda k$. Please let me know what you think.
Comment: Sorry, your map *is* linear! But I believe my suggestions works also. One should be able to map $x$ to any fixed scalar.
Comment: Is it okay for me to edit your answer and delete ''closed''? @martini


Labelling and coloring plots inside loop - matplotlib

Question: I'm plotting multiple hysteresis loops from multiple files in the same axis using a for loop, and I'm wondering how to have a different label and colour for each loop.  Each loop is actually made up of two lines.  The relevant code is:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

filelist = ['file1', 'file2', 'file3']

fig = plt.figure()
axes = fig.add_subplot(111)

for item in filelist:
    filename = item
    #import hyst files
    up = pd.read_csv(filename)
    up.columns = ['Field','Moment','Temperature']

    upcut = up2[:cut_loc -1] #cuts the file in 2
    down = up2[cut_loc +1:]

    upcutsrt = (upcut.sort(['Field']))

    upcutsrt.plot(x='Field', y='Moment', ax=axes)
    down.plot(x='Field', y='Moment', ax=axes)

ax1.set_xlabel('Magnetic Field', fontsize = 20, labelpad = 15)
ax1.set_ylabel('Magnetic Moment', fontsize=20, labelpad = 15)

plt.show()

So this plots 3 different hysteresis curves on the same axes with the same axes labels and scale and everything.  Unfortunately though, all the lines are the same colour.  I would like to have each curve (up and down from file) to have a different colour and a different label but I'm at a loss as to how to do it.
Answer: Well first you need a list of colors, one per file:
colors = ['red', 'green', 'blue']

then modify the for loop:
for item,col in zip(filelist,colors):

and finally plot using the colors:
    upcutsrt.plot(x='Field', y='Moment', ax=axes, color=col)
    down.plot(x='Field', y='Moment', ax=axes, color=col)

Comment: could you format this with the correct indents to make it more readable?


org.hibernate.HibernateException error in Eclipse, using Hibernate.!@!

Question: I am making a simple hibernate program.
And I get this error.
I am using a Mac and Eclipse Framework for this.
    Exception in thread "main" org.hibernate.HibernateException: Error accessing stax stream
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:107)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:65)
    at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:163)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:258)
    at driver.main(driver.java:12)
Caused by: javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,1]
Message: Premature end of file.
    at java.xml/com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:652)
    at java.xml/com.sun.xml.internal.stream.XMLEventReaderImpl.peek(XMLEventReaderImpl.java:276)
    at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:103)
    ... 5 more

From the driver.java , I wish to make changes to the Database using Hibernate. I am not aware of the errors.
I am using an object of the employee class in driver.java.
Here is the employee.java
public class employee
{

private String name;

private int Eid;

private String city;

employee(){}

//getters
public String getName()
{
    return this.name;
}
public int getEid()
{
    return this.Eid;
}
public String getCity()
{
    return this.city;
}

//setters
public void setEid(int a)
{
    this.Eid=a;
}
public void setName(String s)
{
    this.name=s;
}
public void setCity(String s)
{
    this.city=s;
}
}

Driver .java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class driver {

public static void main(String[] args)
{
    Configuration conf = new Configuration();
    conf.configure("/Users/ronin/Desktop/Hibernate/employee.hbm.xml");
    SessionFactory sf = conf.buildSessionFactory();
    Session s = sf.openSession();
    Transaction tx = s.beginTransaction();
    employee e = new employee();
    e.setEid(34);
    e.setName("Robin");
    e.setCity("Patiala");
    s.persist(e);
    tx.commit();
    s.close();
}
}

employee.hbm.xml file
    <?xml version = "1.0" encoding = "utf-8"?>

<hibernate-mapping>
   <class name = "employee" table = "employee">

      <id name = "id" type = "int" column = "id">
         <generator class="native"/>
      </id>

      <property name = "name" column = "name" type = "string"/>
      <property name = "city" column = "city" type = "string"/>
      <property name = "Eid" column = "id" type = "int"/>

   </class>
</hibernate-mapping>

hibernate, cfg.xml file
<?xml version='1.0' encoding='UTF-8'?>

<hibernate-configuration>

    <session-factory>
        <property name="hbm2ddl.auto">update</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="connection.url">jdbc:mysql://localhost:3306</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <mapping resource="employee.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

Comment: @LuiggiMendoza 9.0.1
Comment: Great, just confirming that you're using Java9. I assume you've setted classpath correctly for the application and also have the `module-info.java` file at the root of your project, right?
Comment: @LuiggiMendoza Yes I did!
Answer: JAXB is not readily available in JDK 9 as part of SE. I guess it is moved J2EE in version 9. Refer here
To make the JAXB APIs available at runtime, you may add following command-line option
--add-modules java.xml.bind

or as a permanent solution you can use these dependencies by importing them using maven like,
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.2.8</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.2.8</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.2.8</version>
</dependency>

Note:
In case of  Java 6 use JAX-B Version 2.0.
In case of  Java 7 use JAX-B Version 2.2.3.
In case of  Java 8 use JAX-B Version 2.2.8
Comment: I am not sure how to do that in Eclipse!
Comment: I am using Java 9.0.1,which JAX-B version to use?
Comment: That Helped! Thanks!