Min/Max number of inequalities needed to determine the order of $n$ numbers

Question: We are given an ordered $n$-tuple of positive real numbers $R=(r_1,..r_n)$. A $k$-inequality is an inequality of the form
$x_1<x_2<...<x_k$
where $x_1,..,x_k$ are in $R$. For example, for $n=7$, we might have the $3$-inequality $r_5<r_2<r_1$. We would like to order by magnitude all the elements in $R$ given some number of $k$-inequalities.
(1) Find the minimum number of $k$-inequalities such that the ordering is determined.
(2) Find the maximum number of $k$-inequalities one can give such that the ordering is not determined.

I made up this problem yesterday, but I'm guessing that this is a well known thing in computer science/information theory/algorithms.
Comment: The first part is easy. For the second part, my approach: let the answer be $f(k,n)$. Use recursion to relate $f(k,n)$ to $f(k,n+1)$. For example take $k=3$. We first give all the $f(3,n)+1$ inequalities not involving $r_{n+1}$ which determine the order of $r_1,..,r_n$, then we need to give inequalities involving $r_{n+1}$. If $r_1,..,r_{n+1}$ are ordered as $x_1<..<x_{n+1}$ with $r_{n+1}=x_k$, then we can give all the inequalities of the form $x_i<x_j<x_k$ with $1 \le i<j<k$ and similarly all of the form $x_k<x_i<x_j$ with $k+1<i<j \le n+1$.
Comment: Also we can give all of the form $x_j<x_k<x_i$ with $1 \le j < k-1$ and $k+1<i\le n$. Its easy to find the number of inequalities that is in total.
Answer: Assume $r_1<r_2<\ldots<r_{n-1}<r_n$.
For $k=2$, the answers are (1) $n-1$ and (2) $\binom{n}2-1$.
In the first case, we can write $r_1<r_2,\ r_2<r_3,\ \ldots,\ r_{n-1}<r_n$.
In the second case, we can write all possible inequalities with $r_1$ as the lesser: $r_1<r_2,\ r_1<r_3,\ \ldots,\ r_1<r_n$ and then all the inequalities with $r_2$ as the lesser, etc., until we reach $r_{n-1}<r_n$, without which the order is not totally decided.
For $k=3$, in the first case we can write $r_1<r_2<r_3$, then $r_3<r_4<r_5$, etc. and establish the order in just $\lceil \tfrac12(n-1)\rceil$ statements.
In the second case, I suspect the answer is $\tbinom{n}3-(n-2)$. Write down all the 3-inequalities except for those which end $\ldots<r_{n-1}<r_n$.
For general $k$, the analogous answers would be (1) $\lceil \tfrac{n-1}{k-1}\rceil$ and (2) $\binom{n}k-\binom{n-2}{k-2}$.
Comment: This looks correct.


Brownian motion reflection principle result

Question: I'm studying about the reflection principle of the brownian motion, and I found that this result is a direct consequence of this principle:
Let $B_t$ a brownian motion, then for every $a \in \mathbb{R} \ $,
$$\mathbb{P}(\lim_{t \to \infty} \sup_{s\in [0,t]} B_s > a) = 1$$
I'm trying to prove this statement using the reflection principle but I'm totally lost. I can't see how are those results related.
Comment: Which formulation of the reflection principle do you know/use? It is direct consequence of the reflection principle that $$M_t := \sup_{s \leq t} B_s$$ equals in distribution $|B_t$|. Knowing this, it shouldn't be difficult to prove the assertion.
Answer: Let $M_t = \sup_{s \in [0,t]} B_s$.  For $a < 0$ the statement is trivial, so take $a \ge 0$.
The reflection principle says that $P(M_t > a) = 2 P(B_t > a)$.  Now since you know $B_t \sim N(0,t)$, you can compute $\lim_{t \to \infty} 2 P(B_t > a)$ and determine that it equals 1.  Thus $\lim_{t \to \infty} P(M_t > a) = 1$.
This is not the same as the desired statement, but can be used to prove it in this case.  Note that $M_t$ is increasing in $t$, so necessarily $\lim_{t \to \infty} M_t$ exists (as a random variable) and $\lim_{t \to \infty} M_t \ge M_u$ for any fixed $u$.  Hence $P(\lim_{t \to \infty} M_t > a) \ge P(M_u > a)$.  Passing to the limit as $u \to \infty$ and using what we previously proved, we have $P(\lim_{t \to \infty} M_t > a) \ge \lim_{u \to \infty} P(M_u > a) = 1$.
Comment: What is $\lim_{t\to\infty} M_t$?
Comment: It's the usual thing.  It's the random variable $M$ defined as $M(\omega) = \lim_{t \to \infty} M_t(\omega)$.  We know by definition of $M_t$ that for each $\omega$, $M_t(\omega)$ is an increasing function of $t$, so the limit exists in $[0,+\infty]$ for each $\omega$ and $M$ is well defined.  It is an exercise to verify that it is measurable.  Of course, we end up proving that $P(M > a) = 1$ for every $a$, from which it follows that in fact $M = +\infty$ almost surely.
Answer: From the Law of Iterated Logarithm:
$$
\limsup_{t\to+\infty}\frac{B_t}{\sqrt{2t\ln\ln t}} \overset{\mathbb{P}\rm -a.s.}{=} 1,
$$
so
$$
\mathbb{P}\left(\lim_{t\to+\infty}\sup_{s\in[0,t]}B_s>a\right)=1.
$$


jsf 2.0 reading  tag as String ""

Question: I wish to add ul tag to my jsf in some cases. My codes like:
<c:if test="${level ne 1}" ><ul></c:if>

..

..

..

<c:if test="${level ne 1}" ></ul></c:if>

When I was using jsf 1.2, it works well. But after I change to jsf 2.0, it reads like
 "
"

..

..

..

 "
"

How can I fix it? Thanks so much!!
Answer: You seem to have replaced legacy JSP by Facelets as well (well done!). This behaviour is specific to Facelets. It implicitly HTML-escapes all the template text as part of builtin XSS attack prevention.
Use <h:outputText escape="false"> instead.
<c:if test="${level ne 1}"><h:outputText value="<ul>" escape="false" /></c:if>

..

..

..

<c:if test="${level ne 1}"><h:outputText value="</ul>" escape="false" /></c:if>

You'd better use its rendered attribute instead of those ugly JSTL tags by the way.
<h:outputText value="<ul>" escape="false" rendered="#{level ne 1}" />

..

..

..

<h:outputText value="</ul>" escape="false" rendered="#{level ne 1}" />

Unrelated to the concrete problem, for the concrete functional requirement, you may find OmniFaces <o:tree> component useful.

jsf 2.0 reading  tag as String ""


How to pass block instance configuration settings to TWIG template?

Question: I've got a custom block plugin which has some configuration settings that can set from the block configuration form. How can I then access that configuration info later when the block is being rendered?
I know that if I know the block's instance id, I can get the configuration data using:
\Drupal::config('blockID'])->getRawData()
However, I'm having trouble finding a hook that can determine the block instance id at the same level as the template so that it can pass that data as a TWIG variable.
I can find the block id inside of HOOK_preprocess_block(&$variables), but then I don't know how to pass anything from this hook to the theme template.
Vice versa, if i use HOOK_preprocess_TEMPLATE(&$variables), I cannot figure out how to get the block instance id in order to pull the configuration values.
I know what the default block id is and can hard code that into the theme template hook, however, this breaks down if more than one instance of the block is placed into the site.
What is the right approach to retrieving block instance configuration settings for use in the theme TWIG template?
Answer: Thanks to Jaypan over at the Drupal forums who provided the answer to this issue, in a post regarding a different config form question. The proper way to pass config data to the theme template is to define variables in the template registration, in the theme's hook function. Then in the block plugin class definition's build() function we can populate those variables with values from the configuration.
In theme's hook_theme() function, register the template with variables to be passed to the template.
/**
 * Implements hook_theme().
 */
function hook_theme() {
  return [
    // The theme key.
    'bubblepop' => [
      // The variables used in the render array.
      'vars' => [
        'color' => NULL,
        'text' => NULL,
      ],
      // I believe this must be the same as the theme key, with any
      // underscores turned into hyphens.
      'template' => 'bubblepop',
    ],
  ];
}

In the block's build function we can then populate them with config values:
public function build() {
  $config = $this->getConfiguration();
  return [
    // An arbitrary theme, defined in hook_theme().
    '#theme' => 'bubblepop',
    // Attributes are defined in hook_theme().
    '#color' => $config['color'],
    '#text' => $config['text'],
  ];
}


Practicing chords in Bb Minor

