What is the reason that equations such as $\tan x = 2x$ can only be solved with the help of algorithms?

Question: This is my first StackExchange question:
What is the reason that equations such as $\tan x = 2x$, $\cos x = x$, $\sin(x) = x^2$ and other questions that involve the same variable within a trigonometric function and outside the trigonometric function can only be solved with computer algorithms and have extremely complex closed forms; such as the Dottie number, the root of $\cos x = x$, having the mind-blowing closed form $\sqrt{1-\left(2I_{\frac{1}{2}}^{-1}\left(\frac{1}{2},\frac{3}{2}\right)-1\right)^2}\,,$ which is really fascinating to me.
For $\cos x = x$, I tried solving the equation using the complex definition of $\cos x$ (aka. the cooler version of cosine), $\frac{e^{ix}+e^{-ix}}{2} = x$ but after using a quadratic formula to solve for $e^{ix}$, I found that I just ended up with $x$ being equal to the complex definition of inverse cosine (arccos) in the formula $x = -i\ln(x + \sqrt{x^2-1})$ and I had gone around in circles, I thought "Is this really an impossible equation to solve for $x$?" The sum inside the natural logarithm, the $i$ being present in the equation even though the Dottie number is a real number approximately $0.739085$... and the $\sqrt{x^2-1}$, I had seen that thing everywhere in Pythagoras and trigonometric calculus. It's as if mathematics had put as many barriers around the $x$ as possible to prevent you from solving for $x$. And I had a similiar problem with $\sin x = x$, I knew for a fact that the solution was definitely $0$ and yet the "solution" I got was total garbage that looked nothing like $0$. And apparently this equation also had infinitely many complex solutions as well, which I don't grasp at all.
These equations look so simple from first glance and yet are mathematically impossible for a human to solve for an exact form, but why is that? is it something to do with "transcendental numbers"? Does it have any applications in trigonometry and calculus?
Comment: There's just a very specific set of functions that count as "closed forms" and most interesting questions can't be answered exactly in terms of them. In a typical mathematics education this fact is thoroughly hidden from you because teachers are careful to only show you questions which *do* have closed form answers. "Random" mathematical questions simply don't.
Comment: The solution can't have a closed form when the equation is composed of different kind of functions such $x e^x = 1$, $x + \ln x = 2$, $\sin x + e^x = x^2$ ...
Comment: The answer by Qiaochu Yuan is excellent. I will add that the little society of "elite functions" accept to integrate newcomers having a sufficiently good Vitae. For example "cardinal sine" function which is $\operatorname{sinc}(x)=\frac{\sin(x)}{x}$ (with the exceptional value $\operatorname{sinc}(0)=1$ encountered in equations like $\sin x = 0.1 x$ has been "ennobled" around 100 years ago (in particular for its role in Fourier Transform). Same thing for Lambert function $W$, for a certain number of "special functions" like Airy, etc. discovered mainly in the 19th century.
Comment: @Essaidi Not only. For instance polynomials of degree $5$ or more are generally not solvable so for such a polynomials $P(x)=2x$ likely too, yet both sides are the same types (i.e. polynomials). The impossibility of finding a closed form is not limited to the so called transcendental equations.
Comment: See [here for the inverse of $2\tan(x)-x$](https://math.stackexchange.com/questions/4526080/change-of-variable-to-the-arclength-for-y-sec2x/4526793#4526793), a similar problem
Comment: When you want to address a comment to some one, in the body, add @user_name. If you ask the question about why $\frac \pi 4$, I chose it because it is the simplest angle close to the solution and which gives nice coefficients in th first expansion.
Comment: Glibly: Undoing things is harder than doing things.
Comment: @Essaidi obviously, $x e^x = 1$ has solution $W(1)$, $x + \ln x = 2$ has solution $W(e^2)$, you can verify it using Wolfram Alpha.
Comment: I'm talking about expressing solution with elementary functions. Other way, one can always write: the solution of $a = f(x)$ is $x = f^{-1}(a)$ when $f$ is bijective.
Answer: I love your question, and while I won't be able to put into words a complete answer that does it justice, I hope to provide enough intuition to get you thinking and find your own satisfying answer.
First of all, I bring to your attention that working with "complex closed form" expressions is not new to you, and in fact you've been working with them for most of your mathematical life. Indeed, $\cos x$, $\sin x$, $e^x$, $\log x$, and even something as "elementary" as $\sqrt{2}$ are "complex closed form" expressions. They are just expressions that appear so often, and that we use so much, and that we know so many properties about, that we just consider them as part of the "not complex" repertoire. Two thousand or so years ago, a mathematician just like you would look at $x^2 = 2$ and say that it can only be solved with a "computer" algorithm that approximates the answer and has an extremely complex closed form with a weird v-shaped symbol. What you are experiencing is not the exception, it is the rule!
More generally, some objects of interest appear sufficiently often in math that it is simpler, more elegant, and more efficient to give them their own symbol  and add them to our "fundamental repertoire". As an analogy, say that you and I develop a language with only two letters, say $a$ and $b$, and when we communicate, the word $ababababa$ keeps appearing all over the place. It is only natural to decide after some time that rather than repeating that monstrosity every time, we just invent a new letter, call it $c$, and just refer to $c$ from now on. If you are familiar with information theory, this is exactly what compression theory aims to achieve! And notation such as $\cos x$ and $\sqrt{2}$ are just convenient "letters" we added to our alphabet. The solution to $cos x = x$ simply does not appear often enough for mathematicians to bother developing syntax around it. Most of math starts with very few extremely basic symbols, such as $1,2,+,x^2$ etc then develops problems and solutions with those symbols, then develops new symbols to make doing math more efficient, for example by associating the symbol $\sqrt{2}$ to the chain of symbols $x^2=2$.
Comment: Perfect answer with perhaps just one thing missing. You focus essentially on beauty - although that word is not approved of by everyone. What needs to be added is the *faith* of the mathematician - which is that "Beauty is truth, truth beauty". We don't just say $sin$ because it's a short way of saying "sine". We say it because the abbreviation, as well as being beautiful, is true and leads to truth. (The thing that everyone believes but nobody is allowed to say is that there is an element of "**because of** being beautiful" in that sentence).
Comment: Very nice answer! In the beginning there was only 0 and the successor function and we built an empire out of these humble beginnings.
Comment: You could extend the definition of $a^b$ to fractions and ignore the square root notation since $\sqrt 2=2^\frac12$
Answer: If we want a complete and mathematical correct answer, we have to translate the question into mathematical terms. What you mean is: What is the reason that such equations cannot be solved by applying only finite numbers of elementary functions/operations?
It's a kind of closed-form problems. That means, solutions in closed form are wanted.
Note that I'm reflecting only my personal findings here.
The term $\mathbb{C}$-algebraic means "algebraic over $\mathbb{C}$".
The problem of solving a given equation can be split into two mathematical sub-problems. Let $F$ be a function, $x$ a variable and $c$ a constant. Let the equation $F(x)=c$ be given. If we find the inverse relation $F^{-1}$ of $F$ (that means the appropriate partial inverses of $F$), the solutions of the equation can be found by applying $F^{-1}$: $F^{-1}(F(x))=F^{-1}(c)$, $x=F^{-1}(c)$.
The second mathematical sub-problem is to decide if a solution of the equation can be represented by a closed-form number.
You are asking for solutions that can be represented by elementary expressions (means function terms of elementary functions) or by elementary numbers.
According to Liouville, the elementary functions are generated by applying only finite numbers of only $\exp$, $\ln$ and/or unary or multiary $\mathbb{C}$-algebraic functions. Each elementary standard function (i.e. the trigonometric functions, the hyperbolic functions, the arcus functions, the inverse hyperbolic functions) can be represented in that form.
1) Applying the inverse relation
1 a) Ritt's theorem
We have the main theorem of [Ritt 1925], that's also proved in [Risch 1979], for deciding if a given elementary function can have partial inverses with non-discrete domains that are elementary functions. I call it structure theorem about elementary invertible elementary functions. With help of Ritt's theorem, we can conclude that the elementary functions that have elementary partial inverses with non-discrete domains are generated by applying only finite numbers of only $\exp$, $\ln$ and/or unary $\mathbb{C}$-algebraic functions.
But your equations are multiary $\mathbb{C}$-algebraic equations. Your functions $F$ are multiary $\mathbb{C}$-algebraic functions therefore. That means, your functions $F$ don't have partial inverses with non-discrete domains that are elementary functions.
The following is my own conclusion:
That means your kind of equations cannot be solved by rearranging them by applying only finite numbers of elementary functions/operations we can read from the equation.
[Risch 1979] Risch, R. H.: Algebraic Properties of the Elementary Functions of Analysis. Amer. J. Math. 101 (1979) (4) 743-759
[Ritt 1925] Ritt, J. F.: Elementary functions and their inverses. Trans. Amer. Math. Soc. 27 (1925) (1) 68-90
1 b) Khovanskii's Topological Galois theory
[Khovanskii 2014]:
"Vladimir Igorevich Arnold discovered that many classical questions in mathematics are unsolvable for topological reasons. In particular, he showed that a generic algebraic equation of degree 5 or higher is unsolvable by radicals precisely for topological reasons. Developing Arnold's approach, I constructed in the early 1970s a one-dimensional version of topological Galois theory. According to this theory, the way the Riemann surface of an analytic function covers the plane of complex numbers can obstruct the representability of this function by explicit formulas. The strongest known results on the unexpressibility of functions by explicit formulas have been obtained in this way.
...
The monodromy group of an algebraic function is isomorphic to the Galois group of the associated extension of the field of rational functions. Therefore, the monodromy group is responsible for the representability of an algebraic function by radicals. However, not only algebraic functions have a monodromy group. It is defined for the logarithm, arctangent, and many other functions for which the Galois group does not make sense. It is thus natural to try using the monodromy group for these functions instead of the Galois group to prove that they do not belong to a certain Liouville class. This particular approach is implemented in one-dimensional topological Galois theory ...
...
Nevertheless, the set of singular points of an elementary function is at most countable, and its monodromy group
is solvable. If a function does not satisfy these restrictions, then it cannot be elementary."
[Khovanskii 2014] Khovanskii, A.: Topological Galois Theory - Solvability and Unsolvability of Equations in Finite Terms. Springer 2014
[Khovanskii 2019] Khovanskii, A.: One dimensional topological Galois theory. 2019
[Khovanskii 2021] Topological Galois Theory - Slides 2021, University Toronto
Khovanskii's publications
[Belov-Kanel/Malistov/Zaytsev 2020] Belov-Kanel, A.; Malistov, A.; Zaytsev, R.: Solvability of equations in elementary functions. Journal of Knot Theory and Its Ramifications 29 (2020) (2) 204-205
$\ $
see also:
Conditions to be able to write down the inverse function as a closed-form expression
How do we know if a function has an elementary inverse?
Proving a Problem has a Closed Form Solution
Resolution of symbolic equations
Why some inverse functions do not have a closed form
2) Solutions in the Elementary numbers
A given equation can have solutions that are representable by an elementary number even if the function $F$ doesn't have an elementary partial inverse with non-discret domain. But we cannot find this representation by only rearranging the equation by only applying finite numbers of elementary functions.
Your equations can be rearranged to irreducible polynomial equations over $\overline{\mathbb{Q}}$ in dependence of $x$ and $e^x$. Therefore the main theorems in [Lin 1983] and [Chow 1999] can be used. They state that those kinds of equations don't have solutions except $0$ in the Elementary numbers or Explicit elementary numbers respectively.
And it follows with my theorem in Proof Check: Non-existence of the inverse function in a given class of functions that the function $F$ of these kind of equations cannot have partial inverses with non-discrete domains that are elementary functions.
[Chow 1999] Chow, T.: What is a closed-form number. Am. Math. Monthly 106 (1999) (5) 440-448
[Lin 1983] Ferng-Ching Lin: Schanuel's Conjecture Implies Ritt's Conjectures. Chin. J. Math. 11 (1983) (1) 41-50
see also Trigonometric/polynomial equations and the algebraic nature of trig functions
3) Non-applicability of Lambert W
Some kinds of $\mathbb{C}$-algebraic equations that contain simultaneously $x$ and $e^x$ can be solved in terms of Lambert W. Lambert W isn't an elementary function, but solving equations by applying Lambert W can be done manually.
Your kind of equations are non-symmetrical $\mathbb{C}$-algebraic equations that depend simultaneously on $x$ and $e^{ix}$ wherein the degree of $e^{ix}$ is greater than $1$. This kind of equations cannot be solved in terms of Lambert W.
Answer: Congratulations for a so well-posed first question on this site to which I welcome you !
As said in comments, very few transcendental equations have a closed form and when they have, they express in terms of special functions.
@Tyma Gaidash (in particular) gave a few of them; they are nice, beautiful and interesting. For example (have a look here) Laplace's limit constant corresponds to the solution of
$$ e^{-2x}=\frac{x-1}{x+1}\quad \implies \quad x=\frac{1}{2}W\left({+2\atop -2};1\right)$$ this is an exact solution in terms of the generalized Lambert function but for computing it
$$x=1+2\sum_{n=1}^\infty\frac{L_{n-1}^{(1)}(4n)}{n}e^{-2n}$$ which is an infinite summation.
$\color{red}{\text{Playing the role of the devil's advocate}}$, let me consider, with a more than simplistic approach, the case of the  zero of the simple function $$f(x)=x-\cos(x)$$ which write
$$f(x)=\frac{\pi -2 \sqrt{2}}{4}+\left(1+\frac{1}{\sqrt{2}}\right)\left(x-\frac{\pi }{4}\right) +\sum_{n=2}^\infty \frac{\sin \left(\frac{\pi  n}{2}\right)-\cos \left(\frac{\pi n}{2}\right)}{\sqrt{2} n!}\left(x-\frac{\pi }{4}\right)^n$$ In this form, it can be inversed leading to
$$x=\frac \pi 4+\sum_{n=1}^\infty a_n\,t^n\qquad \text{where}\qquad t=\frac{2 \sqrt{2}-\pi}{4}$$ where we know all the $a_n$ (have look here). This is then (at leat to me) an exact definition of Dottie number.
To give an idea, truncating the infinite series to $O(t^{13})$ gives an absolute error of $1.14\times 10^{-19}$
Comment: Your answer is very helpful. Why for the function $f(x)=x-\cos(x)$ , you make a development at $x=\frac{\pi}{4}$, and not at $x=1$ for example?$$$$ And do you think we could apply the method that you used for $f(x)=x-\cos(x)$ for another function, for example $f(x)=x-\sin(x)$ and find the $a_n$?


How to use multiple declarations in lambda filter?

Question: I am pretty new to Lambdas and I'm trying to use it the following way, but it doesn't seem to work. Is it possible to have multiple declarations where ONE of those is the condition?
ArrayList<Message> msgs = new ArrayList<>(ms.values());
Calendar cal = Calendar.getInstance();

msgs.stream().filter( m -> {
    cal.setTime(m.getCreated());
    cal.get(Calendar.YEAR) == year
});

I understand that it works like:
collection.stream().filter(x -> 1 == x);

But since I need to set the Date and use it with Calendar to get the year, I would have to do this in two declarations.
I know this works:
msgs.forEach(m -> {
    cal.setTime(m.getCreated());
    if (cal.get(Calendar.YEAR) != year) {
        msgs.remove(m);
    }
});

But I want to know if it is possible to do it the way I'm trying to, or something relatively similar?
Answer: You need to return a value if you use curly braces.  It's expecting a boolean return value.  It just assumes that if there's no braces.
return cal.get(Calendar.YEAR) == year;
Answer:
But I want to know if it is possible to do it the way I'm trying to, or something relatively similar?

You don't even need to use the old Calendar API. Since you are using an old Date, you would need to convert it to a Java 8 ZonedDateTime, which has a simple method to get the year.
Your filter would then look like this (extracted to a method for clarity):
List<Message> filterOnYear(int year, List<Message> msgs) {
  return msgs.stream()
      .filter(msg -> msg.getCreated().toInstant().atZone(ZoneId.systemDefault()).getYear() == year)
      .collect(Collectors.toList());
}

Date#toInstant() is a new method in Java 8, which we here use as a bridge between the old Date and the Java 8 Date and Time API. The conversion might seem a bit tedious, but it is because a Date is not exactly a date, as discussed here:

Despite its name, java.util.Date represents an instant on the time-line, not a "date". The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).


Building taxonomy Selector

Question: I'm building a classified website, on which users can create ads using the custom content type I've created. Each ad has a category field which a reference to a multilevel taxonomy, and uses the  hierarchical select field type.
When a user creates an ad/classified, I'd like the UI to first ask the user to choose from the the top-level terms of the taxonomy, then from the child terms of what is selected, then the child terms of that, so on so forth.
Here's an example of what I'm trying to achieve:

I've already tried using Conditional Fields with Hierarchical Select, and Simple Hierarchical Select but neither have worked out so far. I'm trying to create something that's user friendly.
Any help is appreciated.
Comment: Please note that questions about _Implementing a functionality, or a layout seen in a site, for which only a screenshot or a site URL is provided_ are off topic here as they're only likely to be useful to the person asking them. The [help] has more information on what kinds of question to ask here
Answer: You can try with Hierarchical Select module.

This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.
Comment: I already tried but  it's not help or maybe i didn:t understand the right way to configure it in this way

Building taxonomy Selector


PHP retrieve text/event-stream data

Question: For my DIY project I want to retrieve data from an 3rd party API which returns with the 'text/event-stream' header.
Because the connection doesn't close, I do it with a timeout as shown here:
$url='https://example.com/api/';
$ctx = stream_context_create(array('http'=>
    array(
        'timeout' => 1 // second
    )
));
$data = file_get_contents($url, false, $ctx);

Besides being super hacky, it is slow and it feels bad.
Is it possible to only catch the first data-element (JSON) from an event-stream?
So far I couldn't find any satisfying solution for my problem. Maybe I am lacking the correct vocabulary to search with.
Help very appreciated.
Comment: Can't you just `fopen` the stream, read as much data as you need, and close it when the stream is no longer needed?
Comment: The mods deleted my answer as I was too lazy to type the same one out twice, and I disagree with their deletion policy. Anyway, there's a helpful answer to your question here https://stackoverflow.com/a/70942426/120603
Answer: The following code worked for me to read a single event. The event stream seems to have a double EOL after each event. At least in my case. I am not sure if this is the case for all such streams.
readEvent can be called multiple times to read more then one event.
$handle = fopen($url, "rb");

function readEvent($handle) {
    $line = '';
    while (true) {
        $byte = fread($handle, 1);
        if ($line == '') {
            $timeStamp = DateTime::createFromFormat('U.u', microtime(true));
        }
        if ($byte === "\n") {
            fread($handle, 1); // skip one empty line (not sure if that is only necessary on the stream I am consuming)
            return ['timeStamp' => $timeStamp, 'event' => $line];
        }
        $line .= $byte;
    }
}

$event = readEvent($handle);
echo '1st event: ' . PHP_EOL;
echo '- received: ' . $event['timeStamp']->format("Y-m-d H:i:s.u") . PHP_EOL;
echo '- event: ' . $event['event'] . PHP_EOL;

fclose($handle);

PHP retrieve text/event-stream data


Função que some os valores dentro da lista

Question: Estou com um problema e preciso criar uma função que some os valores que estão dentro de uma lista. Já fiz isso e o código está abaixo, entretanto, o Python me retorna o valor 3 como resultado, quando na verdade o valor deveria ser 103. Não consigo achar o erro de jeito nenhum, se alguém puder ajudar agradeço.
Código abaixo:
def soma(x):

    total = 0
    for i in x:
        total += i
        return total
l1 = [3,7,1,90,2]

print(soma(l1))

Answer: O seu erro está na indentação da expressão return total; você colocou o retorno dentro do laço de repetição for, assim a função se encerrará sempre na primeira iteração, retornando o valor referente ao primeiro elemento da lista. Para corrigir, basta você remover a indentação:
def soma(x):

    total = 0
    for i in x:
        total += i
    return total

l1 = [3,7,1,90,2]

print(soma(l1))

Veja funcionando no Ideone | Repl.it
Você pode tentar reconhecer o erro elaborando o teste de mesa para o seu código: O que é um Teste de Mesa? Como aplicá-lo?
Além disso, o Python já possui uma função nativa, sum, que calcula a soma de listas.
l1 = [3,7,1,90,2]

print(sum(l1))  # Exibe 103

Veja funcionando no Ideone | Repl.it


A compact Lie group has descending chain condition on closed subgroups.

Question: Proposition: Let $G$ be a compact Lie group and let $$G\supset G_1\supset G_2\supset\ldots$$ be a chain of closed subgroups $G_i$ of $G$. Then this chain must eventually stabilize.
Question: The hint for the proof is that $G_i$ are closed manifolds and if $G_{i+1}\neq G_i$, either $\dim G_{i+1}<\dim G_i$ or $G_{i+1}$ has fewer connected components than $G_i$. I understand first part since closed subgroup of compact Lie group is subgroup that is also (embedded) submanifold, but I don't understand second part of the hint, ie. if $G_{i+1}\neq G_i$, either $\dim G_{i+1}<\dim G_i$ or $G_{i+1}$ has fewer connected components than $G_i$. Can you please help me with that? And I believe the rest of the proof is (please correct me if i'm wrong or if I missed something): Since dimensions are finite they must stabilize, ie. there exist $n_0$ such that $\dim G_{n_0}=\dim G_{i}=\dim G_{i+1}=\ldots=constant$ But then (from the hint) the number of components of  $G_{i+1}$ $<$ number of components of $G_i$ $<$ number of components of $G_{n_0}$. Since $G_{n_0}$
 is closed in $G$ it is compact and therefore has a finite number of connected components (since compact and locally-connected topological space has at most finitely many connected components). So it follows that eventually these number must also stabilize and proposition is true. Thank you!
Comment: If for some $i$ the group $G_i$ is *not* connected, then by taking the connected component of the identity, you get another closed subgroup which is not equal to $G_i$ but still has the same dimension. However, it has fewer connected components.
Answer: Since your argument is perfectly fine, I'll only explain the point you ask about. In a nutshell, this follows from the fact that a Lie subgroup with $\dim{G_{i+1}} = \dim{G_{i}}$ is an open subgroup.
Good examples to have in mind are the inclusion of $SO(n)$ in $O(n)$ or subgroups of $SO(n) \times M$ of the form $SO(n) \times N$, where $N$ runs through the subgroups of a finite group $M$.
A few generalities: Notice that the connected component $G^0$ of a locally connected topological group $G$ is an open subgroup (take a connected neighborhood $U$ of the identity and look at the subgroup $H = \bigcup_{n \in \mathbb{Z}} U^n$ generated by it: it is connected, open and thus it is also closed, hence $G^0 = H$ by connectedness, see here for more details). Moreover, $G^0$ is normal since $gG^0 g^{-1}$ is a connected subgroup containing the identity. The quotient group $\pi_0 G = G/G^0$ of $G^0$-cosets consists of the connected components of $G$ and it has the discrete topology since the quotient map $G \to G/G^0$ is open and since $G^0$ is open.
Coming back to your question, the dimension requirement $\dim{G_{i+1}} = \dim{G_i}$ together with the fact that the Lie algebra $\mathfrak{h}$ of a closed subgroup $H$ embeds as a Lie subalgebra of $\mathfrak{g}= \operatorname{Lie}{G}$, imply that $\mathfrak{g}_{i+1} = \mathfrak{g}_i$. The exponential map is a local diffeomorphism from $\mathfrak{g}_{i+1} = \mathfrak{g}_i$ to the connected component $G_{i+1}^0$ of $G_{i+1}$ and thus $G_{i+1}^0$ is an open subgroup of $G_{i}^0$, so $G_{i+1}^0 = G_{i}^0$. It follows that $\pi_{0}G_{i+1} = G_{i+1}/G_{i+1}^0$ is a subgroup of $\pi_{0}G_i = G_{i}/G_{i}^0$ and both groups are finite since they are compact and discrete. But as I explained in he second paragraph, $\# \pi_0 G_{i+1} = \# (G_{i+1}/G_{i+1}^0)$ is the number of connected components of $G_{i+1}$ and thus it divides the number of connected components of $G_{i}$.