Question: I'm playing the piano since 2 years now. Currently, I started playing this piece. It mainly consists of chords and since it's written in Bb Minor, there are many black keys. How do I practice these chords? My hands are pretty small (I can play an octave).
Any tipps would be appreciated!
Comment: What is specifically giving you trouble?
Comment: @user45266 it is mainly finding good fingerings and moving my hand around. Probably I just have to practice it a lot
Answer: These chords are all less than an octave.
So you should be able to reach the notes.
You'll notice the hands are placed on the black keys and the white keys are played in between
You need to do this.
This requires more strength than stretch as you need to play further up the fulcrum of the white key.
I would highly recommend a good teacher if you wish to play at this level of technique.
Comment: thanks for your answer, but actually most of the chords are octaves (except for the beginning). I also take piano lessons, but due to corona, the music school is closed.
Answer: How old are you (I'm only asking to find out whether your hands will grow, no need for a specific age)?
There are some things you could do. For a start, I'd do what I have been doing for years: practise all your scales with their diatonic chords every day. No need to practise in all 12 keys. You can dedicate 6 days of the week to 2 keys each and revise them all on the 7th day.
Are you following a good system with regard to your practising in general? I highly recommend "Fundamentals of Piano Practice" by Chuan C. Chang.
If your hands are not growing any time soon, there are some workarounds for more difficult cases as well. Remember that the most important notes in every chord are the 3rd and the 7th. If you cannot play all the required notes, you can just play those 2.
You could invest some time into finger-stretching and wrist exercises as well. Make sure your fingers end up on top of the keys and take things very slowly. Play the same chord over and over, making sure your posture is proper, and that your fingers are relaxed and correctly positioned on top of the keys. Often extended practising and anxiety can make our joints too stressed to properly work with an instrument (I play instruments with keys too, and I always invest some time before any practice session to ensure I am breathing properly and none of my joints are strained or feel "unnatural" in some way).
Comment: thanks for your answer! I'm currently 16.5 years old. However, my hands have always been small and since I have (except for that) a "normal" size, I don't have much hope that my hands will grow a lot.

Practicing chords in Bb Minor


RegEx: Split a string by another string, including diacritics

Question: I've been trying to split a string by another string via RegEx.Split() method in C#.
Either data or splitter can have diacritics.
Let me give you an example:
Data: education
Splitter: dù
Expected result: e / du / cation
--or--
Data: èdùcation
Splitter: ed
Expected result: èd / ùcation
Is it possible?
If it is, could you help me for writing the pattern?
Answer: There is no option in .NET's regular expression engine to "ignore diacritics", however it might be possible to work around it by making use of Unicode normal form-D (for "decomposed"). This is untested.
Accented characters can be represented in two ways:

As single pre-composed code points. Eg. U+00F9 (Latin Small Letter U with Grave).
As a base code point followed by one or more combining characters. Eg. U+0075, U-0300 (Latin Small Letter U, Combining Grave Accent).

Thus if you ensure the input data is decomposed (use String.Normalise(normalization) passing NormalizationForm.FormD), and that any potentially accented character in the pattern is replaced by
B\p{Mc}*

a base character B followed by zero or more code points in Unicode category "Mark, Spacing Combining".
To include the text that matches the regex in the output make it capturing, so to match and capture both du and dù use (du\p{Mc}*).


When realizing a basso continuo, should the realization avoid consecutive fifths and octaves with the written parts?

Question: Many continuo manuals (both historical sources and modern treatises) are careful to point out that a continuo realization should be contrapuntally correct, i.e., one ought to avoid parallel fifths and octaves in the extemporized parts, as well as other voice-leading mistakes. (With some amount of license allowed in very full-voiced textures.)
However, such prescriptions only seem to apply to the internal consistency of the continuo realization. Most continuo manuals that I've seen only show music examples for the realization itself, and not for the composition as a whole. For that reason, I'm wondering how the realization should interact contrapuntally with the other written parts of a composition.
Suppose, for example, that we have three string parts (2 violins, viola) above a continuo line. If I want to play a four-part continuo realization, should the resulting seven-part texture be correct contrapuntally? That seems almost impossibly difficult to me, especially if it has to be extemporized. Or am I allowed to double in the right hand one or more of the written parts, so that we effectively get a less than seven-part texture?
I find this a rather confusing aspect of Baroque musicianship.
Edited for clarity.
Answer: Yes and no.
More precisely, octave and unison doubling is probably permissible with inner voices.  As always, this is subject to considerations of style and taste.

Suppose, for example, that we have three string parts (2 violins, viola) above a continuo line. If I want to play a four-part continuo realization, should the resulting seven-part texture be correct contrapuntally?

Another way of asking this is whether the resulting texture really ought to be a seven-part texture.  It probably shouldn't.
If you really want to go into the question in depth, study some larger orchestral or choral/orchestral works of the period.  A piece with four string parts and two wind parts, for example, will not employ a six-part texture throughout.  There is a lot of doubling, sometimes at the octave.  Bach's festive choral music, for example, frequently has the first trumpet doubling the alto at the octave.
One technique that Bach, at least, employs frequently in his orchestral writing is to use different "choirs" of instruments antiphonally.  I don't know how readily applicable that is to a continuo realization, but it brings to mind a related point: using some sort of figuration in the continuo realization might help avoid unwanted doublings.  I once heard Christopher Hogwood suggest, in a workshop rehearsal of Dido and Aeneas, that the continuo harpsichordist consider a realization inspired by the opening of this through-composed piece for solo harpsichord:

(To be sure, I'm talking about the first few measures where the right hand is in the alto range, here on the upper manual, not the part where the right hand jumps to the soprano range, here on the lower manual, and begins playing the ornamented melodic line.)
Parallel unisons and octaves are going to be impossible to avoid in a piece with a full choral or orchestral texture.  They should generally be avoided in accompanying a soloist, and they should probably also be avoided with the soprano/first violin/treble wind instrument in a fuller texture.
Parallel fifths should be avoided more assiduously.
Disclaimer: I have limited experience actually playing continuo realizations, so there are probably many practical considerations that I'm not aware of.  I wish Wheat Williams were still on the site.
Comment: Thanks a ton! Exactly what I wanted to know. Yes, I was mainly asking about very full textures, such as the tutti sections from Handel's Messiah.
Comment: @KimFierens funny, I was just looking at Messiah as a sanity check against some of the assertions in this answer.  It's fascinating, in fact, how the orchestra jumps into and out of doubling the voice parts.  At the opening of _Worthy is the Lamb,_ the first violins, doubled with the first trumpet, are independent in m1, doubling the soprano at the octave in m2, and doubling the alto at the octave in m3.  By the cadence in mm6-7, the first trumpet and second violins are doubling the soprano at the unison while the first violin is doubling the alto at the octave.
Comment: @KimFierens and I don't see a reasonable way for a continuo player to realize that cadence without doubling the 7-6 suspension in the soprano and the B-to-A♯ resolution in the alto.
Comment: Thank you; interesting. Come to think of it, I believe we can generalize your observation: if there is a dissonance anywhere in the written parts that is also notated in the continuo part, then doubling is inevitable, because the resolution of dissonance is more or less unique (in the Baroque style at least).
Answer: Yes. The bass part (especially in Figured Bass style) stands out. Parallel fifths or octaves with a melody line (or two melodies in trio sonatas or even more) gives the effect that a voice dropped out.
You can test this by playing some simple songs and play a bass line that imitates the melody. It sounds like a full melody but not two parts.
Comment: The question isn't just about the bass part — which is written in basso continuo parts. The question relates to the harmonic realization.
Comment: Yes, Aaron is correct. I was asking about the extemporized right-hand parts of the continuo. Should those also not form faulty consecutives with the other written parts?
Comment: Yes, the other parts have the same problems with parallels. The bass just stands out more so that's what I used. In inner parts, one may get away with doublings but not parallels.
Comment: The bass isn't discretionary; it's the given starting point from which the continuo realization is, well, realized.  Parallel fifths and octaves between the bass and the melody (or any other part) are an error on the part of the composer, not the performer.


Render form with ajax submit

Question: I have a custom form in a module, similar to this example:
function mymodule_form($form, &$form_state) {
   $radio_options = array(...);
   $form = array();
   $form["wrapper"] = array("#markup" => "

");
   $form['choice'] = array(
       '#title' => '',
       '#type' => 'radios',
       '#options' => $radio_options,
   );
   $form['submit'] = array(
       '#type' => 'submit',
       '#value' => t('Vote'),
       '#ajax' => array(
           'callback' => 'demo_form_ajax_submit',
           'wrapper' => "test-ajax",
           'method' => 'replace',
           'effect' => 'fade',
       ),
   );
   return $form;
}

function demo_form_ajax_submit($form, $form_state) {
   var_dump("something");
}

And I'm printing that form in template like this:

   <?php print render($form['choice']); ?>
   <?php print render($form['form_build_id']); ?>
   <?php print render($form['form_token']); ?>
   <?php print render($form['form_id']); ?>
   <?php print render($form['submit']) ?>

The form is printed correctly and even the button shows the ajax icon when clicked, but it does not work. When I check the logs it shows 2 errors:

Notice: Undefined index: form_build_id in ajax_get_form() (line 325 of...
Invalid form POST data.

It is similar to this issue Ajax not working for themed form but it does not work even adding drupal_render_children($form); at the bottom of the template.
Notes:

I added drupal_add_library('system', 'drupal.ajax'); in the module.
I'm using jQuery 1.7
I also tested drupal_render() instead of render().
Answer: Instead of print rendering the individual items, you can try to build your form using the drupal_get_form core function, which allows Drupal to add all the extra components to the form (including the Ajax call).
So in your template it would like like this:
$output = drupal_get_form('mymodule_form');
print drupal_render($output);

Comment: I need to print the elements separately in order to theming them. I tried that way printing the elements separately para I got the same issues above.
Comment: @JoseDaniel You can theme the elements separately using form_alter. Are you saying that you did try the drupal_get_form? If yes, what happens - does the form render properly?
Comment: If I printed the way you said (drupal_render($output)), it prints the html of the form and it works, but I need to print each element separately in order to theme them and put the elements in different places.

I also tried to print drupal_render($output['name_of_the_element']) as my example above, but I got the same issues.

What is your solution with form_alter? Thanks!
Comment: @JoseDaniel so if you use drupal_render($output) does the Ajax call work? Re theming, look at this [tutorial](https://www.drupal.org/node/651106) so you can do something like: `function mymodule_form_alter(&$form, $form_state, $form_id) {
 if($form_id == 'your_form_id') {
    // modify  your form fields here
 }
}`
Comment: I see, but it does not solve my problem. I don't need to modify the elements, I need to render them separately in the template.
Comment: Ah I see. Out of curiosity, what is the reason you need to render the elements separately? And let me know if Ajax worked when you used drupal_get_form... this will help figure out where the bug is

Render form with ajax submit


Find the natural numbers with the property that the product of their divisors is equal to $10^a$

Question: Find the natural numbers N other than 0 with the property that the product of all of the divisors of N is equal to $10^a$ where a is the number of the divisors of N.
This is my approach:
Let N be a natural number with prime factorization $ N = p_1^{a_1} \cdot p_2^{a_2} \cdot \ldots \cdot p_k^{a_k} $, where $ ( p_1, p_2, \ldots, p_k ) $are distinct prime numbers and $( a_1, a_2, \ldots, a_k )$ are positive integers.
The number of divisors of  N is given by $( (a_1 + 1) \cdot (a_2 + 1) \cdot \ldots \cdot (a_k + 1) ).$
Now, we want the product of the divisors to be equal to ( 10^a ), where ( a ) is the number of divisors. This leads to the equation:
$[ (a_1 + 1) \cdot (a_2 + 1) \cdot \ldots \cdot (a_k + 1) = 10^a ]$
For this equation to hold, we can consider two cases:

If $ ( a_k \geq 3 )$ for any $( k )$, then the right side of the equation has a prime factor of 5, but the left side does not. This is a contradiction.

If $( a_k \leq 2 )$ for all $( k )$, then the right side of the equation is a power of 10, and the left side must also be a power of 10. This implies that each $( a_i + 1 )$ is a power of 2 and 5.

By analyzing the possible combinations, we find that the only natural numbers satisfying the given property are 120 and 100.
Is it correct? I'm not sure about the conclusion, I think there could be more numbers to satisfy the property.
Comment: The product of the divisors of $24$ is $24^4\neq 10^a$
Comment: $24$ doesn't satisfy the property. The divisors of $24$ are $1,2,3,4,6,8,12,24$ so their product is $1\times 2\times 3\times 4\times 6\times 8\times 12\times 24 = 331776$ whereas the quantity $10^a = 10^8=100000000$
Comment: For a `solution-verification` question to be on topic you must specify *precisely* which step in the proof you question, and *why so*. This site is not meant to be used as a proof checking machine.
Comment: Tip: Don't write `\(`, write `(` when in math mode.
Comment: @BillDubuque alright, I'm sorry if it seemed like I'm using this website as a "proof checking machine".
Comment: You're right, then the only numbers who satisfy the property should be powers of 10?
Comment: It should be obvious if $k$ is a divisor of $N$ then $k$ is one of the components that constructs the product of the divisors and has to be a divisor of the product as well.  So $N$ can't have any divisors that are not also divisors of $10^a$.
Answer: First, the product of divisors of a number are given by $n^\frac{\sigma_0(n)}{2}$ where $\sigma_0(n)$ is the number of divisors of $n$.
So, $10^{2a} =N^a$, which gives $N=100$.
In order to see this, you can note that multiplying two of the divisors of $n$ yield $n$, and you just have to count how many time that happens.
You just equated the number of divisors of $n$ to $10^a$, which obviously isn't correct.
Comment: The notation $\sigma(n)$ is traditionally used to denote the **sum** of the divisors of $n$.
Comment: Yes indeed. Shall change that to $\sigma_0$.
Answer: For any number (eg 20)
$$
\text{Factors: } 1,2,4,5,10,20
\\
\text{Product: }(1*20)(2*10)(4*5)=20^3
$$
So generally speaking $$\text{Product}=N^{\frac{no. of factors}{2}}$$


Physics based trigonometry question

Question: I am working on solving the problem stated in this image:

I understand almost everything about this problem. I solved for the magnetic field along the axis of a circular loop, and now I need to integrate from Ө1 to Ө2.
The problem I am encountering is that I am not sure how to put dz in terms of dӨ. Here is how the example does it:

Can someone explain these steps to me? I pretty much understand every step here except for this one:
$$
\frac{d\theta}{\cos^2\theta} = -\frac a{z^2}\,dz
$$
Thanks for your help!
Comment: You might consider reading all the answers (e.g., the ones that won't be posted until 45 minutes from now) before accepting one. ${}\qquad{}$
Answer: Given:
$$ \tan \theta = \frac az$$
Now perform differentiation on both sides against some dummy variable $t$:
\begin{align}
\frac{d}{dt}\tan\theta &= \frac{d\theta}{dt} \sec^2\theta \\
\frac{d}{dt}\frac az &= -\frac{dz}{dt} \frac{a}{z^2}.
\end{align}
"Eliminate" the $dt$ and use $\sec\theta=\frac1{\cos\theta}$.
$$\frac{d\theta}{\cos^2\theta} = -\frac{a}{z^2}dz.$$
Answer: $$
\tan\theta = \frac a z \tag 1
$$
Consequently
$$
\frac 1 {\cos^2\theta} = \frac d {d\theta} \tan \theta = \underbrace{\frac d {d\theta} \frac a z = \frac{-a}{z^2}\,\frac{dz}{d\theta}}_{\text{chain rule}}
$$
$$
\frac{d\theta}{\cos^2\theta} = \frac{-a}{z^2}\,dz
$$
Answer: Differentiate $$ z  \tan \theta  = a \tag{1} $$
$$ dz \tan \theta  +  z  \sec ^2\theta\; d\theta = 0 \tag{2}$$
$$ \dfrac{d \theta }{dz}=\dfrac{-\tan\theta \cos^2 \theta}{z}= \dfrac{(-a/z) \cos^2 \theta}{z}=\dfrac{-a \cos^2 \theta}{z^2} \tag{3}.$$
and re-arrange.

Physics based trigonometry question


Is the set $ \{x \in \mathbb{R^2} | x_1 + x_2 < x_2^2 \} $ open or closed?

Question: Is the set $ \{x \in \mathbb{R^2} | x_1 + x_2 < x_2^2 \} $ open or closed?
This question has been confusing me for a very long time. I have tried solving it using coordinate geometry and trying to find the shortest distance between any arbitrary point x and the parabola created by $ x_1 + x_2 = {x_2}^2 $ but it just results in a huge mess. It so extremely obvious to me that the set is open when I draw a picture but I am not able to formally prove it.
Any help would be extremely appreciated.
Answer: Consider the continuous function $\varphi(x_{1},x_{2})=x_{1}+x_{2}-x_{2}^{2}$, the preimage of $(-\infty,0)$.
Comment: So the set in question is exactly $\varphi^{-1}(-\infty,0)$. As $\varphi$ is continuous, the preimage of an open set is still open.
Comment: Umm, what about this function?
I'm sorry I'm just extremely confused right now
Comment: Is there any way we could prove it using the ball method, by considering a ball around an arbitrary set?
Comment: I think there is, but that makes me panic all the time.
Comment: I have not been taught continuous functions with respect to open sets so it's really hard for me to understand this method,
If you could help me out with the ball method I would really appreciate it
Comment: Let's wait if somebody could post an answer using elementary method, I would like to see so. Sorry, I can't help you.


How to test sagas when there are functions not using 'yield' or an effect like 'call' or 'put'?

Question: In all the examples I've found everyone is using yield call(), yield put(), etc. on their sagas. Right now I have a saga that just executes a function without using yield call(). This function is executed after a select effect and before a call effect (see code below for the service variable. This function returns an instance of a class, it's not a network request or a promise.
The saga works fine, but I'm not sure how to test it like this. Using redux-sagas-test-plan while having the effects works fine, but as soon as I remove the effect (which I remove from the .provide(), the test fails.
Saga
export function* getDetails() {
    try {
        const config = yield select(getProperties());
        const service = getService(config);
        const data = yield call([service, service.getDetails]);
        yield put(success(data));
    } catch(e) {
        yield put(failure());
    }
}

Test
import { getDetails as detailsSaga } from '...';
const data = {};

it('should succeed getting details', async () => {
        await expectSaga(detailsSaga)
            .provide([
                [select(getProperties), {}],
                [call([serviceMock, serviceMock.getDetails]), data]
            ])
            .put(success(data))
            .dispatch(fetchDetails())
            .silentRun();
    });

The expected result from the test is tu have the success(data) creator to execute but instead I get the failure() creator as the actual value.
Expected
    --------
    { '@@redux-saga/IO': true,
      combinator: false,
      type: 'PUT',
      payload:
       { channel: undefined,
         action:
          { type: 'FETCH_DETAILS_SUCCESS',
            data: { } } } }

    Actual:
    ------
    1. { '@@redux-saga/IO': true,
      combinator: false,
      type: 'PUT',
      payload:
       { channel: undefined,
         action: { type: 'FETCH_DETAILS_FAILURE' } } }

Comment: I'm assuming `service.getDetails` is making a network request? You may want to mock the network request with something like `jest-fetch-mock`: https://github.com/jefflau/jest-fetch-mock to return the expected response. When you use the provider you're skipping entirely whatever is happening in `service.getDetails` which is also fine if you don't care about testing the implementation of `service.getDetails` in this particular test.
Answer: Based on other examples I found, this was my solution:
import { call } from 'redux-saga-test-plan/matchers';

beforeEach(() => {
  service = getService({});
  data = { /* ... */ });
});

it('should succeed getting details', async () => {
  await expectSaga(detailsSaga)
    .provide([
      [select(getProperties), {}],
      [call.fn(service.getDetails), data]
    ])
    .put(success(data))
    .dispatch(fetchDetails())
    .silentRun();
});

I have to use the call effect from redux-saga-test-plan/matchers and create an actual instance returned by getService. For some reason a mock doesn't work here.
The details of why this works are not that clear to me, but I'm writing this answer just in case someone is trying to achieve this as well. Note: I agree with the other answer, that all functions should be called using yield call but I've been asked not to do that here.
Answer: Anytime you call a function in a saga, you should use the call effect. It would be best to use that instead of directly calling the function as you have done. It would return the same data as when you call it directly, and would make testing it easier as you don't have to mock or spy on anything.
Example:
export function* getDetails() {
    try {
        const config = yield select(getProperties());
        const service = yield call(getService, config);
        const data = yield call([service, service.getDetails]);
        yield put(success(data));
    } catch(e) {
        yield put(failure());
    }
}

Comment: I agree with you, that's what I was doing, but I'm being asked not to do that. The getService method is just a regular function that returns an instance of a class based on the config values. It's not a network request or a promise even. People in my office are telling me that getService is a "function not a saga" and that we should be treating it as a regular function. So literally, I'm being asked to remove the `yield call` I had just as you mentioned.
Comment: No problem, the `call` effect is created to call any type of function. It also supports calling methods from within classes and passing the `this` context. It is not just for calling promises, or other sagas. Technically any function should be used with it as it makes testing easier.


Is the empty set is a subspace of any vector space

Question: Is the empty set is a subspace of any vector space?
im not too sure about this one, is the zero vector in the empty set?
Comment: As you say, the empty set does not contain the zero vector, and so it is not a vector space.
Answer: The answer is no. The empty set is empty in the sense that it does not contain any elements. Thus the zero vector is not a member of the empty set.


Calculating $ \sum_{ k=1}^n (-1)^k k $

Question: I've got two sums here
$ \sum_{k=1}^n (-1)^k k  $
and $ \sum_{k=1}^n (-1)^k k^2 $
I need to solve them through term isolation.
I struggle to find anything similar.
So I am asking you for help; do you have any ideas or approaches?
Comment: [(1)](https://math.stackexchange.com/q/2137234), [(2)](https://math.stackexchange.com/q/2069385), [(3)](https://math.stackexchange.com/q/388388)...
Comment: Just look at the even and odd summands separately.
Comment: For the $k$ terms, consider each consecutive pair...
Comment: A similar idea — grouping pairs of terms as far as possible — works for the second sum too.
Comment: I did consider that as well. Though the "term isolation" confuses me. Does that just mean consindering each consecutive pair?
Answer: Try writing out some terms as $n$ grows.
$$\left\{\sum_{k=1}^n(-1)^kk\right\}_{n=1}^{\infty}=\{-1,1,-2,2,-3,3\ldots\}$$
You have the ceiling of $n/2$ alternating negative and positive.
$$\left\{\sum_{k=1}^n(-1)^kk^2\right\}_{n=1}^{\infty}=\{-1,3,-6,10,-15,21\ldots\}$$
You have the triangular numbers $n(n+1)/2$ alternating negative and positive.
If you need a proof, there are good ideas in the comments.

Calculating $ \sum_{ k=1}^n (-1)^k k $


Existe algum comando ou função em JavaScript que controle a atualização de tela antes do loop terminar?

Question: Apenas um exemplo:

O que eu esperava era enviar uma mensagem na tela a cada "delay", mas isto não acontece, só exibe as 10 mensagens na tela quando o loop termina.   Alguém ai conhece algum comando para forçar a exibição do texto no momento exato que ele é enviado, dentro do loop?   Pretendo utilizar isto para atualizar a progress bar de uma função JS que manipula arquivos e muitas vezes demora para finalizar, o usuário pensa que o navegador travou e fecha a janela antes da função terminar. Se alguém puder ajudar, ficarei muito grato!
Obs. Já tentei com setTimeout, alguns artificios para forçar o rendering, enfim, por enquanto nada funcionou, lembrando que o codigo acima é apenas um simples exemplo para ilustrar o meu problema.
Comment: O fato é que em condições normais você não deve fazer o código dessa forma em JS (nem em linguagem nenhuma praticamente). Mesmo que existisse o que quer, ainda assim um código que consome todo processamento pode ser considerado até como tendo um bug se isso não for um objetivo específico dele. Mesmo códigos que rodam 24/7 normalmente tem um ponto em que liberam a CPU, a não ser em caso de cálculos intensos e coisas do tipo (como uma máquina dedicada a encontrar números primos ou mineração de algumacoisacoins)
Comment: O que você procura seria algo como uma promise? https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise
Comment: Já tentou usar `setInterval`?
Comment: Ja tentei, mas também não funcionou. Não tenho muita experiencia com JS, mas me parece ser um problema conceitual da linguagem, enquanto está executando uma função não faz outra coisa até terminar aquela função.   Na minha cabeça uma interrupção de tempo (setInterval ou setTimeOut) deveria ter prioridade na execucão, mas na prática parece que não acontece...
Comment: Depois que vc dispara o `setInterval`, ele fica rodando independentemente de estarem sendo executadas outras coisas no script. Pelo que pude entender, bastaria vc disparar um `setInterval` mostrando algo na tela, e quando seu progress terminar, basta cancelar o `setInterval`.
Comment: Se eu mudar o "document.get..." por "console.log" consigo monitorar da forma que quero em tempo real pelo monitor da console, dai funciona perfeitamente.   Mas preciso fazer isto pela tela do navegador.
Comment: ja fiz este teste com setInterval, quando entra no loop, para de atualizar a tela e so retorna quando o loop termina.
Comment: Já tentou colocar `+=` no lugar de `=` após o `document.get...`?
Answer:
Existe algum comando ou função em JavaScript que controle a
atualização de tela antes do loop terminar?
- Não, não existe comando ou função em JavaScript que controle a atualização de tela antes do fim dum loop.

Javascript é uma linguagem de thread único o que significa que o display em HTML só será atualizado após o laço for ser terminado.
Para fazer o seu HTML ser atualizado em um laço seria necessário lançar mão de um hipotético laço de repetição assíncrono.
A linguagem não oferece esse laço de repetição assíncrono mas é possível obter essa funcionalidade através do método setInterval() que cria um timer repetindo a chamada de uma função em um intervalo de tempo definido em milissegundos e que retorna um identificador para o timer.
Para interromper esse timer use a função clearInterval() que aceita como parâmetro o identificador para o timer que deseja interromper.

var i = 0;
var j = 0;

var menssagem = document.getElementById('mensagem');
//Executa o laço a cada décimo de segundo
var loop = setInterval(() => {
  menssagem.innerText = `teste msg na tela ${i}`;
  if (i >= 10) {
    clearInterval(loop); //Se i for maior ou igual a dez encerra o laço
  } else {
    i++; //Se i for menor que 10 incrementa i
  }
}, 100);
//Executa um segundo laço em paralelo em com duração
//e um tempo de atualização diferentes
var loop2 = setInterval(() => {
  console.log(`teste msg no console ${j}`);
  if (j >= 20) {
    clearInterval(loop2);
  } else {
    j++;
  }
}, 55);
Teste em tempo real:
Comment: Só um adendo, é possível também usar o `setInterval` com intervalo `0` porque ele já vai pra fila de *callback* por ser assíncrono, não importa o "tempo de espera". Relacionado: https://pt.stackoverflow.com/a/184783/100416
Answer: O seu loop só exibe a mensagem depois do final do seu loop, pois é exatamente isso que está escrito no código, veja:
for (var i=0;i<10;i++) {
 var t=0;
 while(t<1000000) {
   t++;
 }
 document.getElementById('mensagem').innerHTML = `teste msg na tela ${i}` //a mensagem so esta sendo exibida logo apos todo o seu loop for concluido
}

caso você queira que apareça antes do loop do comando (for) experimente colocar a sua mensagem dentro do bloco while:
for (var i=0;i<10;i++) {
 var t=0;
 while(t<1000000) {
   document.getElementById('mensagem').innerHTML = `teste msg na tela ${i}`
   t++;
 }
}

porém neste trecho de código a sua mensagem irá aparecer ate a variavel T chegue no valor 1000000, depois disso o (for) irá se repetir por 10 vezes sem fazer nada pois a sua váriavel T já vai valer 1000000, caso queira que apareça 1000000 por uma vez e pare o comando (for) recomendo escrever desta maneira:
for (var i=1;i<1;i--) {
 var t=0;
 while(t<1000000) {
   document.getElementById('mensagem').innerHTML = `teste msg na tela ${i}`
   t++;
 }
}

desta forma o comando (for) não ira se repetir 10 vezes, o que irá se repetir é o while por 1000000 vezes e a cada vez que ele se repetir irá mostrar a sua mensagem.
outra alternativa é, repetir o comando (for) 10 vezes mostrando a mensagem por 1000000 vezes por 10 vezes:
for (var i=0;i=10;i++) {
     var t=0;
     while(t<1000000) {
       document.getElementById('mensagem').innerHTML = `teste msg na tela ${i}`
       t++;
     }
       var t = 0;
    }

Comment: Obrigado Muriel, mas no primeiro exemplo que coloquei se observar bem o texto está sendo enviado dentro do laço "for", e não fora. Se colocar dentro do loop while (neste exemplo serve apenas para criar um delay), a mensagem seria enviada 1000000 vezes ao invés de 10.   Isto é apenas um exemplo, a questão é que a mensagem não vai para a tela em tempo real como ocorre no "console.log". E dai, permanece a minha pergunta, será que existe algum comando que obrigue o navegador exibir a mensagem e depois continuar o loop, mesmo que isto implique em maior lentidão. Espero ter explicado de forma clara.
Answer: Aqui está um exemplo de loading usando o setInterval. O setInterval espera como o primeiro parâmetro uma função que vai ser executada de forma assíncrona a cada intervalo de tempo.

let perc = 0;
let id = null;
$(document).ready(() => {
 id = setInterval(() => {
   console.log("executing function");
   perc += 10;
   $('.progress-bar').css('width', perc+'%').attr('aria-valuenow', perc);
    $('.progress-bar').innerHtml = perc + "%";
    if(perc >= 100) {
     clearInterval(id);
    }
  }, 1000);
});
.row {
  background: #f8f9fa;
  margin-top: 20px;
}

.col {
  border: solid 1px #6c757d;
  padding: 10px;
}

<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css">

<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">

Segue jsFiddle:
https://jsfiddle.net/cf9w7eur/9/
Comment: Agradeço a tentativa de me ajudarem, mas continuo com o mesmo problema:  O progress bar apresentado funciona perfeitamente, atualizando a cada segundo, até ai ok, mas basta chamar uma segunda função que demore mais de alguns segundos para executar e a barra fica parada, só volta a ser atualizada quando terminar esta segunda função, que seria justamente o objetivo, acompanhar o progresso desta segunda função, monitorando em tempo real.  Não entendo porque o setInterval não tem prioridade em relação a uma função ou loop por exemplo.
Comment: javascript é single thread e funciona como se fosse uma cpu com 1 core. Ela divide tempo de processamento. Se você bombardear a thread com um loop sem delay. A função não vai rodar. Se consequir enviar a forma de como você estiver fazendo o processamento. Posso te ajudar melhor, garanto que tem solução melhor do que esse while imenso.
Comment: Esse while imenso foi só uma maneira que encontrei de ilustrar de forma simples o meu problema real, na prática é uma função que manipula arquivos 32 bits e tem laços "for" para esta manipulação. O meu objetivo, enquanto esta manipulação ocorrer, tivesse uma sinalização na tela em tempo real, gráfica ou um simples texto do tipo "processando camada x de y", onde x seria atual e y o total. Mas todas as tentativas foram frustradas porque a tela so recebe as msg quando termina a funcão, pelo que estou percebendo não tem solução com JavaScript, teria que passar para o back-end em outra linguagem...


real analysis and arithmetic progression

Question: Let $f: \mathbb{R} \rightarrow \mathbb{R}$ be a continuous function which takes positive and negative values. Given $ n>2 $ natural, prove that there are $a_1, a_2, a_3 \cdots a_n$ real numbers in arithmetic progression, such that
\begin{equation}
f(a_1) + f(a_2) + \cdots + f(a_n) = 0
\end{equation}
Comment: Perhaps you might like to tell us what in-roads you have made.
Answer: Since $f$ takes negative and positive values, there exist $x_-, x_+ \in \mathbb R$ such that $f(x_-) < 0$ and $f(x_+) > 0$. By continuity, for a small $\varepsilon > 0$ all the values $f(x_- + k\varepsilon)$ are negative ($k = 1,\ldots,n$) and all the values $f(x_+ + k\varepsilon)$ are positive ($k = 1,\ldots,n$). Let
$$g(x) := \sum_{k=1}^n f(x+k\varepsilon).$$
Then $g$ is continuous and satisfies $g(x_-) < 0$ and $g(x_+) > 0$. By the intermediate value theorem, there is an $x_0$ such that $g(x_0) = 0$. Let $a_k = x_0 + k\varepsilon$ ($k=1,\ldots,n$). Then the $a_k$ are in arithmetic progressions and satisfy
$$f(a_1) + \ldots + f(a_n) = 0.$$


Can I group rows in a Javafx TableView?

Question: I'd like to make a javafx TableView with rows that may (or may not) have "related" rows. Basically, I think it might be a tableview of tableviews, but (a) I'm not sure that would work and (b) my gut tells me there's an easier way.
Imagine a bill or materials like
item    material    quantity    name
1       wood        1           base
2       wood        4           drawer
        wood        4           drawer sides
        wood        1           drawer base
        hardware    1           pull
        hardware    8           nails
3       aluminum    4           leg
        plastic     1           foot
        hardware    1           screws

Right now, it's sorted by name (base, drawer, leg). If I sort it by material, I want the items to be 3, 1, 2 (or 3, 2, 1): aluminum, wood, wood. I need the "subitems" to remain with the numbered items.
Can I make "complex rows"? (And I don't even know what I'd call it!)
Or do I need a custom sort that will keep groups together?
Comment: Looking for [`TreeTableView`](https://openjfx.io/javadoc/11/javafx.controls/javafx/scene/control/TreeTableView.html)?
Answer: You may want to check out TreeTableView. With it, you may be able to sort by whatever criteria you like, while at the same time having the records grouped by any other criteria (for example by name)
This component gets its data from a tree structure model built on the TreeItem class.
With it a root TreeItem can be built for the root object of your bill of materials having as children a TreeItem for each group you want (name of the material?). Then, each of these grouping TreeItem objects should contain as children the corresponding TreeItem children for each of the actual material in the bill of materials being displayed.
There are multiple good tutorials out there that cover in detail the technical aspects of this:

https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/tree-table-view.htm
https://o7planning.org/en/11149/javafx-treetableview-tutorial
https://examples.javacodegeeks.com/desktop-java/javafx/javafx-treetableview-example/

Hope this helps.
Comment: When I looked through the javafx controls, I saw TreeTableView and thought it was a TreeView, ie, no columns. This is much easier than my options and I thank you, Marco.
Answer: This answer uses a TreeTableView to represent the data rather than a TableView.
It uses a demonstration data model with hard-coded data.
The complicated nested lambda expressions could be replaced by procedural code mapping your actual model data to the TreeItem data structure which backs the TreeTableView.

import java.util.*;

import javafx.application.Application;
import javafx.beans.property.*;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;

@SuppressWarnings("unchecked")
public class TreeTableViewSample extends Application {

    private final List<String> employeesNames = Arrays.asList(
            "Ethan Williams",
            "Emma Jones",
            "Michael Brown"
    );

    private final Random random = new Random(42);

    @Override
    public void start(Stage stage) {
        ObservableList<DutyAssignment> assignments =
                determineAssignments(employeesNames);

        TreeItem<DutyAssignment> assignmentTree = createAssignmentTree(assignments);
        TreeTableView<DutyAssignment> dutyAssignmentView = createAssigmentTreeTableView(assignmentTree);

        stage.setScene(new Scene(dutyAssignmentView));
        stage.show();
    }

    private TreeTableView<DutyAssignment> createAssigmentTreeTableView(TreeItem<DutyAssignment> root) {
        TreeTableColumn<DutyAssignment, String> employeeColumn =
                new TreeTableColumn<>("Employee");
        employeeColumn.setPrefWidth(120);
        employeeColumn.setCellValueFactory(
                param -> param.getValue().getValue().nameProperty()
        );

        TreeTableColumn<DutyAssignment, Workday> dayColumn =
                new TreeTableColumn<>("Day");
        dayColumn.setPrefWidth(100);
        dayColumn.setCellValueFactory(param ->
                param.getValue().getValue().dayProperty()
        );

        TreeTableColumn<DutyAssignment, Duty> dutyColumn =
                new TreeTableColumn<>("Duty");
        dutyColumn.setPrefWidth(100);
        dutyColumn.setCellValueFactory(param ->
                param.getValue().getValue().dutyProperty()
        );

        TreeTableView<DutyAssignment> dutyAssignmentView = new TreeTableView<>(root);
        dutyAssignmentView.getColumns().setAll(employeeColumn, dayColumn, dutyColumn);
        dutyAssignmentView.setShowRoot(false);
        dutyAssignmentView.setPrefSize(380, 500);

        return dutyAssignmentView;
    }

    private TreeItem<DutyAssignment> createAssignmentTree(ObservableList<DutyAssignment> assignments) {
        TreeItem<DutyAssignment> root = new TreeItem<>(
                new DutyAssignment("All Assignments", null, null)
        );
        root.setExpanded(true);
        employeesNames.stream()
                .sorted()
                .forEach(employeeName -> {
                    TreeItem<DutyAssignment> employeeTitleItem = new TreeItem<>(
                            new DutyAssignment(employeeName, null, null)
                    );
                    root.getChildren().add(employeeTitleItem);
                    employeeTitleItem.setExpanded(true);

                    assignments.stream()
                            .sorted()
                            .filter(assignment -> employeeName.equals(assignment.getName()))
                            .forEach(dutyAssignment -> {
                                TreeItem<DutyAssignment> assignmentLineItem = new TreeItem<>(
                                        new DutyAssignment(null, dutyAssignment.getDay(), dutyAssignment.getDuty())
                                );
                                employeeTitleItem.getChildren().add(assignmentLineItem);
                            });
                });

        return root;
    }

    private ObservableList<DutyAssignment> determineAssignments(List<String> employeesNames) {
        ObservableList<DutyAssignment> assignments = FXCollections.observableArrayList();

        for (String employeeName : employeesNames) {
            for (Workday day : Workday.values()) {
                assignments.add(
                        new DutyAssignment(
                                employeeName,
                                day,
                                selectRandomDuty()
                        )
                );
            }
        }

        return assignments;
    }

    private Duty selectRandomDuty() {
        return
                Duty.values()[
                        random.nextInt(
                                Duty.values().length
                        )
                ];
    }

    public static void main(String[] args) {
        Application.launch(TreeTableViewSample.class, args);
    }

    public class DutyAssignment implements Comparable<DutyAssignment> {
        final private SimpleStringProperty name = new SimpleStringProperty();
        final private SimpleObjectProperty<Workday> day = new SimpleObjectProperty<>();
        final private SimpleObjectProperty<Duty> duty = new SimpleObjectProperty<>();

        final private Comparator<DutyAssignment> nameDayDutyComparator =
                Comparator.comparing(DutyAssignment::getName)
                        .thenComparing(DutyAssignment::getDay)
                        .thenComparing(DutyAssignment::getDuty);

        public DutyAssignment(String name, Workday day, Duty duty) {
            setName(name);
            setDay(day);
            setDuty(duty);
        }

        public String getName() {
            return name.get();
        }

        public SimpleStringProperty nameProperty() {
            return name;
        }

        public void setName(String name) {
            this.name.set(name);
        }

        public Workday getDay() {
            return day.get();
        }

        public SimpleObjectProperty<Workday> dayProperty() {
            return day;
        }

        public void setDay(Workday day) {
            this.day.set(day);
        }

        public Duty getDuty() {
            return duty.get();
        }

        public SimpleObjectProperty<Duty> dutyProperty() {
            return duty;
        }

        public void setDuty(Duty duty) {
            this.duty.set(duty);
        }

        @Override
        public int compareTo(DutyAssignment o) {
            return nameDayDutyComparator.compare(this, o);
        }
    }

    public enum Duty {
        WRITING, EDITING, COLORING, COMPOSITING
    }

    public enum Workday {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
    }
}

Can I group rows in a Javafx TableView?


How to print user role in body profile page

Question: I've got two roles in my website and I'd like to print the role name in the user profile page body classes for the user being viewed. How can I do this?
Answer: The html.tpl.php template uses the $classes variable to add classes to the body element. You can use template_preprocess_html() to add classes to this variable. Add this function to your theme's template.php
//Replace MYTHEME with the name of your theme
function MYTHEME_preprocess_html(&$variables) {

  //Check if the path is a profile page with a valid user
  if(preg_match('/^user\/(\d+)/', current_path(), $matches) == 1) {
    if($user = user_load($matches[1])) {

      //Add each role to the $classes_array which makes it available in $classes
      foreach($user->roles as $rid => $role) {
        $variables['classes_array'][] = str_replace(' ', '-', $role);
      }
    }
  }
}

Comment: Hi Shawn thanks for your help. Maybe I've to edit the question. What I meant is: not to get the current logged in user role, but to get the role of the profile page user I'm visiting. I.e. if I see a user profile page with `role-A` I would like to have in the body classes `user-role-a`, and so on.
Comment: I'm trying with this code in the `preprocess_html` function but without success: `if (arg(0) == 'user' && is_numeric(arg(1))) {
    $user = user_load((int) arg(1));

    if (in_array('role-a', $user->roles)) {
      $vars['classes_array'][] = 'user-role-a';
    }

    if (in_array('role-b', $user->roles)) {
      $vars['classes_array'][] = 'user-role-b';
    }
  }
`
Comment: All that's need is a simple mod that makes `$user` refer to the currently viewed user. See above.
Comment: Sorry for my inexperience. Works perfectly... Thank you!


Linq complex Inner Join

Question: I want to join my data with linq inner join as:
[DataContract]
public class Data
{
    [DataMember(Order = 0, IsRequired = false, EmitDefaultValue = false)]
    public List<DataResultObject> Row { get; set; }
}

[DataContract]
public class DataResultObject
{
    [DataMember]
    public string NAME { get; set; }
    [DataMember]
    public string VALUE { get; set; }
    [DataMember]
    public string TYPE { get; set; }

}

List<Data> follow = (List<Data>)dataset_cache.Get("follow");//364 rows
List<Data> icerik = (List<Data>)dataset_cache.Get("icerik");//134854 rows

List<Data> follow_icerik = icerik.Join(follow,
                i => i.Row.Where(w => w.NAME == "CrawlSourceId").Select(s => s.VALUE),
                f => f.Row.Where(w => w.NAME == "crawl_source_id").Select(s => s.VALUE),
                (i, f) =>
                    new Data
                    {
                        Row = i.Row.Concat(nf.Row).ToList()
                    }
                ).Take(5).ToList();

But it returns empty, how to use inner join when we have list in "on" clause ?
Comment: It would be awesome if you could provide a [mcve] **including sample data**.
Comment: Can you write it with basic loops? It will help you. Also, Can you add a [mcve]?
Comment: I need to use linq, no prblem with sql.
Comment: @CanerUnutkan Post your data as a POCO
Comment: You can probably use conversion to string for this `String.Join("\0", i.Row.Where(w => w.NAME == "CrawlSourceId").Select(s => s.VALUE).OrderBy(o => o))`. But you should definitely do what mjwills said to get a good answer.
Answer: Try this:
List<Data> follow_icerik = icerik.Concat(
                icerik.SelectMany(e => e.Row)
                                 .Where(w => w.NAME == "CrawlSourceId")
                                 .Join(follow.SelectMany(e => e.Row)
                                              .Where(w => w.NAME == "crawl_source_id"),
                i => i.VALUE,
                f => f.VALUE,
                (i, f) =>
                     new List<DataResultObject> { i, f }
                ).Select(e => new Data { Row = e })
).ToList();

EDIT:
icerik.SelectMany(e=>e.Row) - select rows with data which we are needed
icerik.SelectMany(e=>e.Row).Where(w => w.NAME == "CrawlSourceId") - filter this data
...  Join(... - join filtered data
In Join we also have to filter data before join: follow.SelectMany(e=>e.Row)                                              .Where(w => w.NAME == "crawl_source_id")
i => i.VALUE,
 f => f.VALUE, - fields on which we join data.
Comment: get the error on  w.NAME : "List' does not contain a definition for 'NAME' and no extension method 'NAME' accepting a first argument of type 'List,"
Comment: I edited a litle and worked but result has only joined colums , other colums are missin.
new Data
                    {
                        Row = new List {
                            i,f
                        }
                    }
Comment: Explain what result you want because it is not clear from your question description.
Comment: Edited again. Hope it is that you are needed.
Comment: Now the error is : Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)
Comment: Edited. Add `.ToList()` at the end.
Comment: retruned same of icerik as result :/
Comment: Check what `Join` returns. If it returns not empty collection then concat return you concatenated data. https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.concat?view=netframework-4.8

Linq complex Inner Join


Eclipse Oxygen, How to close this Tab/Directory/...?

Question: I accidentally opened this hierarchy/directory, or whatever tab in my eclipse oxygen... It is slowing down my eclipse because whenever I click something it updates and shows the information of that method/variable... How can I close it? It is enclosed by the red rectangle in the picture below. I tried to google it, but it is very hard to find useful results when I don't even know what this is called... Many thanks!
Answer: It's called breadcrumb.
There's a button in the global toolbar, called Toogle Breadcrumb.
In my eclipse there's no keybinding for it, but you can configure this via Window -> Preference -> General -> Keys. The corresponding command is called Toggle Java Editor Breadcrumb.
Comment: After seeing your answer, a simple google solved my problem. I feel  relieved now that it's gone... Thank you so much!


error: specializing member requires 'template<>' syntax

Question: I am trying to port some code from a visual studio solution to GCC. The code looks like this and I am trying to understand why I am getting this issue
template <class BASE, class SHADER>
class Shader : public BASE {
...
...
    ~Shader()
    {
        someAssesrt(0);
    }
};

typedef Shader< VertexShader, ddVertexShader> VertexShaderBase;

VertexShaderBase::~VertexShaderBase()  <-- ERROR HERE
{
}

The error is:
error: specializing member '{anonymous}::Shader< VertexShader, IDirect3DVertexShader9*>::~ <unnamed>::VertexShaderBase< VertexShader, IDirect3DVertexShader9*>' requires 'template<>' syntax

I am having difficulty understanding this error and some other code components.
First of all what is happening here
typedef Shader< VertexShader, ddVertexShader> VertexShaderBase;

    VertexShaderBase::~VertexShaderBase()  <-- ERROR HERE
    {
    }

From my understanding a type of VertexShaderBase  is created and then the destructor of that type is implemented. Isnt the destructor of the type already defined in the type Shader ? If i understand that then maybe I might be able to figure out why I am getting this error. From what I understand is that Shader<VertexShader, ddVertexShader> is a type somewhere in the code ?
 error: specializing member '{anonymous}::Shader< VertexShader, IDirect3DVertexShader9*>::~ <unnamed>::VertexShaderBase< VertexShader, IDirect3DVertexShader9*>' requires 'template<>' syntax

I am not sure what is happening here and help regarding understanding this code would be helpful.
Comment: The error message seems self-explanatory... what happened when you tried with `template<>` in front?
Comment: `Shader` is a template for defining classes, `VertexShaderBase` aka `Shader< VertexShader, ddVertexShader>` is a particular instance of that template.  When you change the behavior of one instance of the template, that's called **specialization**.  If you change the behavior of an entire category of instances at once, that's *partial specialization*.
Comment: It works however i am trying to understand the code too and why that is happening
Comment: Thanks Ben let me see if I get this correct. So there was a destructor  in the shader class. Then there was the destructor that i mentioned above. That destructor of the shader class only gets called if the template parameter of the shader class are of types ` VertexShader, ddVertexShader ` . I understand the  destructor of the class like any other method was being specialized. Kindly correct me if I am wrong
Comment: @MistyD yes that's right
Answer: You always need to inform the compiler that you are specializing a template by placing template<> in front of it. If it is a partial specialization it might be template<class X> instead.
If the Microsoft compiler was not requiring this, then it was doing it wrong.
The syntax gets especially interesting when specializing a template function of a template class. See https://stackoverflow.com/a/4995106/13422


Need a unique, reversible function to convert text to integers in MySQL

Question: I need to convert arbitrary alphanumeric IDs to integers that will be guaranteed to be unique and reversible.  Any cool tricks out there to do this?  I've looked at some hash functions and the like but usually they don't produce integer output or they are non-unique.
For example, suppose I have an ID such as AX36543TXQ.  I need a function that will uniquely map this into an integer in such a way that it will not collide with any other possible IDs and can be converted back to its alphanumeric form if need be.
Comment: Please read [What topics can I ask about](http://stackoverflow.com/help/on-topic)
 and [How to ask a good question](http://stackoverflow.com/help/how-to-ask)
 and [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)
 and how to create a [Minimal, Complete and Verifiable example](http://stackoverflow.com/help/mcve)
**SO is not** a free Coding or Code Conversion or Debugging or Tutorial or Library Finding service
___We try to fix your code, we do not write your code___
Answer: Avoid collision is very difficult, but you can do something similar, like this:
First: Creating a table with a column VARCHAR as Primary Key:
CREATE TABLE `table` (
  `pkey` VARCHAR(10) NOT NULL,
  `name` TEXT NULL,
  `others` TEXT NULL,
  PRIMARY KEY (`pkey`));

Adding some data:
INSERT INTO `table` (`pkey`, `name`, `others`) VALUES ('a', 'Albert', '123');
INSERT INTO `table` (`pkey`, `name`, `others`) VALUES ('b', 'Bernard', '456');
INSERT INTO `table` (`pkey`, `name`, `others`) VALUES ('c', 'Chelsea', '789');

As you can see, the column PKEY is the primary key, and VARCHAR:
DESCRIBE `table`;

Now, changing the Primary Key to another column based on Auto Increment:
1º) Create the column:
ALTER TABLE `table` ADD COLUMN `new_key` INT;

2º) Fill the columns with a sequence of integers
SET @i=0;
SET @Count=(SELECT COUNT(*) FROM `table`);
UPDATE `table` SET `new_key` = @Count-(@i:=@i+1)+1;

3º) Change the new column to be the Primary Key
ALTER TABLE `table` DROP PRIMARY KEY;
ALTER TABLE `table` ADD PRIMARY KEY (`new_key`);
ALTER TABLE SO1 MODIFY COLUMN ID INT AUTO_INCREMENT;

To see the final result:
DESCRIBE `table`;

And, you will have your original "primary key" to check, and the new Primary Key with unique integers for each row.
And to work in your case, the "function" will be:
select `new_key` from `table` where `pkey` = 'AX36543TXQ';

Assuming the result of the select above being '17', your "reverse function" will be:
select `new_pkey` from `table` where `new_key` = 17;


Learn to use GIT with Wordpress and a hosting

Question: I normally build my projects using Wordpress , but with the "cowboy approach" of using a FTP client to logg in to the host and edit the files there... a bit old school technique that I need to stop ASAP.
I want to learn to use GIT with WP and my hosting, Bluehost, but I cannot find a guide or document that explains how to achiev this.
Is a bit useless maybe because Im the only user, only person who edits this. But in the future I know GIT is going to be definitive tool to know to get a good , better job.
HOw can I begin to implement this change in my life?
Added details:
Im using Bluehost. I understand I can use GIT with them. But is there a guide to implement WP and git?
Comment: What sort of hosting is it? Can you ssh in and run commands? Can you install things? or is it shared hosting?
Comment: added details : bluehost hosting. allows ssh
Answer: One way I have made this work, is using two tools:
1) git deployment tutorial here
2) WP Command line http://wp-cli.org/
If you can install stuff on the host and ssh in, then you can set up a git repository on the server, set it up as a remote (e.g. called "deployment"), and push to it from your dev environment. Install a simple post-receive hook, which checks out your code into the website.
The master branch is checked out on the website, with the local remote set as the origin. When you push the master branch to the web server, you will need to log in with the ssh credentials (or set up a key). Once git receives this update, it runs the post-receive hook, which can simply cd to the working directory, and do a pull -q. This pulls from the master branch which has just been pushed from your dev. It all happens extremely quickly and reliably when it's all set up.
I'd recommend installing WP normally, then allowing it to manage its own updates internally. Don't try to do WP via git it gets pretty complicated.
Your code is probably a plugin, so the repository mentioned above would checkout to your plugin folder (the working directory).
Be careful to not modify any of the files on the server (in your working directory) else you may get conflicts and failures to deploy. But it sounds like you want to stop being a cowboy :) Of course you need to ensure the plugin doesn't write to files itself, e.g. temp files, caches etc. or at least craft git ignores to deal with them.
Then finally if you need to trigger anything in WP after your deploy your code, you can add wp-cli commands to the git post-receive hook.
Sorry if these aren't beginner-level topics! But it gives you a starting point.


Tipo de relacionamento entre as tabelas(Laravel)

Question: estou implementando meu TCC, sobre fotos e tal..
Mas agora me pegou uma dúvida na hora de criar as tabelas...
Estou usando Laravel ok?
Seguinte, tenho as seguintes tabelas:
<code>users - roles - photos - tags
</code>
funciona da seguinte maneira:
Existem funções de:
1) Fotografo
2) Cliente(que seria o cliente do fotografo)
Ou seja, um fotógrafo terá vários clientes.
Na table photos, eu havia pensado nas colunas:
<code>|  photos       |
| id            |
| path          |
| imageable_id  |
| imageable_type|
</code>
O imageable_type porque  por exemplo, o fotógrafo terá a imagem de perfil dele, o cliente tambem, o fotografo poderá ter imagem da empresa, e quando houve um ensaio fotografico, haverá várias fotos linkando o fotografo ao cliente. Mas nesse caso estaria faltando uma coluna para vincular o fotografo com o cliente?
Para as tags
<code>| tags           |
| id             |
| description    |
| taggable_id    |
| taggable_type  |
</code>
Este eu creio que seja mais fácil porque o type, ou vai ser uma tag para a foto ou vai ser uma tag para um ensaio, somente isso...
Mas em relação a photos mesmo, que tipo de relacionamento é? Polimorphic ManyToMany??
Espero que tenha explicado com êxito, obrigado!
Answer: Eu vejo alguns relacionamentos...
Seguindo a ideia do negócio (me corrija se precisar de adaptação):
<code>**Users** (contém Cliente e Fotográfo)
id
nome
cpf
login
senha
ft_perfil
> outros dados, se necessário
</code>
*Login e senha, você pode por numa tabela apartada para um controle de quando a pessoa errar senha ou quiser trocar e manter um histórico para não permitir senhas iguais. Ficaria:
<code>**acesso**
id_user (fk da Users)
login
senha
nr_tentativas (definir limite de tentativas quando a pessoa errar)
status (bloqueado, ativo, inativo)
</code>
Como fotográfo possui n clientes:
<code>**r_fotografo_cliente**
id_fotografo (fk da users)
id_cliente (fk da users)
dt_associacao (data em que o fotografo foi associado a este cliente)
(ambos FK da user)
</code>
Como essa combinação de formada, há fotos...
<code>**fotos**
id_fotografo (FK da r_fotografo_cliente para não perder a integridade!)
id cliente (FK da r_fotografo_cliente para não perder a integridade!)
path
imageable_id
imageable_type
</code>


Error while creating calculated field in Tableau

Question: I have a Baseball Player Data file. I want to create a calculated column called "Quadrant" which will categorise the types of players into 4 categories.
My code is:
CASE

WHEN ([OBP]<=PERCENTILE([OBP],50)) AND ([BB/K]<=PERCENTILE([BB/K],50))
THEN "Banjo Hitter"
WHEN ([OBP]<=PERCENTILE([OBP],50)) AND ([BB/K]>PERCENTILE([BB/K],50))
THEN "Patient Hitter"
WHEN ([OBP]>PERCENTILE([OBP],50)) AND ([BB/K]<=PERCENTILE([BB/K],50))
THEN "Solid Hitter"
WHEN ([OBP]>PERCENTILE([OBP],50)) AND ([BB/K]>PERCENTILE([BB/K],50))
THEN "Top Performer"
END

here OBP and BB/K are calculated fields. The 50th percentile is the median.
I am getting an error that says "Syntax error: maybe you are missing an identifier".
Can anyone help me figure out what my mistake is? I am new to tableau and practicing examples.
Answer: The percentile expression can be as per below image:

The below calculation is valid.
IF [OBP]<= { FIXED : PERCENTILE([OBP],0.50) }AND [BB/K]<= { FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Banjo Hitter"

    ELSEIF  [OBP]<= { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]>{ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Patient Hitter"

    ELSEIF [OBP]> { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]<={ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Solid Hitter"

    ELSEIF [OBP]> { FIXED :PERCENTILE([OBP],0.50)} AND [BB/K]>{ FIXED :PERCENTILE([BB/K],0.50)}
    THEN "Top Performer"

    END

Also for reference Click Here
Comment: Thank you for the answer..I changed the percentile value from 50 to 0.50..then I added ATTR  to get dimension value at the sum level. But I could only create 1 category "Banjo hitter". Others are not getting created.
Comment: Place it as a dimension not as attribute.
Comment: Worked!! Thanks a lot ..:)
Comment: No Problem...:)


Search em várias tabelas

Question: Olá, estou tentando fazer um search em 3 tabelas diferentes, vejam meu código:
$buscando = $pdo->query("SELECT * FROM filmes WHERE nome LIKE '%$busca%' AND status='ativo' ORDER BY nome ASC");

As tabelas seriam: animes, filmes e series. Todas possuem as mesmas colunas, ou seja, seria WHERE nome LIKE '%$busca%' AND status='ativo' para todas.
Tentei realizar usando esse select: SELECT * FROM animes, filmes, series, mas não retornou nada. Poderia me ajudar?
Estruturas das minhas tabelas:
animes:

filmes:

series:

Caso prefiram as imagens hospedadas:

animes: prntscr.com/ga9nw9 || filmes: prnt.sc/ga9o5w || series:
  prnt.sc/ga9occ
Comment: Utilize o comando **Union** do sql, que faz essas junções.
Answer: Olá,
Neste caso você pode usar a cláusula UNION, que junto dois ou mais resultados em um só, segue um exemplo:
SELECT
    *
FROM
    (
        SELECT
            'animes' AS tabela,
            id,
            nome,
            url,
            imagem,
            status,
            null AS destaque
        FROM
            animes
        UNION ALL
        SELECT
            'filmes' AS tabela,
            id,
            nome,
            url,
            imagem,
            status,
            destaque
        FROM
            filmes
        UNION ALL
        SELECT
            'series' AS tabela,
            id,
            nome,
            url,
            imagem,
            status,
            null AS destaque
        FROM
            series
    ) AS t
WHERE
    t.nome LIKE '%a%'
    AND t.status='ativo'
ORDER BY
    t.nome;

Neste exemplo, inclui uma 'coluna' a mais indicando de qual tabela está vindo o registro (primeira coluna). Incluí todas colunas que são comum entre as 3 tabelas e incluí a coluna destaque que existe na tabela filmes e não existe na outra para exemplificar este comportamento que, neste exemplo, deixei como valor padrão nas outras tabela como null.
Criei este exemplo também neste fiddle: https://www.db-fiddle.com/f/jefqxbEkSJxArr4xQus6B2/0
Lembrando que o UNION exige que todos selects devem ter exatamente a mesma quantidade de colunas com os mesmos tipos.
Para ler mais sobre o union você pode consultar a documentação oficial do MySQL: https://dev.mysql.com/doc/refman/5.7/en/union.html
Comment: O problema é que a tabela filmes não tem a mesma quantidade de colunas que as outras duas.
Comment: Então precisa padronizar no select, edita sua pergunta com o schema das tabelas que te ajudo a montar a query ;)
Comment: animes: http://prntscr.com/ga9nw9 || filmes: https://prnt.sc/ga9o5w || series: https://prnt.sc/ga9occ
Comment: Também coloquei na pergunta, caso preferir.
Comment: Editei a resposta ajustando o exemplo ao seu schema :)
Comment: Funcionou perfeitamente, muito obrigado meu amigo!
Comment: Disponha! estamos sempre a disposição!

Search em várias tabelas


Does Brownian motion visit every point uncountably many times?

Question: Let $B_t$ be a one-dimensional standard Brownian motion.

Is it true that, almost surely, for every $x \in \mathbb{R}$ the set $\{t : B_t = x\}$ is uncountable?

Let $A_x$ be the event that $\{t : B_t = x\}$ is uncountable.  It is well known that $\mathbb{P}(A_0) = 1$.  By recurrence and the strong Markov property, we also have $\mathbb{P}(A_x) = 1$ for every $x$.  I am asking about the probability of $A = \bigcap_{x \in \mathbb{R}} A_x$.  Because of the uncountable intersection, it is not even obvious that this set is measurable.
George Lowther in this comment says the answer is yes, but I don't see how to prove it.
Comment: @ Nate Eldredge : Hi here is a naive question, by taking a dense subset $B$ of or $\mathbb{R}$ and using the continuity of Brownian motion, is there a problem to show that $A^B=\bigcap_{x \in B} A_x$ ? Best regards
Comment: @TheBridge: I thought about that a little, but it can't be quite that simple.  For instance, one can construct a continuous function $\gamma$ such that $\{t : \gamma(t)=x\}$ is uncountable precisely when $x$ is rational.  (Enumerate the rationals as $q_0, q_1, \dots$, and let $\gamma(t) = q_n$ for $t \in [2n, 2n+1]$ and piecewise linear in between.)  So something else is needed.
Comment: @ Nate Eldredge: I don't know if this helps but still naively, I just can't help myself thinking about support of Local Times, and remembering about them that Local Times seen as indexed by time and space are jointly continuous (or at least for a good version). Best Regards
Comment: I believe the fact that the local time process is continuous in space follows from the Ray Knight Theorem, which says that the space distribution of the local time is a squared two-dimensional Bessel Process.
Answer: Actually there is an almost sure lower bound on the Hausdorff dimension of the level sets of Brownian motion that follows from the Ray-Knight theorem.
$$ a.s \quad \forall a\in \mathbb{R}, \quad \text{dim}\{t \geq 0 | B(t) =a\} \geq \frac{1}{2}.  $$
This is a theorem (6.48, p. 170) in the book, "Brownian Motion" by Peres and Morters.
Answer: Consider $C_x$ be the event that the set ${t: B_t = x}$ is countable.
For any $x$, the measure of $C_x$ is zero. Countable zero-measure sets union is also a zero-measure set. $A = \bigcap A_x = -\bigcup -A_x = -\bigcup C_x$ and hence has a measure of $1$.
Comment: ... but $\bigcup_x C_x$ is an uncountable union ...
Comment: Sure. I misread the question, thinking you're asking about simple random walk.


Scope buttons hiding behind the UITableview

Question: I am creating a search screen using UISearchController, in which I have to show three scope buttons.I have put search bar programmatically.But somehow the scope buttons are hiding behind the UITableView.
<code>- (void)viewDidLoad {
    [super viewDidLoad];
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = NO;
    self.searchController.searchBar.delegate = self;
    self.tblFoundList.tableHeaderView = self.searchController.searchBar;
    self.definesPresentationContext = YES;
    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setDefaultTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
    [[UITextField appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"Search by" attributes:@{NSForegroundColorAttributeName: [UIColor lightGrayColor]}]];
    self.searchController.searchBar.tintColor = [UIColor purpleColor];
    self.searchController.searchBar.barTintColor = [UIColor groupTableViewBackgroundColor];
    self.searchController.searchBar.scopeButtonTitles = @[@"A",@"B", @"C"];
    [self.searchController.searchBar sizeToFit];
}
</code>

Could anyone help in this? Thank you.
Comment: Are you using autolayout?
Comment: @iPeter I have put it programmatically, no auto layout.
Comment: Then please check the frame of your `tableview` and the `buttons`. As per the screenshot it seems like the `y position` of your `tableview` is incorrect.
Comment: try giving height of tableHeaderView, in which OS u are checking this ? iOS11 provides default header height which may cause this issue. changing table header height should work.
Comment: @iPeter, I tried changing the y position of the TableView created by me, yet it showed no results. But thank you for help
Comment: @torap I tried increasing the height of the header height too but even that didn't seem to work. Thanks for help
Comment: Can you show your `storyboard`? @SimerynDenis
Answer: As I mentioned earlier I had created UISearchController programmatically, so the UITableview in the image is UISearchController's UITableview, that is why nothing was affecting it.
So I got help from
UISearchController Search Bar Position Drops 64 points
and
UISearchBar presented by UISearchController in table header view animates too far when active
<code>- (UIBarPosition)positionForBar:(id<UIBarPositioning>)bar
    {
      if (bar == self.searchController.searchBar) {
        return UIBarPositionTopAttached;
      }
      else { // Handle other cases
        return UIBarPositionAny;
      }
    }
</code>
On adding following method the search bar got shifted up and the scope buttons were visible.
But thank you all for helping out.


Reducing the number of variables in a multiple regression

Question: I have a large data set consisting of the values of several hundred financial variables that could be used in a multiple regression to predict the behavior of an index fund over time.  I would like to reduce the number of variables to ten or so while still retaining as much predictive power as possible.  Added: The reduced set of variables needs to be a subset of the original variable set in order to preserve the economic meaning of the original variables.  Thus, for example, I shouldn't end up with linear combinations or aggregates of the original variables.
Some (probably naive) thoughts on how to do this:

Perform a simple linear regression with each variable and choose the ten with the largest $R^2$ values.  Of course, there's no guarantee that the ten best individual variables combined would be the best group of ten.
Perform a principal components analysis and try to find the ten original variables with the largest associations with the first few principal axes.

I don't think I can perform a hierarchical regression because the variables aren't really nested.  Trying all possible combinations of ten variables is computationally infeasible because there are too many combinations.

Is there a standard approach to tackle this problem of reducing the number of variables in a multiple regression?

It seems like this would be a sufficiently common problem that there would be a standard approach.
A very helpful answer would be one that not only mentions a standard method but also gives an overview of how and why it works.  Alternatively, if there is no one standard approach but rather multiple ones with different strengths and weaknesses, a very helpful answer would be one that discusses their pros and cons.
whuber's comment below indicates that the request in the last paragraph is too broad.  Instead, I would accept as a good answer a list of the major approaches, perhaps with a very brief description of each.  Once I have the terms I can dig up the details on each myself.
Comment: [This reply](http://stats.stackexchange.com/a/14528/919) gives a concrete example of one of the (many) problems with method 1. A comment by @cardinal to Frank Harrell's reply gets to the crux of the problem with method 2: anything you do with the independent variables alone, without considering their relationships to the dependent variable, risks being irrelevant or worse.  As far as standard or "canonical" answers go, asking for one here is a bit like asking for a discussion of all the methods to find rational points on elliptic curves, with their pros and cons :-).
Comment: As noted by others here, method 1 will lead to problems.  For an intuitively accessible treatment of why that's true / a description of another one of the issues with this approach, you may want to read this: http://stats.stackexchange.com/questions/20836/algorithms-for-automatic-model-selection/20856#20856
Comment: Mike, you might browse through Chapter 3 of [ESL](http://www-stat.stanford.edu/~tibs/ElemStatLearn/), if you are unfamiliar with it. The page at the link provided points to a free, legal PDF of the text.
Comment: Can you clarify if you are looking to only keep, say, ten of the original variables or would also be interested in methods that use a small subset of linear combinations of the original variables (the latter being what something like a traditional principal-components regression would give you).
Comment: @cardinal: I would like to keep ten or so of the original variables, not linear combinations of them. Each variable has a particular economic meaning, whereas taking linear combinations would lose that: We need to preserve the meaning aspect of the explanatory variables. And thanks for the ESL pointer. I'll take a look at it.
Answer: Method 1 doesn't work.  Method 2 has hope depending on how you do it.  It's better to enter principal components in descending order of variance explained.  A more interpretable approach is to do variable clustering, then reducing each cluster to a single score (not using Y), then fit a model with the cluster scores.
Comment: It does not seem like there is any *a priori* reason to believe that the directions of maximal variance of the *predictors* are necessarily highly correlated with the *response*. Perhaps I'm mistaken or have misunderstood your comment. Could you clarify?
Comment: Also, it sounds like the OP is not (quite) describing principal-components regression in his Method 2.
Comment: Variable clustering is related to factor analysis but is simpler.  Variables are grouped in how they correlated with each other.  See the `varclus` function in the R `Hmisc` package, or PROC VARCLUS in SAS.  Data reduction can help with subsetting variables if you exercise a bit of caution; you can remove an entire cluster if its $P$-value is 0.3.  With principal components there are techniques such as battery reduction where you essentially approximate the PCs with a subset of their constituent variables.
Comment: +1. By "variable clustering", do you mean *factor analysis*--that's a strategy I might use (also before looking at y).  I think of cluster analysis as grouping observations rather than variables, but I have only superficial knowledge of cluster analyses.
Comment: I wasn't completely clear in my original post, but I need a *subset* of the original variables.  So a straight principal components analysis or clustering isn't really what I'm after.
Answer: You might consider using a method like LASSO that regularizes least squares by selecting a solution that minimizes the one norm of the vector of parameters.  It turns out that this has the effect in practice of minimizing the number of nonzero entries in the parameter vector.    Although LASSO is popular in some statistical circles many other related methods have been considered in the world of compressive sensing.
Comment: Thanks.  I'll look up LASSO. (It looks like it's mentioned in the reference cardinal gives, too.)
Answer: In chapter 5 of Data Mining with R, the author shows some ways to choose the most useful predictors. (In the context of bioinformatics, where each sample row has 12,000+ columns!)
He first uses some filters based on statistical distribution. For instance, if you have half a dozen predictors all with a similar mean and s.d. then you can get away with just keeping one of them.
He then shows how to use a random forest to find which ones are most useful predictors. Here is a self-contained abstract example. You can see I've got 5 good predictors, 5 bad ones. The code shows how to just keep the best 3.
set.seed(99)

d=data.frame(
      y=c(1:20),
      x1=log(c(1:20)),
      x2=sample(1:100, 20),
      x3=c(1:20)*c(11:30),
      x4=runif(20),
      x5=-c(1:20),
      x6=rnorm(20),
      x7=c(1:20),
      x8=rnorm(20,mean=100, sd=20),
      x9=jitter(c(1:20)),
      x10=jitter(rep(3.14, 20))
      )

library(randomForest)
rf=randomForest(y ~ ., d, importance=TRUE)
print(importance(rf))
#         %IncMSE IncNodePurity
# x1  12.19922383    130.094641
# x2  -1.90923082      6.455262
# ...

i=importance(rf)
best3=rownames(i)[order(i[, "%IncMSE"], decreasing=TRUE)[1:3]]
print(best3)
#[1] "x1" "x5" "x9"

reduced_dataset=d[, c(best3, 'y')]

The author's last approach is using a hierarchical clustering algorithm to cluster similar predictors into, say, 30 groups. If you want 30 diverse predictors you then choose one from each of those 30 groups, randomly.
Here is some code, using the same sample data as above, to choose 3 of the 10 columns:
library(Hmisc)
d_without_answer=d[,names(d)!='y']
vc=varclus(as.matrix(d_without_answer))
print(cutree(vc$hclust,3))
# x1  x2  x3  x4  x5  x6  x7  x8  x9 x10
#  1   2   1   3   1   1   1   2   1   3

My sample data does not suit this approach at all, because I have 5 good predictors and 5 that are just noise. If all 10 predictors were slightly correlated with y, and had a good chance of being even better when used together (which is quite possible in the financial domain), then this may be a good approach.
Answer: This problem is usually called Subset Selection and there are quite a few different approaches. See Google Scholar for an overview over related articles.
Comment: Anothr search term is [tag:feature-selection]


Palindrome Using Stack Data Structure

Question: Problem:
Write a Python program that takes user input of a word and determines if it is a Palindrome or not using the Stack data structure.
A palindrome is a word that can be read the same backward as forward. Some examples of palindromic words are noon, civic, radar, level, rotor, kayak, reviver, racecar, redder, madam, and refer.
The following code is what I've done so far and need help to make it compile correctly:
import Stack

def palidromeChecker(words):
palidromestack = Stack.Stack()

words = user_input("Type a word: ")
for x in words:
 palidromestack.push(x)
palindrome = True
for x in words:
 if x != palidromestack.top():
    palindrome = False
break
palidromestack.pop()
if palindrome:
print (words, "is a palindrome")
else:
print (words, "is not a palindrome")

Comment: `import Stack`!! Where did you get that module from? can you also mention the error you are receiving ?
Comment: @Unni I am using python 3.6 and was told you to use import Stack when creating a stack.  Hence the palidromestack = Stack.Stack() declaration.
Comment: `Stack` is not a stdlib module. Where did you get it?
Comment: As far as I know, you can use `list` as a stack. I don't see a `Stack` module in Python 3 docs https://docs.python.org/3/tutorial/datastructures.html#using-lists-as-stacks
Comment: The closest thing I can find is [this](https://stackoverflow.com/questions/19413735/trying-to-stop-an-error-with-stacks-in-python). Is the same `Stack` module what we're looking at here?
Answer: No one seems clear on what a Stack is, so let me show you how you might do this with a collections.deque
import collections

def palindrome_checker(word):
    # casefold the word, since "Racecar" is a palindrome just like "racecar"
    q = collections.deque(word.casefold())
    while True:
        try:
            l, r = q.popleft(), q.popright()
        except IndexError:
            # we've reached the end without error!
            return True
        else:
            if l != r:
                return False

That said the canonical palindrome checker in python is just:
def palindrome_checker(word):
    word = word.casefold()  # as before
    return word == word[::-1]

Slicing a string with [::-1] says "Give me back this string, unbounded on each end, in reverse order." This is equivalent to str(reversed(word))
Comment: as it happens, this is the rare case where it's about as short in Haskell as it is in Python. `isPalindrome s' = let s = map toLower s' in s == reverse s` (with `toLower` imported from Data.Char)
Answer: Sorry about the stack confusion
I changed the code to the following and it seems to be working:
class Stack:
def __init__(self):
    self.items=[]

def isEmpty(self):
    return self.items==[]

def push(self,data):
    self.items.append(data)

def size(self):
    return len(Self.items)

def show(self):
    print (self.items)

def peek(self):
    return self.items[len(self.items)-1]

def pop(self):
    assert not self.isEmpty()
    return self.items.pop()

word=input("Enter a word: ")
s=Stack();

for i in word:
 s.push(i)

list1 = ""
while not s.isEmpty():
 list1 += s.pop()

if(list1 == word):
print(word,"is a palindrome");
else:
print(word,"is not a palindrome");

Palindrome Using Stack Data Structure


Minimum of Pairwise-Independent Variables

Question: Given $X_{1},\dots, X_{n}$ which are uniform on unit interval $[0,1]$, and pairwise independent, i.e. $X_{i}$ and $X_{j}$ are independent for $1\leq i,j\leq n$. Show that $$\Theta\left(\frac{1}{n}\right)\leq \mathbb{E}[\min(X_{1},\dots,X_{n})] \leq \Theta\left(\frac{\log{n}}{n}\right).$$
For the lower bound by Markov's inequality,
$$\Pr(\min(X_{1},\dots,X_{n})\geq a) \leq \frac{\mathbb{E}[\min(X_{1},\dots,X_{n})]}{a}$$
By Union Bound,
$$\Pr(\min(X_{1},\dots,X_{n})\geq a) = \Pr(X_{1}\geq a,\dots,X_{n}\geq a)\geq 1-\sum_{i}\Pr(X_{i}\leq a)=1-n\cdot a.$$
Plugging back in
$$\mathbb{E}[\min(X_{1},\dots,X_{n})]\geq \max_{0\leq a\leq 1}{a(1-na)}=\frac{1}{4n}.$$ For uniform i.i.d. variables we establish that the lower bound is tight.
I don't know how to prove the upper bound.
Comment: Where does $P(A_1 \cap \cdots \cap A_n) \ge 1 - P(A_1 \cup \cdots \cup A_n)$ come from? A counterexample for this is $A_1 = \cdots = A_n$ and $P(A_1) < 1/2$.
Comment: Are your $X_{ij}$ really uniformly distributed (and pairwise independent) in your example? https://en.wikipedia.org/wiki/Triangular_distribution
Comment: I meant the union of the complement of the sets.
Comment: Now, I remember that rolling a 7 on two dice is more likely than rolling a 2 :). @ClementC.
Comment: Last line should be $\max_{0 \le a \le 1} (a(1-na)) = \frac{1}{4n}$?
Comment: What about addition mod 2? @ClementC. I think that might work.
Comment: @angryavian yes indeed.
Comment: Where does the problem come from?
Comment: It comes up when talking about this algorithm: https://en.wikipedia.org/wiki/Flajolet%E2%80%93Martin_algorithm @Zhanxiong.
Answer: I can give an upper bound of $O\left(\frac{\log n}{n}\right)$.
For $t\in(0,1)$ let $N_t$ be the number of samples among $X_1,\dots,X_n$ that are at most $t$. Then $\mathbb EN_t=nt$ and pairwise independence implies that $\operatorname{Var}N_t=nt(1-t)$. Then by the second moment method
$$\mathbb P(\min X_i\leq t)=\mathbb P(N_t>0)\geq\frac{\mathbb E[N_t]^2}{\mathbb E[N_t^2]}=\frac{nt}{nt+(1-t)}.$$
So we have
$$\mathbb E[\min X_i]=\int_0^1\mathbb P(\min X_i>t)\mathop{}\!\mathrm{d}t\leq\int_0^1\frac{1-t}{(n-1)t+1}\mathop{}\!\mathrm{d}t=\frac{n\log n}{(n-1)^2}-\frac{1}{n-1},$$
establishing the upper bound.
Comment: I didn't know of the second moment method, it seems to work. Do you have an idea for a construction?
Comment: @Ethan I don't know what "the second moment method" exactly is either, but to derive the inequality $P[N_t > 0] \geq (E[N_t])^2/E[N_t^2]$, just notice $E[N_t] = E[N_tI_{\{N_t > 0\}}] \leq \sqrt{E[N_t^2] \times P[N_t > 0]}$, by Cauchy-Schwarz inequality.


pegar o resultado de uma função e enviar via post em outra

Question: estou usano a lib instascan para ler qr code. mas não estou conseguindo enviar o resultado via post com ajax. alguem pode ajudar?
O código que estou usando está abaixo:

  qr sacanner

qr scanner

<video id="preview"></video>

Comment: O data tá com o valor '', deveria ser content, não? Pra isso você criaria uma variável global pra receber o valor de content no listener do scanner e passaria no atributo data essa variável.
Answer: Você está chamando a função gravar(content) enviando o valor de content, então deve colocar na função o respectivo parâmetro para receber esse valor, e jogar no data do Ajax:
function gravar(content){
   $.ajax({
      method: "POST",
      url: "dados.php",
      data: { codigo: content },
      success: function(data){
         alert(data.teste);
      }
   });
}

Na página PHP (dados.php) você recebe o valor com $_POST['codigo'].


How to prove that for element $c\in R,\ c^2=c \Rightarrow c\in C(R)$?

Question: Let $R$ be an associative ring. Let $C(R)=\{a\in R: ab=ba\; \forall b\in R\}$. Let $a^2=0 \Rightarrow a=0\; \forall a\in R$. How to prove that for element $c\in R,\ c^2=c \Rightarrow c\in C(R)$?
Comment: Let $x, y\in R$ and try your conditions on $x+y\in R$.
Answer: Let $c \in R$, such that $c^2=c$. Let $b \in R$. Note that
$$(c(b-bc))^2 = cbcb-cbcbc-cbc^2b+cbc^2bc = cbcb-cbcbc-cbcb+cbcbc = 0$$, so $c(b-bc) = 0$, i.e. $cb = cbc$.
Analogously get $((b-cb)c)^2 = 0$ and $bc = cbc$. Thus $bc = cb$.


How do I set custom trigger for comparing old value with new one and executing function depending on result?

Question: I need an actual working gs code for this but I cant seem to find the correct function for this so I scraped an explainable version of this, it works like an onEdit function
function(value, modifier) {
 if (value < modifier) = setBackground("red");
}

function(value, modifier) {
 if (value > modifier) = setBackground("blue");
}

what I want:

change cell color and cell highlight color to red if new input value is greater than previous one
change cell color and cell highlight color to blue if new input value is less than previous one
Answer: onEdit(e) has in the event object with properties e.value and e.oldValue so if you enter a new value in the cell you could use that to compare to the value that was previously in the cell.
function onEdit(e) {
  if( e.value > e.oldValue ) {
    e.range.setBackground("red");
  }
  else if( e.value < e.oldValue ) {
    e.range.setBackground("blue");
  }
  else {
    // value didn't change
    e.range.setBackground(null);
  }
}

Reference

onEdit event object


Problem when installing package using RPM

Question: I'm new to Linux, currently using RHEL 5.
I want to install some package on my Server but there is an error:
rpm: error while loading shared libraries: libstdc++.so.6: cannot open shared object file: No such file or directory.
Note: before this error occured, I have installed libstdc++2.10-2.96-0.83mdk.i586.rpm, which is the dependency of nxclient-3.4.0-5.i386.rpm
Any idear pls?
Sarith
Answer: I agree with @wzzrd.
Additionally you can perform the following steps in order to restore you system stability:

add EPEL repo to your /etc/yum.repos.d:

su -c 'rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-3.noarch.rpm'

find which package provides libstdc++.so.6:

yum provides */libstdc++.so.6

(re-)install this package
remove the wrong rpm:

rpm -e --force libstdc++2.10-2.96-0.83mdk.i586.rpm
Answer: You are trying to install RPM's made for Mandriva on your RHEL box. Try and find packages that are specifically built for RHEL. Try rpmforge, the EPEL repository or the vendor website, and look for RPM's that have .el5 instead of mdk in the filename.
Answer: There was a similar question asked about CentOS workstations, which I posted some example <code>.repo</code> file content to: What issues should I watch for when rolling out CentOS as a desktop environment?