How to add default text that clears on focus to a form in Drupal?

Question: I would like to display a default text in a field of a views filter form. That default text would then be hidden "on focus", and would re-appear "on blur".
So far I have tried to follow the instructions given here:
How to add default text that clears on focus with jQuery to a search form text field in Drupal
but with no success.
What I did:
1. Downloaded the Jquery files (https://github.com/mudge/jquery_example/downloads), and copied them in my /sites/all/libraries/mudge-jquery directory
2. Added a helper.js file into that directory with that code
(function ($) {
  Drupal.behaviors.helper =  {
    attach: function(context, settings) {
      $('input#edit-title.form-text.beautytips-module-processed.bt-active').example('TEXT TO HELP');
    }
  };
})(jQuery);

3. Created a simple module with that code:
function helper_preprocess_page (&$vars) {
  // Let's add some js to page for the search box.
  $path = drupal_get_path('module', 'helper');
  drupal_add_js($path . '/sites/all/libraries/mudge-jquery/jquery.example.min.js');
  drupal_add_js($path . '/sites/all/libraries/mudge-jquery/helper.js');
}

Still nothing is displayed in my "input#edit-title.form-text.beautytips-module-processed.bt-active" field. What am I doing wrong here?
Comment: Is your doctype HTML5 or (X)HTML? Oh and we'll need to see the code in jquery.example.min.js to help out really
Answer: What you want here is:-
a) hook_form_alter to change the form
b) #attached to add JS to the form
c) add clear-text to ['#attributes']['classes'] where necessary.
Then you can use this little JS.
 Drupal.behaviors.clearText = function(context) {
    var inputs = $('input.clear-text:not(.processed)');

    // Store the original values
    inputs.each(function() {
      $this = $(this);
      $this.data('default', $this.val());
    }).addClass('processed');

    // Set up inputs to clear on focus & reload default (if blank) on blur
    inputs
      .focus(function() {
        $this = $(this);
        if ( $this.val() == $this.data('default') ) {
          $this.val('');
        }
      })
      .blur(function() {
        $this = $(this);
        if ( $this.val() == '' ) {
          $this.val( $this.data('default') );
        }
      });
  }

Comment: When you see something new, it's always helpful to search core for that. In this case, there are hundreds of examples, here is one: `$form['#attached']['js'][] = drupal_get_path('module', 'field_ui') . '/field_ui.js'`
Answer: i have used a little javascript to display default text which gets removed on focus.
However in validation i have to check for null if the field is blank and as well as the default text.
 $form['account details']['first name'] = array(
    '#type' => 'textfield',
    '#title' => t('First Name'),
    '#default_value' => t('Be sure of your first name'),
    '#attributes' => array(
    'onblur' => "if (this.value == '') {this.value = 'Be sure of your first name'}",
    'onfocus' => "if (this.value == 'Be sure of your first name') {this.value = ''}"
      , ),
       );

Comment: Using on* is unseemly, ugly, deprecated etc.
Comment: well am new to it....thanks for telling.your logic uses functions a bit new to me for now . Anyways thanks @chx
Answer: I think Compact Forms module will help you. Even if you won't use it as is - you can take js code from that module that will solve your issue.
Answer: I use the follow simple straight-forward code for my search fields and add it in my theme:
(function ($) {
  Drupal.behaviors.mysiteSearch = {
    attach: function() {
      // Apply the default text to the search block's text field.
      $('#block-search-form .form-text')
      // Add default text options on blur.
      .blur(function () {
        $(this).addClass('gray');
        $(this).attr('value', Drupal.t ('Search...'))
        // keep what's typed
        .keypress(function(){
          $(this).unbind('blur');
        })
        // clear on focus
        .focusin(function () {
          $(this).attr('value', '');
          $(this).removeClass('gray');
          $(this).unbind('focusin');
        });
      })
      // Trigger the blur event to set things up.
      .blur();
    }
  };
}(jQuery));

Just be sure to set a .gray css style.


Pandas Dataframe comparison with range/stdev

Question: I have to dataframes A and B. Both have a 'datetime' column and another common column X. B is bigger as it has X at every minute while A only has X at intermittent times during a day. For each 'datetime' in A, I want to calculate the range (or stdev) of X during previous 30 minutes using B. So something like:
For i,time in enumerate(A['time']):
   temp=B[(B['time'] > time -timedelta(days=0, minutes=30)) and (B['time'] <=time]
   range[i]=temp.max-temp.min
Here temp is intended to snapshot all the data within 30 mins prior to A's timestamp in B. Is there a simple way, maybe one that doesn't require a loop, to do this? Note that sizes of A and B are different.
Sample A: (only few outputs available along with inputs)

Date                         input  output
2015-01-02 20:48:00-00:00     1120    343
2015-01-02 21:25:00-00:00     1345    365
Sample B: ( all the inputs available but no outputs)

Date                         input
2014-11-02 00:32:00-00:00     1542
2014-11-02 00:33:00-00:00     1285
Sample Output:

Date                         input  output  Range_input_previous 30 min
2015-01-02 20:48:00-00:00     1120    343      ??(use table B)
2015-01-02 21:25:00-00:00     1345    365      ??(use table B)
Comment: can you provide sample of both the data frames?
Comment: Added. Let me know if it helps
Comment: Can you add desired output?
Comment: Added. Let me know if it helps
Comment: Thank you. I think the best is use such values in sample which return some numbers.
Comment: There is main problem your conditions return only `False`, so I cannot test it. So you need change datetime to values, where return `True`
Answer: This works for me but uses a loop:
rangex=np.zeros(A.shape[0])
 for i,Date in enumerate(A['Date']):
     temp=B[(B['Date'] > Date-datetime.timedelta(days=0, minutes=30)) & (B['Date'] <=Date)]
     rangex[i]=temp['input'].max()-temp['input'].min()
 A['range']=pd.Series(rangex, index=A.index)


Should I include an interaction term for a covariate if I expect it to be correlated with one or more of the variables?

Question: I'm fitting a linear model where the response variable is a measure of physical performance-- running speed for example-- and the predictor variables are sex and drug treatment, with an interaction term.
$$Y = \beta_{0}+\beta_1X_{sex}+\beta_1X_{drug}+\beta_3X_{sex}X_{drug}$$
We suspect that body weight influences running speed, so we need to include body weight as a covariate to make sure the differences we're seeing aren't adequately explained by body weight alone.
However, body weight is affected by the drug, and of course it also correlates with sex. That makes me think that body weight should be included only as an additive term and its interactions with other terms should not be considered (because they will be spuriously significant):
$$Y = \beta_{0}+\beta_1X_{sex}+\beta_1X_{drug}+\beta_3X_{sex}X_{drug}+\beta_4X_{bw}$$
Am I correct to not include body weight interactions, and are my reasons for doing so correct? Thanks.
Answer: I don't know whether you are correct in not including the body weight interactions--the data should decide that--but the reasoning does not appear to be valid.
To see why not, suppose (purely hypothetically) that there is an ideal body weight for running that lies somewhere between the (low) mean female weight and (high) mean male weight.  Then it is plausible that performance increases with female body weight and decreases with male body weight.  That's a strong interaction between body weight and gender.
(There's also an important nonlinearity involved here: my supposition of an ideal intermediate weight is tantamount to saying that performance is not linearly related to body weight.  But in some circumstances--such as when male and female body weights are well separated in the dataset--such nonlinearity could be adequately modeled in a linear fashion by means of this interaction.  In effect, the relationship between weight and performance could be $\wedge$-shaped and gender becomes an indicator of which arm of the $\wedge$ is involved.)
Now of course body weights and running performance do not behave exactly like this, but nevertheless the mere possibility that three variables (body weight, gender, and performance) could be so related shows that the reasoning is incorrect.  Whether or not there is a body weight-gender interaction will depend on your data: consider including it during preliminary analyses until it is clear that it adds no value to the model.
Comment: I see collinearity as being more a problem of *identifiability*: when variables are almost collinear, each becomes almost interchangeable with linear combinations of the others, whence any interactions also become interchangeable with linear combinations of interactions.
Comment: I see, so collinearity in predictor variables isn't going to inflate the apparent significance of interactions that involve those variables?
Comment: Ah, so if performance is improved, for example, by treatment conditional on sex AND has an increased improvement in treated individuals the higher their body weight... then either or both of those interactions could be real and we don't have enough information to determine which? Is that right?


How can I move beyond learning songs?

Question: I can competently learn and play chord progressions and simple runs on the guitar but I do not feel like I understand the instrument.  My playing progresses by memorizing songs.
However, I know that there is more to playing than this.  I have seen other players listen briefly to a new song and then be able (with perhaps only a few missteps) join in and play.
What should I be focusing on in my practice and playing to move beyond simply memorizing how to play new songs?
Answer: You need both ear training and music theory.
Ear Training
By "ear training", musicians mean the ability to identify musical intervals, chords, scales, etc.  It means developing your relative pitch as opposed to perfect pitch.  Perfect pitch is the ability to hear a tone and be able to identify what note it is ("is it a C# or a Bb?").  Relative pitch is the ability:

to hear an interval and correctly identify its type (a major sixth, a perfect fifth, etc.).
to hear a note and sing the note that's a specified interval above or below the given note ("sing the note a major third above this note I'm playing now.").
to hear a chord and correctly identify its type (a major chord, a dominant chord, a diminished chord, etc.).
to hear a scale or an arpeggio and identify its type (again, major, minor, etc.).
to hear a chord progression and identify the chords' functions or relations (thanks to Ulf Åkerstedt for this suggestion).

You don't need perfect pitch at all.  You need relative pitch in industrial-scale quantities.
Music Theory
Music theory is the knowledge of the component building blocks of music and the understanding of how they fit together.  Some people would say that ear training is a component of music theory, and although I disagree, I also think it's splitting hairs to debate this point.  More importantly, you need to know and understand:

what musical intervals are, their types, and how to produce them on your instrument (this is where many people say ear training is a part of music theory, saying "how can you identify intervals if you don't even know what they are?"  Again, I don't think it's worth arguing over the semantics).
scales, especially major scales, and how to produce them on your instrument.
how musical intervals combine to form chords, the various types of chords, and how to produce them on your instrument.
the relationships between scales and chords, how chords emerge from scales, and how scales contain chords.
how chords relate with each other to form chord progressions, and how those chord progressions work---this study is known as functional harmony (here's the answer I wrote on this site outlining the very basics of functional harmony).

Acquiring these skills will literally take years of focused daily practice, but I don't mean to scare you off---it's totally worth it.  I highly recommend studying with a teacher.  You can get all of this information from books, CDs, iPad apps, and other resources, but a teacher will give you both guidance tailored to your specific level of development and feedback on what you're doing right and wrong.  Best of luck!
Comment: @MatthewRead :) Thanks. It's been fun. Looking forward someday to getting out of beta.
Comment: Excellent answer! Maybe you should add "to hear a chord progression and identify the chords' functions or relations" to the list at ear training? Especially since this would be important in order to "join in and play" as stated in the question.
Comment: Great overview, congrats on hitting 10k :)
Comment: Great answer, but I would add a couple of things in terms of Ear Training.  The first is to learn the style of music.  When I first started in a Gospel Choir that didn't use music, it took me a while to get an ear for how the Gospel harmonies are put together. (I come from a strict classical music upbringing.)  The second is to transition from see->finger->play->hear to hear->finger->play.  A musician with good ear-training can hear a note and then just finger the note without having to first think about what note it is.
Answer: Besides just knowing the mechanics of the songs, which you obviously seem to be doing, listen to different artists perform them. Listen to as much music as you can. Start with people that play the same songs as you do, then expand to people in the same genre. See where your tastes take you. Try to imitate your favorite players, watch videos of them, see how they hold the guitar, how their playing is different from yours. Listen to players you like, players you don't like. Try and identify why you like/don't like them. It's fun to learn new songs, but if you focus too hard on the technicality of it, you lose the soul of music.
Ear training and music theory is all well and good, but if you truly want to identify with your instrument, listen to all the music you can.
Answer: in addition to composition techniques, there's also getting good at EXPRESSION.
Being able to keep the left hand soft, make a melody flow with subtle volume nuances.
Careful articulation of each note's volume, attack and duration to make a song really shine.
This is what seperates a song played by a human from one played by a computer.
Listen to any midi file that was "just typed in" (a faithful realization of the sheet music).
Sheet music doesn't say exactly how to "punch" a song.  That comes from the piano player.
And most midi files sound terrible since they lack that punch.  SOME midi files are an actual recording of a live piano player and they HAVE that punch.

How can I move beyond learning songs?


I would like Jenkins to fire a build when a patchset is uploaded or changed in Gerrit. How, exactly, do I configure this?

Question: I am using Jenkins 1.557 to watch a Gerrit 2.8 instance for changes. I am using the following plugins:

Git Plugin 2.1.0
Git Client Plugin 1.7.0
Gerrit Trigger 2.11.1

When I use "test connection" on the Gerrit Trigger, it returns success, so I know the credentials are working. I'm using the default values under the "advanced" button.
For my test build type, I'm using a git repo, which Jenkins checks out (I added a post build step of "ls -l" and it shows the repo contents correctly). I have the build trigger set to "gerrit event" and for "gerrit trigger" I have "Check non-reviewed patchsets" selected, and a trigger for "patchset created" enabled. The gerrit project settings seem correct.
I cannot get the build to fire by uploading a new change or a new patchset for a change. When I manually fire the build using the "Query and trigger Gerrit patches" button, the build happens, but no votes are recorded. I'm clearly missing on part of the puzzle - if I ssh into gerrit and do a "stream-events", I see the events I'm expecting to see.
Jenkins - the definitive guide - from O'Reilly does not really cover Gerrit. I'm trying to avoid polling because there will be dozens of git repos managed by this Jenkins instance.
What is the next step in debugging?
Answer: There have been some changes in the past, which broke the plugin:

Gerrit 2.8 removed the deprecated approve command, which AFAIK broke the plugin, see discussion and Release Notes. This was fixed with 2.11.0-beta1, so I guess this is not the case for you.
Gerrit 2.7 introduced the Stream Events privilege, which disallows users to receive stream events by default, see Release Notes. Very likely, your Jenkins user does not have this access privilege and thus no builds are triggered after pushing a change.
Comment: WRT *Stream Events*, the Jenkins user is in group "Non-Interactive Users", and that group has Steam Events: Allow in the global permission block (All-Projects). If I ssh in with the Jenkins user credentials, I do see the events. WRT approve/review, the commands for the gerrit verified commands blocks show gerrit review ... for each one, so it shouldn't be an issue. I will try manually using those commands, though
Comment: It looks like the "--verified" command is gone, too. Adding "-l VERIFIED=" instead makes the values show up correctly. Now to figure out the trigger itself.


How to alter the name of downloadable excel sheet of webform

Question: Issue:
When I click on the link ofwebform Download as shown in below screenshot the default name of excel sheet before save to local disk appears like localhost_worklog.xlsx but I want something like localhost_worklog_02172017.xslx which is appended with _<current time>.
SCREENSHOT:

EDIT: After using iLLin's answer

Problem: How can I alter the name of localhost_worklog.xlsx before save?
I am using drupal 7.53.
Answer: The only way to do this is to change the $node->title on the loaded object for the webform.  That filename uses that title, so I am assuming you have a webform title of "Localhost Worklog".
The problem with that is you only want to change the node title, when you are downloading the webform (or atleast running through that process).
You have two options (I think).  You could implement a hook_entity_load() function and then check if the URL is
node/%webform_menu/webform-results/download
or
node/%webform_menu/webform-results/download-file
function MYMODULE_entity_load($entities, $type) {
  if (arg(2) == 'webform-results' && (arg(3) == 'download' || arg(3) == 'download-file')) {
    foreach ($entities as $entity) {
      $entity->title = $entity->title .'_'. now();
    }
  }
}

Docs
The other way I can think of is altering the page callback with a hook_menu_alter(), changing the title there and then calling their function to return the form or download file with the updated node object to include the time appended to the title.
EDIT
From reviewing your update, it seems it's changing the title too soon on that page.  So I think you will need a combo approach.  Using hook_entity_load and hook_form_alter.  The point is changing that title in the $node object that is passed around for download.  So try this.
/*
 * Implements hook_entity_load().
 */
function MYMODULE_entity_load($entities, $type) {
  // Change the node title to include the time when downloading.
  if (arg(2) == 'webform-results' && arg(3) == 'download-file') {
    foreach ($entities as $entity) {
      $entity->title = $entity->title .'_'. now();
    }
  }
}

/*
 *  Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == WEBFORM_DOWNLOAD_FORM_ID) {
    // Change the node title that is passed around for download.
    // @TODO: Check to make sure this is correct.
    $form['node']['#value']->title = $form['node']['#value']->title . '_'. now();
  }
}

Comment: Thanks,I was able to change filename accordingly but how can I retain the original title on dashboard.Pls see my edit.
Comment: You need to only change that title before the download process.  What does your code look like?  It shouldn't "save the node title" and it should only change it on those two pages.  You may need to do a form_alter or try another location in the code.


What terms describe music that generally moves down (Or up) in pitch as the music moves forward?

Question: I have noticed that some music, particularly music rock music played on guitar, often has passages that start lower in the register of the guitar (Or other), and increase pitch as the passage progressive, usually building up tension.
Is there terminology to describe music that starts in the higher register of the guitar (or other instrument) and progresses downwards in pitch as a motif in a passage of music, or entire song?
(P.S: I suppose another way to think of it, is that guitar passages often start in keys that are easily played closer to the head-stock of the guitar, that is, the lower notes progressing higher as the passage moves forward.)
Comment: are you talking about changing in register or changing keys? "start in keys". change of keys is called modulation, but not sure if that is what you are talking about or if you just mean the performer changes the register they are playing in.
Answer: I would caution against thinking too hard and trying to re-invent the wheel; we would just call this an ascent or descent. If you want to be really fancy you could maybe say something like a "registral trajectory," but come on now; that's just silly :-)
A relatively new field in music theory is called "embodiment" (or "embodied music theory") and it discusses the physical connections to music performance. It's possible you could discuss locations on the guitar neck from an embodiment standpoint, but when it comes down to it, you're just talking about an ascent.
Imagine a painting where the far right of the canvas uses only dark reds. We wouldn't really need to come up with a name for that dark red patch; we can just describe it as what it is: a dark red patch that may or may not fit with the rest of the painting.
Typically in scholarship we only feel the need to dedicate a new term if it's a common, innovative, and influential new tactic. If the dark red patches in paintings started to appear in 1863 and an entire school of French artists from ~1860 to ~1900 used dark red patches in their paintings, we'd probably have a name for it.
But turning back to music, sometimes things go up, sometimes things go down. Unless there's a clear trend that's a result of it, we can probably be safe just calling it an ascent or a descent. You could always modify it by describing it as a "chromatic ascent," or maybe as something "descending by thirds," but that's about as specific as we tend to get in this case.
Comment: So you're saying that a passage or song in which there is a general motif of descent dominating the music, it is said to contain  many  descents?
Comment: I think so; check out, for instance, The Beatles' ["A Day in the Life"](https://youtu.be/usNsCeOV4GM?t=3m46s); in my experience, we would just call this an ascent.
Comment: Your "dark red patches" analogy reminds me of musical features like the Mannheim rocket.
Comment: @Dekkadeci Oh, great example. It's all about ubiquity!
Comment: Interesting read, but from my point of view wrong, since there is an established term, see my answer.
Answer: Actually there is a German term Rückung (I suggest "tonal center shift" as rough and free translation; Wikipedia seems to offer chromatic modulation) which means repeating the same theme a semi-tone or full tone transposed. It is different from modulation, since the target key is completely unrelated to the source key. It is frequently used e. g. in Schubert songs, where the effect is sometimes repeated several times.
Answer: Ascent, moving up, or descent, moving down, describes both moving up or down while staying in a single key or mode, but can also apply to key or mode changing and in fact you can even modulate up or down and continue to ascend or descend as the music moves forward. Therefore Ascent or Descent usually refers to movement within a scale or key, where as modulation usually refers to movement up or down of a tonal center, key, or mode.


Como passar dados de uma ViewController para outra ViewController

Question: Pesquisando sobre isso encontrei algumas soluções, a primeira é passar pelo prepareForSegue(), a segunda é usar uma variável compartilhada (global), também cheguei a ver uma coisa sobre usar protocolo, mas não consegui usar.
Em alguns casos, em que um app que possui vários níveis ou usa uma biblioteca como SWRevealViewController(slide out menu), é difícil ficar passando dados e usar variáveis globais. Sempre fui recomendado a não usar em outras linguagens de programação.
Assim, segundo as melhores práticas, qual a forma de passar dados de uma ViewController para outra.
Comment: Editei de forma a torná-la mais fácil de ler e tentei que não seja considerada como "baseada em opiniões"[(veja porquê)](http://pt.stackoverflow.com/help/dont-ask).
Comment: Não sei nada de *swift* mas se "protocolo" é o equivalente a "interfaces" em *Java* e se puder ser feita uma analogia com o Android, então usar "protocolo" poderá ser uma solução. Talvez esta [pergunta](http://pt.stackoverflow.com/q/10418/2541) possa ajudá-lo.
Answer: Há várias formas de passar informações entre os objetos e a maneira certa vai depender das características da aplicação.
Usando propriedades:
Normalmente usado quando a dado é passado uma única vez, tão logo o objeto é alocado. Creio que essa foi a forma que você fez. Define-se as propriedades do segundo controller e quando aloca-lo, modifica os valores dessas propriedades:
class SecondViewController: UIViewController {

    var data: String?
}

class FirstViewController: UIViewController {

    ...
    //Utilizando segues para transição
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if let destinationViewController = segue.destinationViewController as? SecondViewController {
            destinationViewController.data = "foo"
        }
    }

    //Definindo as transições programaticamente
    @IBAction func openDetail(sender: UIView) {

        let destinationViewController = SecondViewController(nibName: "SecondViewController", bundle: nil)
        destinationViewController.data = "foo"
        presentViewController(destinationViewController, animated: true, completion: nil)
    }
}

Protocolos: Outra forma bastante utilizada é através de protocolos, como sugeriu o @ramaral, veja a pergunta que trata isso. Normalmente utilizamos protocolos quando os dados são passados de forma assíncrona. Ex: o segundo controller solicita dados ao primeiro sob demanda, a medida que o usuário faz scroll na tela. Sugiro estudar os padrões delegate e datasource, largamente usados no iOS.
Um outro padrão muito usado para comunicação é o singleton, mas ele não deve ser usado pra comunicação direta entre dois objetos. Singletons são melhor utilizados para manter o estado global da aplicação.


Flow down tables with bootstrap

Question: I have a responsive bootstrap table (1 tr and 3 td) and when it comes to xs devices I want them to flow down.

Trophies

View

Medals

View

Souvenirs

View

**I have this table with single row and 3 td on it and each of td contains a thumbnail image. And when it comes to xs devices I want them to flow down like in the example picture please help me with this.
this is what i wanted to look like when it comes to xs devices
Comment: You will have to change your HTML for this.
Answer: Are you using tables for a specific purpose? Because if not, you can use the grid on Bootstrap.
e.g.

 "your image here"

 "your image here"

 "your image here"

But you can omit the code col-xs-12 because I think col-md-4 automatically flows them down if you resize your screen.
Comment: Thanks ! It helped. It didn't come to my mind earlier.
Comment: Glad you find it useful, please mark it as answer :)

Flow down tables with bootstrap


Macro to remove double quotes in c

Question: Is there any macro which will remove double quotes and '\0' in a string?
For example:-
"HELLO\0" -> HELLO
Edited:-
Actually I want to get the function address. So I thought to use FUNC Macro to get the function name and stipping out double quotes and '\0' will help me to get the function address.
for ex:
#define FUN_PTR fun
#define FUN_NAME "fun"
void fun(){
 printf("fun add %p name %s\n",FUN_PTR,FUN_NAME);
}

To avoid user define macros. I like to know other methods to derive these functionality :).
void fun(){
 printf("fun add %p name %s\n",<SOME_MACRO>(__FUNC__),__FUNC__);
}

Comment: Ok, what exactly are you trying to do here?  Seems like if we had a larger idea of the problem domain, we could give a better answer.
Comment: Why? Maybe there's another way to do what you want ...
Answer: Do it the other way around.
#define PRINT_PTR(p) printf(#p " == %p\n", (void *) p)

int main()
{
    PRINT_PTR(exit);
    return 0;
}

Inside a macro, if x is a macro argument, then #x is the string version.
#define PRINT_INT(i) printf(#i " == %d\n", i)
PRINT_INT(5 + ~3);
PRINT_INT(atoi("1234"));

Typically, if you use this a lot, then you'll want to define a helper function to work around the weak type system in C:
void print_ptr_func(char const *s, int v);
#define PRINT_PTR(p) print_ptr_func(#p, p)

Note that this won't work for getting the address of the current function.  __FUNC__ is not a macro and it is not a string literal, it has no double quotes.  You cannot use __FUNC__ to get the address of the function without some serious trickery, and it will break half the time.  For example:
#define PRINT_FUNC_INFO() print_func_info(__FUNC__)

#include <dlfcn.h>
void print_func_info(char const *n)
{
    void *p = dlsym(RTLD_DEFAULT, n);
    printf("Function %s, address %p\n", n, p);
}

However, this will not work half the time -- dlsym wasn't designed to be used for that purpose.

Macro to remove double quotes in c


How can I show a context type menu when clicking a user's photo, With multiple user photo's per page?

Question: I need help, I need to make a menu that only shows when you click on an iamge, I need to position the menu directly to the right hand side of the image div though.  So can someone look at the link provided and help me to position the menu div next to the photo div?
Then maybe show an example of the best method to show/hide the menu div on click and how to hide it when clicked outside of the menu area.  Whould the best way be to create the menu for each user, if there is 20 users on a page should I create 20 hidden menus?   Any help appreciated I know this question kind of seems like I am just lazy but I really don't know how to position the div the way I need it and as for show/hiding it I don't know the best method when it needs to have many of the menus on 1 page.
http://friendproject.isgreat.org/contextmenu.php
Answer: You have to apply the css
float: left;

to the image as well as the menu to position the elements like your Photoshopped image.
I think the easiest option is to indeed create a menu next to every image.
You would have to hide the menu with
display: none

And could toggle the visibility with jQuery's toggle() function like this:
$("image1").click(function() {
    $('#menu1').toggle();
});

Comment: I used your suggestions and here is the outcome http://jsbin.com/epidu  It doesn't position exactly how I wanted before, instead position below the div but I like this look as well.. My only problem now is I don't think toggle is the answer, well I mean I woyuld like to keep toggle but also make it toggle off if I click anywhere on the screen, any idea how to do that?
Comment: Also I will need to make the jquery more dynamic, if there is 20 users on 1 page then the jquery part will not be very efficient because each photo and menu would have a unique ID, like there userid "menu_USERIDHERE" and "photo_USERIDHERE"
Answer: I am going to add another answer because all of this info doesn't fit in a comment.
The elements aren't positioned next to each other because the float:left; is applied to the element that wraps both the image and the menu. They need to have float applied seperately (I think it would work if you apply it to ImageSub instead of Photowrap).
It involves quit a big amount of work if you want the menu to be closed if you click anywhere on the screen. You would also have to toggle a invisible/transparant overlay that stretches to the full width and height of the page. On top of that the menu will be placed. With another onclick event watcher on the overlay both the menu and the overlay would be toggled. This technique is also used with lightboxes.
The overlay could be created with the following CSS:
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;

A more effective approach for toggling would be using the JQuery '^' selector. Here's a great tutorial on that topic: http://www.olliekav.com/2008/10/18/writing-multiple-toggle-links-in-jquery/


Find all numbers $c$ that satisfy the conclusion of Rolle's Theorem

Question: $$f(x) = 4 \sin\ (2 \pi x),\ [-1,1]$$I'm not sure where to start on this problem. It's not simply the Mean Value Theorem where its $\frac{f(b) - f(a)}{(b - a)}$? Any help would be appreciated.
Answer: Hint:
Rolle's theorem is essentially the Mean Value Theorem, except it theorizes that, when $f(a)=0$ and $f(b)=0$ over $(a,b)$, there will be some point "c" in $(a,b)$ such that $f'(c)=0$. What are $f(a)$ and $f(b)$? You can figure that out.
Comment: I found that both f(a) and f(b) both equal zero. Then I set the derivatve of f(x) equal to zero right? How would I solve for that equation?
Comment: @etree, use arccosine and you should be set.
Answer: To settle this problem, we will apply Rolle's theorem to our real-valued function f(x). The sine function is continuous on any interval in $\mathbb{R}$ thus $f(x)$ is continuous on $[-1,1]$. The derivative of $f(x)$ is given by
\begin{equation*}
f'(x)=8\pi\cos(2\pi x).
\end{equation*}
Substituting the endpoints of the interval $(-1,1)$ gives us
\begin{equation*}
f'(1)=8\pi(1)=8\pi=8\pi(1)=f'(-1).
\end{equation*}
The sine function is differentiable on any interval of $\mathbb{R}$ thus differentiable on the interval $(-1,1)$. Also observe that substituting the endpoints into $f(x)$ gives us
\begin{equation*}
4\sin(2\pi)=4\sin(-2\pi)\Rightarrow 4(0)=4(0)\Rightarrow 0=0
\end{equation*}
thus $f(1)=f(-1).$ Applying Rolle's theorem, this implies that there exists some $c\in\mathbb{R}$ such that
\begin{equation*}
8\pi\cos(2\pi c)=0.
\end{equation*}
Rearranging for $c$ gives us
\begin{equation*}
\cos(2\pi c)=0\Rightarrow 2\pi c=\frac{\pi}{2}\Rightarrow c=\frac{1}{4}.
\end{equation*}
Thus $c=1/4$ is the only value for which we have $f'(c)=0$ on $[-1,1].~_{\square}$


Writing a piano part for a 4.-part choir piece

Question: I have a 4-part choir song, with chords.  Does anyone know any reference material or courses I could take about writing good piano parts?  I've written them, but they tend to be too "monotone" - just basic chord notes.  I would like to make them more melodic and, well, something someone would want to listen to.  Thanks!
Comment: This question is too general IMO (it's pretty much asking "How do I write better music?") but try this: find some choir+piano songs that you like. Figure out what's going on. Try to imitate it. Rinse and repeat.
Answer: Look at the sheet music for other songs for similar forces. IMSLP is a very good web resource for PDF scans of scores of public domain music. Here's the results of a search to start you off:
https://imslp.org/index.php?title=Category:For_4_voices,_piano&intersect=&transclude=Template:Catintro
If you want to refine that search, you could start here:
http://imslp.org/wiki/Special:CategoryWalker/For_4_voices,_piano/
Answer:
Select one 4 part song you like, probably a couple of your favorite songs.
Find the sheet score for those songs.
Analyze and understand the pattern of the songs, and the movements that makes it nice for you.
Go through the 4 part writing basic rules most of them includes "no parallel 5ths, octaves, and unison movements, try to use all three chord tones in upper voices and try to double root,Never double leading tone,..."
Go through advance rules which includes rules like "double fifths when root doubling is not working fine, avoid doubling Alto and Tenor voices, try triple roots in cadences, ..."

For references, try lessons like this
For example, take a look at hymn The head that once was crowned with thorns - SATB


Is there a function to get the list of nodes by type?

Question: Is there a function like node_load() that returns a list of nodes by a given content type?
I've tried $nodes = node_load(array("type" => 'student_vote')), but it only returns one node.
I know I could code up something like node_load(), but I wanted to see if there might be anything like that out there already.
Answer: The code to use depends from the Drupal version.
Drupal 6
$nodes = db_query('SELECT nid FROM {node} WHERE type="%s"', $type);

Drupal 7
$nodes = node_load_multiple(array(), array('type' => $type));

Drupal 8
$nids = \Drupal::entityQuery('node')
  ->condition('type', 'NODETYPE')
  ->execute();
$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadMultiple($nids);

Comment: Bear in mind that the $conditions array is depreciated and will be removed in Drupal 8, for future compatibility it would be better to use EntityFieldQuery (http://api.drupal.org/api/drupal/includes%21entity.inc/class/EntityFieldQuery/7) to get the node ids, then pass those into the first argument of node_load_multiple(). There is a good tutorial here: https://drupal.org/node/1343708
Comment: Just for clarity, EntityFieldQuery() is no more in Drupal 8.
Comment: Yes, this would work.
Comment: D8: if you're writing some sort of batch task and you see 0 results for content with restricted permissions, you might need `->accessCheck(FALSE)`
Answer: There is no such API for Drupal 6. The closest you can do is to properly query for all node ID for the content type then load each one using node_load() but this will require n+1 queries and is not very efficient.
function node_load_by_type($type, $limit = 15, $offset = 0) {
  $nodes = array();
  $query = db_rewrite_sql("SELECT nid FROM {node} n WHERE type = '%s'", 'n');
  $results = db_query_range($query, $type, $offset, $limit);
  while($nid = db_result($results)) {
    $nodes[] = node_load($nid);
  }
  return $nodes;
}

Note: db_rewrite_sql will ensure access check and other module provided filtering (such as language filtering provided by the i18n module).
For Drupal 7, you can use $nodes = node_load_multiple(array(), array('type' => $type));but the $conditions argument of node_load_multiple() is deprecated. Instead, you should use EntityFieldQuery to query for the node IDs then use node_load_multiple() but without a $conditions argument.
function node_load_by_type($type, $limit = 15, $offset = 0) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', $type)
    ->range($offset, $limit);
  $results = $query->execute();
  return node_load_multiple(array_keys($results['node']));
}

Comment: Actually, if you do a node_load() in D6 like this: node_load( array( 'type' => 'page' ) ) you will get all an array of all page nodes.
Comment: @bsenftner node_load( array( 'type' => 'page' ) ) only returns one node.
Answer: There's several good answers already, but they take the question literally and refer to nodes only.
Since D6 doesn't have an API for doing what is being asked for, and it's not necessary to limit oneself to nodes in D7 and forward, I feel a good answer should be entity generic.
function entity_load_by_type($entity_type, $bundle, $limit = 10, $offset = 0) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', $entity_type)
    ->entityCondition('bundle', $bundle)
    ->range($offset, $limit);
  $results = $query->execute();
  return entity_load($entity_type, array_keys($results[$]));
}

Comment: did you mean `array_keys($results[$entity_type])` ?
Comment: I was going to add an answer about `EntityFieldQuery`, but you have already written yours. I would just add that the second argument of `user_load_multiple()` has been deprecated since Drupal 7, and the used code should be the one you show.
Comment: I figured I didn't even need to refer to the old versions with deprecated arguments since I just used entity_load right away. That way there's "no" risk of people accidentally ending up using the deprecated functionality. Or do you disagree with that?
Comment: @commonpike Most likely, yes. I don't have the opportunity to check at the moment, but feel free to edit and correct if you test it out. :)
Comment: I was doing something slightly different and needed to specify `entity_load($entity_type, array_keys($results['node']));`. Havent tested it for other entities..
Comment: At the end, Drupal 8 deprecated both `node_load_multiple()` and `user_load_multiple()`, not just the last parameter they used. I would say it's safe to use that parameter on Drupal 7, since the code for Drupal 8 won't use `node_load_multiple()` nor `user_load_multiple()`.
Answer: Drupal 8+
$content_type = 'article';
$articles = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'type' => $content_type,
]);

Answer: At the end, Drupal 8 deprecated functions like node_load_multiple(), user_load_multiple(), not just the $conditions parameter they used. This means it isn't possible to write Drupal 7 code that is compatible with Drupal 8, as the classes used in Drupal 8 aren't available on Drupal 7.
Drupal 7 code can still use node_load_multiple() and its $conditions parameter. To load all the nodes whose content type is $content_type, it's sufficient to use the following code.
$nodes = node_load_multiple(array(), array('type' => $content_type));

A more generic code that works for any entity would be the following one.
$entities = entity_load($entity_type, array(), array('type' => $bundle);

Despite the name, entity_load() loads more entities. It's the function used from node_load_multiple().
function node_load_multiple($nids = array(), $conditions = array(), $reset = FALSE) {
  return entity_load('node', $nids, $conditions, $reset);
}


Inverse of a nonempty subset

Question: Let $S = \{a_{1}, a_{2}, ... a_{n} \}$ be a nonempty subset of $G$, which is a finite group. Also let $S$ be closed under multiplication. If $a_{i} \in S$, then we consider the distinct elements $a_{i}a_{1},...,a_{i}a_{n} \in S$. Because each product is distinct, $a_{i}a_{1} \neq a_{i}a_{k}$. But since I do not know $S$ is a subgroup yet, I cannot assume $S$ contains an inverse element for every $a_{i} \in S$. My question is can I assume $a_{1} \neq a_{k}$ even though I do not know that $a_{i}^{-1} \in S$?
Comment: Yes, since the inverses still exist in G.
Comment: The answer to the question you *should* have asked has been given by @Matt.  You want to show that for any $i$, $j$, $k$, **if** $a_ia_j=a_ia_k$, **then** $a_j=a_k$. In other words, you want to prove that for fixed $i$, the objects $a_ib$, where $b$ ranges over $S$, are distinct.
Answer: Drawing on the comments:
You are assuming that $a_i a_1\neq a_i a_k$. This is a statement about two elements of the group $G$ (whether they are equal does not depend on the choice of subset $S$ at this point). Since $G$ is a group, $a_i$ has an inverse in $G$. Multiplying by this gives that $a_1\neq a_k$ as elements of $G$, as required. However, this still doesn't tell you things about $S$. You don't yet know that $a_i^{-1}\in S$.

Inverse of a nonempty subset


What information do I get if I know that a function is log-concave?

Question: I have a log-concave function $f(\cdot)$ that is defined over $\mathbb{R}^{+}\rightarrow \mathbb{R}^{+}$. If I know that $f(0)=0$, $\lim_{x \rightarrow \infty}f(x)=0$, and in between it has strictly positive values, then can I conclude that it has a unique maximizer $x^{*}$? and what other properties can I know about this function?
My basic understanding of a log-concave function is that the log of it is concave, so if it starts from zero and ends at zero, then I can only imagine that it will have a unique maximizer, but I can't prove it, and maybe my imagination is flawed.
Comment: Maximizing $f$ is the same as maximizing $g(x) = \log(f(x))$. Your assumptions tell you $g(x) \to -\infty$ for $x \to 0$ and $x \to \infty$ and that $g$ is concave. Even if $g$ is arbitrarily smooth, this is clearly not enough to guarantee the uniqueness of the maximizer.
Comment: You would need to have another property, e.g. $f$ is twice differentiable and non-zero, in order to guarantee a unique maximum.  You can, however, guarantee that $f$ attains a maximum, and that $f$ attains this maximum over a unique interval $[a,b]$.
Comment: Let's assume that it is twice differentiable and non-zero. How can I prove that it has a unique maximizer?
Answer: The function $f(x) = \begin{cases} 0, & x=0 \\
e^{\min(0, 3-({1 \over x}+x)}), & \text{otherwise} \end{cases}$ is log concave
and has a maximum value of $1$, but $[1,2] \subset f^{-1} (\{0\})$, so it
is not unique.
Comment: There seems to be a mistake in your formula.
Comment: Thanks for pointing that out!


Cannot read property 'modalType' of undefined at Function.mapStateToProps [as mapToProps]

Question: I am new to react and using Dan Park's solution
https://medium.com/@danparkk/react-modals-scalable-customizable-neat-components-f2088d60f3d3
to design modal in my React project. But getting this error.
How can I try to debug it in react and why modalType is
modalRoot.js
import React from 'react';
import { connect } from 'react-redux';

/** Modal Components */
import LoginModal from '../../components/Modal/logInModal';
import SignupModal from '../../components/Modal/signUpModal';

/** Modal Type Constants */
import { LOGIN_MODAL, SIGNUP_MODAL } from '../../constants/ModalTypes';

const MODAL_COMPONENTS = {
  LOGIN_MODAL: LoginModal,
  SIGNUP_MODAL: SignupModal
};

const ModalContainer = (props) => {
  if (!props.modalType) {
    return null;
  }

  const SpecificModal = MODAL_COMPONENTS[props.modalType];

  return <SpecificModal />;
};

const mapStateToProps = state => {
  return {
    modalType: state.modal.modalType
  };
};

export default connect(mapStateToProps)(ModalContainer);

reducers.js
/** Initial State */
const initialModalState = {
  modalType: null
};

/** Modal reducer */
export default function (state = initialModalState, action) {
  const newState = Object.assign({}, state);

  switch (action.type) {
    case SHOW_MODAL:
      console.log(action.modalType);
      newState.modalType = action.modalType;
      break;

    case HIDE_MODAL:
      return initialModalState;

    default:
      return state;
  }

  return newState;
}

EDIT: I am combining the reducer with react boilerplate like this:
Filename : app/reducers.js
/**
 * Combine all reducers in this file and export the combined reducers.
 */

import { fromJS } from 'immutable';
import { combineReducers } from 'redux-immutable';
import { LOCATION_CHANGE } from 'react-router-redux';

import globalReducer from 'containers/App/reducer';
import modal from './reducers/modal';
import languageProviderReducer from 'containers/LanguageProvider/reducer';

/*
 * routeReducer
 *
 * The reducer merges route location changes into our immutable state.
 * The change is necessitated by moving to react-router-redux@5
 *
 */

// Initial routing state
const routeInitialState = fromJS({
  location: null,
});

/**
 * Merge route into the global application state
 */
function routeReducer(state = routeInitialState, action) {
  switch (action.type) {
    /* istanbul ignore next */
    case LOCATION_CHANGE:
      return state.merge({
        location: action.payload,
      });
    default:
      return state;
  }
}

/**
 * Creates the main reducer with the dynamically injected ones
 */
export default function createReducer(injectedReducers) {
  return combineReducers({
    modal,
    route: routeReducer,
    global: globalReducer,
    language: languageProviderReducer,
    ...injectedReducers,
  });
}

Comment: can you please add the part where you have configured the reducer to store or the combineReducer part
Comment: @Kodanda Rama Durgarao poluri I am using react boilerplate and I Updated it in app/reducers.js. I edited the code
Comment: The error is that in your mapStateProps you need to pass a selector in fact I'm not even sure that you need to use a container here since you pass your modalType directly to your function.
Comment: @soupette what is the selector in this case
Answer: It is updated by changing the selector
Updated code
const mapStateToProps = state => {
  return {
    modalType: state.modalType
  };
};


how to read & search excel data using Apache POI

Question: i am using Apache POI for reading Excel rows and using as needed. In order to Enhance the script for better reusability, how can i search and find a String value in all sheets under Column A and read corresponding row. For Example in Sheet2 ColumnA i have Name called Peter and in ColumnB Date of birth of Peter is 12/18/1984. Can you give code sample to search Peter in ColumnA in Excel work book and return his Date of Birth from ColumnB? Below is the code i am using currently may not suit above criteria.
<code>package com.Sample.GenericFunctionsLibrary;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

public class TestUtil {
    public static Xls_Reader excel = null;

    public static String path = "./XLFile/Data.xlsx";

    public static String mailscreenshotpath;

    public static String generateTimeStamp() {

        Calendar cal = new GregorianCalendar();
        int month = cal.get(Calendar.MONTH); // 3
        int year = cal.get(Calendar.YEAR); // 2014
        int sec = cal.get(Calendar.SECOND);
        int min = cal.get(Calendar.MINUTE);
        int date = cal.get(Calendar.DATE);
        int day = cal.get(Calendar.HOUR_OF_DAY);

        String timestamp = year + "_" + date + "_" + (month + 1) + "_" + day + "_" + min + "_" + sec;
        return timestamp;
    }

    public static boolean isExecutable(String tcid) {

        for (int rowNum = 2; rowNum <= excel.getRowCount("Credentials"); rowNum++) {

            if (excel.getCellData("Credentials", "TestCase_Name", rowNum).equals(tcid)) {
                if (excel.getCellData("Credentials", "runmode", rowNum).equalsIgnoreCase("Y")) {

                    return true;

                } else {

                    return false;
                }

            }

        }

        return false;

    }

    public static Object[][] getData(String sheetName) {

        int rows = excel.getRowCount(sheetName);
        int cols = excel.getColumnCount(sheetName);

        Object[][] data = new Object[rows - 1][cols];

        for (int rowNum = 2; rowNum <= rows; rowNum++) { // 2

            for (int colNum = 0; colNum < cols; colNum++) {
                data[rowNum - 2][colNum] = excel.getCellData(sheetName, colNum, rowNum); // -2
            }
        }

        return data;

    }

    public static void zip(String filepath) {
        try {
            File inFolder = new File(filepath);
            File outFolder = new File("Reports.zip");
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
            BufferedInputStream in = null;
            byte[] data = new byte[1000];
            String files[] = inFolder.list();
            for (int i = 0; i < files.length; i++) {
                in = new BufferedInputStream(new FileInputStream(inFolder.getPath() + "/" + files[i]), 1000);
                out.putNextEntry(new ZipEntry(files[i]));
                int count;
                while ((count = in.read(data, 0, 1000)) != -1) {
                    out.write(data, 0, count);
                }
                out.closeEntry();
            }
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // --------------------------------------Read Data From
    // Excel------------------------------------
    public static String[][] GetValue(String Pathfile, String sheetName, int startrow) throws IOException {
        File excel = new File(Pathfile);
        FileInputStream fis = new FileInputStream(excel);
        @SuppressWarnings("resource")
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet ws = wb.getSheet(sheetName);
        // System.out.println(startrow);
        int colNum = ws.getRow(startrow).getLastCellNum();
        // System.out.println(colNum);
        String[][] arrays = new String[1][colNum];
        for (int i = 0; i < colNum; i++) {
            XSSFRow row = ws.getRow(startrow);
            XSSFCell cell = row.getCell(i);
            arrays[0][i] = cellToString(cell);
            // System.out.println(arrays[0][i]);
        }
        return arrays;
    }

    // private static String cellToString(XSSFCell cell) {
    // Object result;
    // int type = cell.getCellType();
    //
    // switch(type)
    // {
    // case 0:
    // result = cell.getNumericCellValue();
    // break;
    // case 1:
    // result = cell.getStringCellValue();
    // break;
    // default:
    // throw new RuntimeException("there are no support for this type of cell");
    // }
    private static String cellToString(XSSFCell cell) {
        Object result;
        int type;
        try {
            type = cell.getCellType();
        } catch (NullPointerException e) {
            type = 2;
        }

        switch (type) {
        case Cell.CELL_TYPE_NUMERIC:
            DataFormatter formatter = new DataFormatter();
            result = formatter.formatCellValue(cell);
            break;
        case Cell.CELL_TYPE_STRING:
            result = cell.getStringCellValue();
            break;
        case Cell.CELL_TYPE_BLANK:
            result = "";
            break;
        default:
            throw new RuntimeException("there are no support for this type of cell");
        }
        //
        return result.toString();

    }

}
</code>
Comment: So what is not working with your code?
Comment: This code shall not search for the keyword, infact i have to assign required values manually. I am checking if i can get some thing dynamic like my actual question.
Answer: This method will take a String value for the name to search and return the address for the first record found in the column next to it, assuming that the name is in the first column and the address is in the second column.  It will iterate over all sheets as asked.  It returns empty String if name is not found.  Try/catch block excluded for readability.
<code>    public static String findAddressByName(String nameToSearch) {
        String fileLocation = "I:\\foo.xlsx";
        XSSFWorkbook wb = new XSSFWorkbook(new File(fileLocation));
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
            XSSFSheet sheet = wb.getSheetAt(sheetIndex);
            for (int rowIndex = 0; rowIndex < sheet.getLastRowNum(); rowIndex++) {
                XSSFRow row = sheet.getRow(rowIndex);
                if (row != null && row.getCell(0).getStringCellValue().equals(nameToSearch)) {
                    return row.getCell(1).getRawValue();
                }
            }
        }
        return "";
    }
</code>
Comment: Great! If i have int value in the Second Column i am seeing "Cannot get a text value from a numeric cell" Error. All other String values working fine.
Comment: You can use getRawValue() instead of getStringCellValue().  Updated the answer to use that.
Comment: Glad I could help!  Please accept answer if issue is resolved.
Comment: Dan, If i have to Fetch the Text/val in the Third column what should i add to the code?


How to decode an email with embedded images in Ruby/Rails Action Mailbox

Question: I am using Action Mailbox, to receive emails in my Rails application. When the emails contain images, I am not sure, how to save the email in the database, decode it, and then display it to the user so that it can be displayed like how we see emails in gmail etc.
I have used this code-
  class MyMailbox < ApplicationMailbox
    def process
     mail_content = mail.body.decoded
     post = Post.new(title: mail.subject, content: mail_content)
     post.save
    end
   end

This works well for emails which don't have any images etc. But I want a way to save emails with images. This is apparently to be done by using the different parts of the multipart email, but i am not sure how to proceed.
Finally, I want to display those emails with original look. Let me know how to proceed here. Thanks.
Answer: Before you attempt to handle images in the body of an email, you should first check if the email body is multipart or not:
# handle multipart message
body = mail.parts.present? ? mail.parts[0].body.decoded : mail.decoded

What does a multipart email look like? Something like this:
MIME-Version: 1.0
Date: Mon, 8 Nov 2021 19:43:58 +0100
References: <....mail>
In-Reply-To: <....mail>
Message-ID: <...@mail.gmail.com>
Subject: Re: Howdy
From: You <email@example.com>
To: Me <firstname.lastname@example.com>
Content-Type: multipart/alternative; boundary="000000000000376c4305d04b60e2"

--000000000000376c4305d04b60e2
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

Here is my reply to an original message.

--000000000000376c4305d04b60e2
Content-Type: text/html; charset="UTF-8"
Content-Transfer-Encoding: quoted-printable

--000000000000376c4305d04b60e2--

Note that the Content-Type header of the email contains a boundary which is used to separate the email parts. Now that you can see how each part can be a different content type, you have the proper context to understand how to parse each part.
https://github.com/mikel/mail#reading-a-multipart-email
Rails uses the mail gem, so you should reference their docs to understand full functionality. But in short, you can do the following:
if mail.parts.present? && mail.parts[0].content_type == 'text/html'
  sanitized = Rails::Html::WhiteListSanitizer.new.sanitize(mail.parts[0], tags: ['img'])
  # => "\n    \n    \n\n"
  html_doc = Nokogiri::HTML(sanitized)
  html_doc.to_s
  # => "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n\n\n  \n\n"
end

To display the original content of the message, just save the part in its entirety. You'll have to either infer the content type store it alongside the message in your database.
Assuming you're saving an HTML message, you can use Nokogiri, which comes with Rails, to generate an HTML document.


Find a line in a list of .gz files

Question: i around 50 .gz files in a particular directory in linux. i need to find a particular line in each file. currently i am doing by zcat each file.
Eg:
zcat 20160909-custfw.log.7.gz | zgrep BGP | zgrep  126.96.36.199

Output:

Sep  9 17:12:47 184.108.40.206 cap-s12-custfw-1: NetScreen
  device_id=cap-s12-custfw-1  [Root]system-information-00542: BGP peer
  10.24.224.187 changed to Idle state (2016-09-09 17:13:15)

please let me if there is any easier way to do this.
Comment: I am surprised that the above actually works. zcat uncompresses the whole thing and prints everything to stdout. You are wasting a lot of cpu cycles for absolutely no reason here.
Comment: Besides. this site is about programming problems. Your question would rather go to unix.stackexchange.com for example.
Answer: If you already have zgrep installed, you shouldn't have to zcat the file. The entire point of zgrep is to let you grep gzipped files directly. Therefore, you should simply be able to do this:
zgrep BGP *.gz | grep 22.214.171.124

This should be slightly more performant as well.
Answer: What about zgrep 'BGP.*220.127.116.11' $dir/*.gz?
(Or to achieve equivalent results to your sequence of two zgrep calls, you would have to zgrep also the inverse order of the two regexes, sth like zgrep 'BGP.*184.108.40.206\|22.214.171.124.*BGP' $dir/*.gz.)
Answer: Search them in parallel with GNU Parallel:
parallel zgrep BGP {} ::: *.gz | grep 22.214.171.124

If you know it only occurs once in each file, or are only interested in the first occurrence, use zgrep -m1 to avoid bothering to read the remainder of the file and stop on the first match.
Comment: thanks, this was exactly i was looking for, i want to check the first occurrence.

Find a line in a list of .gz files


How to decide a basketball game ended but not yet end of regulation

Question: We got a basketball game with score 56-61 4:40 mins remaining in the fourth quarter. Then game can't continue because of power outage (night). How should we decide on the game? Shall we continue on another day? Shall we declare the leading team as the winner?
Answer: On the assumption you're playing in some sort of organised tournament, ask the organisers.
Comment: Are there no FIBA rules on this?
Comment: Not within the official rules. Doing so (for any sport) would be pretty much impossible because the circumstances can vary so much - what is fair and equitable in one situation (a team leading by 20 with one second on the clock) would be patently stupid in another (a team leading by one point 10 seconds into the match).


Maximum value of sum of K partitioned subarrays

Question: Given a subarray of an array, its value is the maximum of the elements it contains that appear an odd number of times.
I want to Partition an array into K sub arrays to maximize the sum of the subarray values.
E.g. if we have following array
5 6 6 3 9 with K=2
We could partition it as follows:
(5) + (6,6,3,9) = (5 + 9 => 14 )
(5,6) + (6,3,9) = ( 6 +9 => 15 )
(5,6,6) + (3,9) = ( 5 + 9 =>14 )
(5,6,6,3) + (9) = ( 5 + 9 => 14 )
I am able to do it the brute way but looking for an efficient algorithm. Could you please suggest something
Comment: where's the code you have tried?
Comment: where is your limit?
Comment: @saijb Probably, I am trying to convince myself about it.
Comment: oh i got your question now
Comment: pls add maximum value of K & max number of element in array
Comment: K will always be less than equal to number of elements in the array
Comment: how many number can be there?
Comment: solution depends on constraints.
Comment: I think the question is what other algorithms except for brute force could be used for solving the problem
Answer: Actually the question seems like what the sum of maximum K number is. So just need to order by descending and sum the first K number.
Comment: The max K does not fully cover the problem. For example, the expected result for (6,6,6) and K=2 is 6 and it couldn't be calculated by the algorithm to find K max elements
Comment: why for k=5 answer 9
Comment: Another counter example is  [9,9,9,8] and k=2 will give you 17 and not 18
Answer: The algorithm I see is quite easy. You need to find positions of K maximum values in the array and then divide array in the way that these positions are in different subarrays in the way that max value is included the odd number of times in each subarray. Need to specifically look into the last case. One of the options is trying to get the first one if K limit is reached.
So, for (6,6,6) and K=2 the algorithm should be:
Find 2 max elements (if K limit is reached, take the first K). In our case, it's first and second 6.
Then divide into subarrays (from max to nextMax-1)
(6) + (6,6) => 6

Quite an interesting case is (6,7,6,6) and K=3
The expected result is
(6) + (7,6) + (6) = 19

My algorithm doesn't cover that case
Pseudocode:
1. indexes = FindKMaxIndexes() // Use selection algorithm https://en.wikipedia.org/wiki/Selection_algorithm, some variation to save indexes instead of elements values
2. reorder indexes from smallest to largest
3. i = 0
4. for each item in sorted indexes array
4.1 create subarray to include item (from i to current index)
4.2 i = current index + 1

Answer: Clearly, we can have O(n^2 * k) since if f(i, k) represents the maximum achievable up to A[i] with k parts, then:
f(i, k) = max(
  // include A[i] in previous part
  g(A[j..i]) + f(j - 1, k - 1),

  // don't include A[i] in previous part
  A[i] + f(i - 1, k - 1)
)
for all k <= j < i
where g(subarray) is the max element
in subarray that appears an odd number
of times

The question is how can we more efficiently pick which subarrays to test including A[i] against.


Named optional argument and multiple argument order

Question: I have a function wrapper like this.
def funcWrapper(fn_ng, order=None, *args ):
    def clsr(X):
        if order is not None:
            X = calc_poli_dsX(X, order)
        return fn_ng(X, *args);
    return clsr;

However, if I use this function as below:
mGrdnt = funcWrapper( gd.squared_error, dsX1, dy, order=None)
mGrdnt = funcWrapper( gd.squared_error, dsX1, dy)

I have error of

TypeError: funcWrapper() got multiple values for keyword argument
'order'

My guess was that, if I do not specify 'order', funcWrapper will pass 'dsX1' and 'dy' are passed as *arg, but it turned out they are not. No matter I specify an optional argument, it seems that 'dsX1' and 'dy' all go into the 'order' named optional argument.
How can I make a function wrapper that can pass dsX1 and dy into *arg when the optional argument is/or is not specified?
Answer: You can just modify the call:
arr = [dsX1, dy]
funcWrapper(gd.squared_error, None, *arr)

or you can do something like this:
funcWrapper(gd.squared_error, [dsX1, dy])

Comment: Thanks for your answer. It seems that I always have to follow the order. If I do like funcWrapper(gd.squared_error, [dsX1, dy]), [dsX1, dy] goes into optional and it does not work. If I do funcWrapper(gd.squared_error, *arr), dsX1 goes into option...


vertical alignment of ul all the way to the top inside a div - no img, just text

Question: This seems SO simple,(and I feel pretty stupid and toasted) but I've tried all I can find (spent 6 hours digging on the web, w3schools, etc.), and I can't get a simple text ul to go ALL THE WAY to the top of a div it is inside of? It is as if there is a "margin" or a "pad" inside the DIV. I've looked at it with firebug and dreamweaver and I see the same thing. THe real page I am concerned about is at the bottom of this post.. Thnks Everybody
Here's a link to the stripped down HTML shown here:
http://www.abscomputersouthbay.com//CC_Website/one_ul_in_a_div.html
there is also another link to this code at jsfiddle in the link above, - I don't have "10 reputation" yet, so I can't have more than 2 links in a post.. :)

the ul should be right below this line of text, right up to the top of the DIV it
is inside of, with no empty "white space" the looks like a "empty line"

PC World News (external news feed)

PC Mag - New products (external news feed)

Site Map

Here's the actual page I was working on that got me on this tangent... starting with "PC & IT SERVICE, SUPPORT, DEVELOPMENT"
http://www.abscomputersouthbay.com/index.php/services-and-support
THANK YOU
Craig
Answer: ul does not get its margin from body, you can see it clearly in firebug; it works if you give it its own margin as shown in this fiddle
body, ul {
  color:#000000;
  background-color:#FFFFFF;
  margin: 0;
  padding: 0;
}

obviously, there are more elegant ways of assigning the correct css, just done that way for demonstration purposes
Comment: I should have listened to the guy in my head when he said "Step away from the keyboard, S L O W L Y..." - Iwent and had somthing to eat and got thinking why would this be the only text I've ever seen that didn't go to the top of a div by default??
Comment: And realized it must be the ul - not the DIV, sure enough - like you said Thank You of course! and I should have realized that "the browsers..." I imagine give them a default margin/pad.. or maybe that's how a ul is originally intended to be. Hard to see the "ones through the zero's" - I mean "the forest through the trees.." Thanks again


How do I know $x \in \bigcap\limits_{n = 1}^\infty f^{-1}([n,\infty))$?

Question: Suppose $X$ is a compact metric space and $f: X \rightarrow \mathbb{R}$ is a function for which $f^{-1}([t,\infty))$ is closed for any real $t$. Then $f$ achieves its maximum value on $X$.
I am first trying to prove that that $f$ is bounded above. Suppose, for the sake of contradiction, that $f$ is not bounded above. So for all $M \in \Bbb{R}$, there is a $x \in X$ such that $f(x) > M$. So there exists a sequence $\{x_n\}$ in $X$ such that for all $n \in \Bbb{N}$, we have $f(x_n) > n$. So $x_n \in f^{-1}([n,\infty))$ for all $n \in \Bbb{N}$. Since $f^{-1}([n,\infty)) \subseteq X$ are closed for all $n \in \Bbb{N}$, $f^{-1}([n,\infty))$ are compact for all $n \in \Bbb{N}$. Further, since each $f^{-1}([n,\infty))$ is nonempty, and $f^{-1}([n + 1,\infty)) \subseteq f^{-1}([n,\infty))$ for all $n \in \Bbb{N}$, $\bigcap\limits_{n = 1}^\infty f^{-1}([n,\infty))$ is not empty, and it is also closed.
I am trying to show now that $\{x_n\}$ has a convergent subsequence $\{x_{n_k}\}$ that converges to some $x \in \bigcap\limits_{n = 1}^\infty f^{-1}([n,\infty))$, and reach a contradiction since $$\bigcap\limits_{n = 1}^\infty f^{-1}([n,\infty)) = f^{-1}(\bigcap\limits_{n = 1}^\infty [n,\infty))$$ is empty (since $\bigcap\limits_{n = 1}^\infty [n,\infty)$ is empty).
My issue is, how do I know $x \in \bigcap\limits_{n = 1}^\infty f^{-1}([n,\infty))$? I know its in $X$ since it is compact, but I don't know if its in $x \in \bigcap\limits_{n = 1}^\infty f^{-1}([n,\infty))$.
Help, please.
Answer: Here is a slightly more general statement:

Claim. Let $K_1 \supseteq K_2 \supseteq \cdots $ be non-empty closed subsets of a metric space $X$. If $x_n \in K_n$ for each $n$, then every subsequential limit of $(x_n)$ lies in $K_{\infty} := \bigcap_{n=1}^{\infty} K_n$.

For instance, we may apply this to $K_n = f^{-1}([n, \infty))$.
This claim does not involve compactness. As such, $K_{\infty}$ can be empty. In particular, if $K_{\infty} = \varnothing$ then $(x_n)$ has no subsequential limit in $X$.

Proof. Let $(x_{n_k})$ be a convergent subsequence of $(x_n)$ and write $x$ for its limit in $X$. Then for each fixed $N$ and for each $k \geq N$, we have $x_{n_k} \in K_{n_k} \subseteq K_{n_N}$. So, by the closedness of $K_{n_N}$, we have $x \in K_{n_N}$. But since this is true for every $N$, we must have $x \in \bigcap_{N=1}^{\infty} K_{n_N} = K_{\infty}$.

As for the last equality, we have

Lemma. If $A_1 \supseteq A_2 \supseteq \cdots$ is a sequence of sets, then for any subsequence $(A_{n_k})$ we have $\bigcap_{k=1}^{\infty} A_{n_k} = \bigcap_{n=1}^{\infty} A_n$.

Proof. To show that two sets are equal, we may try to show that one contains the other.
First, assume that $x \in \bigcap_{k=1}^{\infty} A_{n_k}$. This means that $x \in A_{n_k}$ for each $k$. Now, for each $n$, there exists $k$ such that $n_k \geq n$, and so, $x \in A_{n_k} \subseteq A_n$. Since this is true for all $n$, we have $x \in \bigcap_{n=1}^{\infty} A_n$, and so, $\bigcap_{k=1}^{\infty} A_{n_k} \subseteq \bigcap_{n=1}^{\infty} A_n$.
The other direction $\bigcap_{n=1}^{\infty} A_n \subseteq \bigcap_{k=1}^{\infty} A_{n_k}$ is almost obvious. Indeed, if $x \in \bigcap_{n=1}^{\infty} A_n$, then $x \in A_n$ for any $n$, and so, $x \in A_{n_k}$ for any $k$.
Comment: I'm a bit confused with the notation. What is $K_{x_N}$, and how does the indexing work for $\bigcap_{N=1}^{\infty} K_{n_K} = K_{\infty}$? @Sangchul Lee
Comment: @Diddysmash, I fixed typos :) Thank you for pointing out them.
Comment: Thanks for the help!
Answer: You cannot know that, since it is not true. Suppose that $x\in\bigcap_{n=1}^\infty f^{-1}\bigl([n,\infty)\bigr)$. Then $(\forall n\in\mathbb{N}):f(x)\geqslant n$. But no real number is greater than or equal to every natural number.
Comment: I guess OP is beginning with the assumption that $f$ is not bounded above and hoping to derive a contradiction.