RxJS nested subscribe

Question: Is it possible to avoid nested subscribe in the following code?
this.requestService().subscribe(
      () => this.success(),
      error => {
        const errorDescription = {
          one: 5,
          two: 10
        };
        return this.error(errorDescription).subscribe();
      }
    );

The second subscribe is part of the error callback of the Observer. How could we use e.g. switchMap as to have only one subscribe?
Comment: can you please share the code of `this.error()` function?
Answer: Seems like you need a catchError, that will let you substitute an error with another stream. Though we'll have to update successful result handling:
this.requestService().pipe(

  // handle success value
  tap(() => this.success()),

  // when an error happens
  catchError(error => {
    const errorDescription = {
      one: 5,
      two: 10
    };

    // we switch to `this.error` stream
    return this.error(errorDescription);
  })
).subscribe(value=>{
  // ...here you'll receive both:
  // events from the requestService()
  // and events from this.error(errorDescription)
});

Heres an article with detailed overview of error handling in RxJS
Hope this helps
Answer: Here's an idea to avoid a 'nested' subscribe. With the code you provided, this is the best I can come up with. If you have any questions, let me know and I'll help.
import { of, throwError } from 'rxjs';
import { map, switchMap, catchError } from 'rxjs/operators';

// this.requestService().subscribe(
//       () => this.success(),
//       error => {
//         const errorDescription = {
//           one: 5,
//           two: 10
//         };
//         return this.error(errorDescription).subscribe();
//       }
//     );

const error = throwError('oops');
const success = of('success!');
const handleError = (d) => of({one: 5, two: 10}).pipe(
  map(n => n),
  catchError(e => 'could not do 2nd network request')
);

const requestServiceSuccess = success.pipe(
  switchMap(d => of(d)),
  catchError(handleError)
)

const requestServiceFail = error.pipe(
  switchMap(d => of(d)),
  catchError(handleError)
)

// if your first network request succeeds, then you will see success
requestServiceSuccess.subscribe(
  (d) => console.log(d),
  (e) => console.log(e)
)
// if your first network request fails, then you will see your errorDescription
requestServiceFail.subscribe(
  (d) => console.log(d),
  (e) => console.log(e)
)

You can paste this into stackblitz to check the logs
https://stackblitz.com/fork/rxjs?devtoolsheight=60
Comment: Two subscriptions will likely cause two requests, you need to be careful here. With `of('success')` you wont notice, but try adding `of('success').pipe(tap(console.log))`. Its considered a good practice to have one or even **zero subscriptions** in your code (zero subscriptions can be achieved using e.g. `| async` pipe in angular or out-of-the box with redux epics).
Answer: I would probably do it like this:
this.requestService().pipe(catchError(e => {
  const errorDescription = {
      one: 5,
      two: 10
  };
  return this.error(errorDescription).pipe(switchMap(empty()));
  // the switch to empty will prevent the error going to success
  // consider moving this into the error handler itself.
})).subscribe(
  () => this.success(),
  error => {
    //should never get here.
  }
);

the catchError -> switchMap -> empty is a pattern that appears pretty frequently in my code as my error handlers should stop the processing chain more often than not.

RxJS nested subscribe


How to calculate the significance of a distance correlation

Question: I have two sets of data points and want to know the correlation.
I.e., my Hypothesis is "The two set of data points are correlated".
The data points are (if at all) non-linear correlated.
This is why I chose distance correlation as my metric.
However, I also want to know whether or not my results are significant, i.e., is the (non)correlation strong enough based on my data points that I can confidently reject my initial hypothesis.
What test do I need to apply to calculate the significance of a distance correlation value?
Answer: Looking at the original paper, I would recommend their approach (section 5):

To implement the distance covariance test for small samples, we obtain a reference distribution for $n\mathcal{V}^2_n$ under independence by conditioning on the observed
sample, that is, by computing replicates of $n\mathcal{V}^2_n$ under random permutations of the indices of the Y sample.

Essentially, you have your current distance correlation $\mathcal{R}_0$. You randomly reallocate each observation from set 1 to a different observation from set 2, without replacement, and recalculate the distance correlation. Your P-value is the number of resamples where the distance correlation is greater  than $\mathcal{R}_0$, so I would recommend doing at least on the order of 10,000 resamples assuming your dataset is not so small that you can actively exhaust all possible permutations.
By the way, this will only allow you to reject a hypothesis of no correlation, but that is usually what these kinds of tests do ('the two sets are correlated' is usually the alternative hypothesis).
Comment: Yes, that sounds about right - obviously you wouldn't be able to make 10K unique permutations from just 3 pairs. Just keep one side of indices fixed and select a random match from the other set.
Comment: Thank you for your response. To make sure I understand you correctly. Given the observations `[(1,2),(3,4),(4,5)] `  I would do 10k permutations where I change up the first observation, e.g., `[(3,2),(4,4),(1,5)]` and then recalculate the distance correlation. I count the amount of times the correlation is higher and divide it by the amount of permutations?


Is there a single logic symbol for "implies the negation of"?

Question: Is there a single logic symbol for "implies the negation of"?
(I came up with this question when studying English grammar, on realising that such a symbol when reversed and itself negated could be used to relate A and B in a sentence comprising a main clause followed by a concession clause, e.g. A, even though B, meaning B does not imply the negation of A.)
Comment: @GPerez - That's two symbols: $\rightarrow$ and $\lnot$
Comment: $\text{A}\rightarrow\neg\text{B}$?
Answer: In classical logic, this is equivalent to NAND.
Proof. The following are equivalent:

$A \rightarrow (\neg B)$
$(\neg A) \vee (\neg B)$
$\neg(A \wedge B)$

So you could denote it with a Sheffer stroke. As in:
$$A \uparrow B = A \rightarrow \neg B$$
Comment: Thanks for this. Would turning it upside down be comprehensible to many people as an expression of the inverse relation?
Comment: @h34, see [here](http://en.wikipedia.org/wiki/Logical_NOR#Definition).
Comment: Thanks @goblin. This is a full answer to the question, so I've accepted it and +1'ed it. But the symbolism is more pure-logical and less intuitive than I'd hoped. I'd thought there might be something that people could read in a grammatical and rhetorical context and link with destruction (*A stops B from being true*; cf. $\Rightarrow$ giving a feeling of flow), just going by the look of the symbol, and that was not only strikeable through but also nicely reversible. I think in my context I will go with $\rhd$, $\lhd$, $\ntriangleright$, $\ntriangleleft$.
Comment: @h34, I hear you. Tbh I find the equivalence between $A \rightarrow \neg B$ and $\neg(A \wedge B)$ to be a little difficult to understand intuitively. Part of the problem is that we often like to view $\rightarrow$ as "causation" which strictly speaking it is not.
Comment: And thus in reverse Polish notation, D == NC


What makes a structure-preserving map?

Question: I'm trying to understand what is meant exactly by "structure-preserving map".  To do so, I'm looking at two examples I was given.  Note that I'm going to write everything in function notation because it helps illustrate what I'm saying better, I think.  So for instance, I'll write $\langle m_1, m_2\rangle$ as $\langle\cdot,\cdot\rangle(m_1,m_2)$.  Hopefully that won't confuse anyone.
First is a vector space $(M,+,\cdot)$ is a set $M$ along with two operations $+:M\times M\to M$ and $\cdot: \Bbb C\times M\to M$.  Then the structure-preserving maps on this are the functions $\phi: M\to N$ such that if $m_1, m_2\in M$ and $k\in\Bbb C$
$$\phi(+_M(m_1,m_2)) = +_N(\phi(m_1),\phi(m_2)) \\ \phi(\cdot_M(k,m_1)) = \cdot_N(k,\phi(m_1))$$
Seeing this I think structure-preserving maps are those maps that can commute (sorta) with the defining operations on the set.
Then I look at the notion of an inner product space $(M,+,\cdot,\langle\cdot,\cdot\rangle)$.  The structure-preserving maps on this space have the same properties as above -- because an IPS is a type of VS -- but additionally satisfies
$$\langle\cdot,\cdot\rangle(\phi(m_1),\phi(m_2)) = \langle\cdot,\cdot\rangle(m_1,m_2)$$
But this doesn't seem to fit with what I concluded about structure-preserving maps above.  I realize that something like $\langle\cdot,\cdot\rangle(\phi(m_1),\phi(m_2)) = \phi(\langle\cdot,\cdot\rangle(m_1,m_2))$ wouldn't make sense because $\langle \cdot, \cdot\rangle$'s target is the complex numbers, but then what makes this the additional condition for structure-preserving maps on IPS's?
If structure-preserving maps aren't the functions that sorta commute with the defining operations on the set, then how should I see them so that I can recognize what the structure-preserving maps must be when learning about new types of structures on sets?
Answer: Consider metric spaces: there are tons of possible structure preserving maps between those: continuous maps, uniform maps, Lipschitz maps, isometries, Hölder continuous maps and so on and so forth. From a naive point there is no obvious "right" notion, although a structure preserving isomorphism should preserve properties you care about, like completeness (every Cauchy-sequence converges) in this example.
You probably need to decide for yourself why you care about a particular notion of structure preserving map if there is no obvious one.

Other than that: The "best" kind of structure preserving map gives you the "best" (category-theoretic) category. In the case of metric spaces $1$-Lipschitz maps seem to be better than everything else since the isomorphisms preserve e.g. completeness  and they make the category of metric spaces complete (that's a different kind of "complete"), unlike e.g. isometries. But these are sort of "high-level considerations".
Comment: So what you're saying is that when textbooks or Wikipedia says "the" structure-preserving maps they mean the maps that preserve the *most* structure possible (that have been discovered up to that point).  Then the definition of structure-preserving map for IPS's that I give above makes sense because the condition involving the IP says that $\phi$ preserves distance, in addition to addition and s-multiplication.
Comment: I'm saying it need not be completely obvious what the right kind of map needs to be.

What makes a structure-preserving map?


Retornar o comprimento da sequencia

Question: Estou com um problema que não consigo resolver:
Dada uma string "aeiaaioooau", identificar sequencias existentes e contar seus elementos com PHP.
Uma sequencia seria a,e,i,o e u ...

Exemplo:
$s = "aeiaaioooau"

"aei" é sequencia de 3 elementos, portanto soma + 3
depois "aa" não é sequencia,portanto não soma nada
depois "iooo" é sequência de 4 elementos, portanto soma + 4
o proximo "a" não soma nada por não ser sequencia
por fim "u" é sequencia de 1 elemento, soma + 1

Sendo os elementos sequenciais "aei+iooo+u" = 8 elementos.

Como fazer isso com PHP?
Comment: Olá. Não entendi muito bem a proposição. Por que "aai" não é sequência mas "iooo" é?
Comment: Qual a lógica? Por que o último *a* não é considerado uma sequência, mas *u*, sim? No caso de outra palavra, exemplo: *abecedario*, o resultado deverá ser *4* ou outro valor?
Comment: Isso é um exercício de escola? Você precisa, antes de aplicar essas lógicas, quebrar a string para ter os elementos distintos em um array para depois tentar utilizá-lo para cada situação. Boa sorte.
Comment: a lógica é que uma sequencia é sempre 'a,e,i,o , u' , portanto aaaeiiiiioooou é uma sequencia tanto como aeiou, mas aaaaeiaaaaaou , tem que ignorar essa cadeia de aaaaa para poder ser contabilizados.
Answer: <?php
$s = "aeiaaioooau";
$sequences = array("aeiou", "aeio", "aei", "ae", "a", "eiou", "eio", "ei", "e", "iou", "io", "i", "o", "u");
$sequenceLengths = array();

for ($i = 0; $i < strlen($s); $i++) {
    for ($j = $i + 1; $j <= strlen($s); $j++) {
        $substring = substr($s, $i, $j - $i);
        if (in_array($substring, $sequences)) {
            $sequenceLengths[] = strlen($substring);
        } else {
            break;
        }
    }
}

$totalElements = array_sum($sequenceLengths);
echo "Total de elementos sequenciais: " . $totalElements;
?>

Neste exemplo, você define um array $sequences com todas as possíveis sequências possíveis ("aeiou", "aeio", "aei", etc.). Em seguida, você percorre a string e verifica todas as substrings possíveis para ver se elas estão presentes nas sequências definidas. Se estiverem, o comprimento da substring é adicionado ao array $sequenceLengths.
Por fim, você calcula a soma de todos os comprimentos das sequências encontradas e exibe o resultado. No caso do exemplo "aeiaaioooau", o resultado será 8 (como no exemplo).

Retornar o comprimento da sequencia


Did Chopin Op. 6 have four or five pieces?

Question: On IMSLP and Wikipedia they only list four, but I found some sources that have a fifth one as well such as here and here. What is with the discrepancy?
Answer: The first editions of Frédéric Chopin's Muzurkas, Opp. 6 & 7 were published in (1833) Leipzig, as works of 4 and 5 pieces respectively.
The last piece of Op. 7 (№ 5 Vivo in C major) was moved to Op. 6 for a Paris edition† which came later.
This is explained at the bottom of the IMSLP page for Op. 7:

*The 5th Mazurka appeared in Op.7 only in the first Leipzig edition. It was issued as the 5th item in Op.6 of the Paris edition.

It's also mentioned (in passing) at the top of a link in your question; the TFCI page for Op. 6 No. 5:

The Mazurka in C major that closes Opus 6 in the Paris edition (Opus 7 in the Leipzig edition) is an oberek.

You can also find this piece listed on the Wikipedia page for Op. 7.

† Apparently this is not the same as the (c. 1916–22) Paris edition that can be found on IMSLP.


Is the extension $\text{Totally Ramified}$?

Question: $(1)$ Let $K/F$ be a finite extension of the local field $F$ of characteristic $0$ obtained by adjoining by the roots of a irreducible monic polynomial to $F$. Is the extension $\text{Totally Ramified}$ ?
I know that adjoining the roots of an Eisenstein polynomial produces $\text{Totally ramified}$ extension.
$(2)$ What is the easiest way to check whether the extension is Totally ramified or not ?
Please help
Comment: It may or may not be totally ramified.
Comment: If you've chosen your polynomial well, you can read off the ramification properties by looking at the polynomial over the residue field. In particular, if the polynomial is not completely reducible over the residue field, then the extension is not totally ramified.
Comment: @mathvision the converse holds if you've chosen your polynomial well, namely if a root of your polynomial generates the ring of integers of $K$. For a counter example, if $p\ne2$ the polynomial $X^2 + p^2$ generates an unramified extension of $\mathbb Q_p$ even though it is reducible mod $p$.
Comment: @AnginaSeng, when will be ?
Comment: @Mathmo123, is the converse hold ?  That means, if a polynomial is reducible in residue field, is the Galois  extension totally ramified ?
Comment: Local fields are $\Bbb{R}$, $\Bbb{C}$ and the finite extensions of $\Bbb{Q}_p$ and $\Bbb{F}_p((t))$ (proving so is interesting), the latter two have unramified extensions. Maybe you are thinking to $\Bbb{C}((t))$ whose algebraic closure is $\bigcup_n \Bbb{C}((t^{1/n}))$.
Comment: @reuns, the unramified extensions of $\mathbb{Q}_p$ are obtained by adjoining roots of unity. When will get a Totally ramified finite Galois extension ? I mean which kind of polynomial do the job? e.g., Adding roots of Eisenstein polynomial (in the splitting field) produce totally ramified Galois extension ?
Comment: @Mathmo123, so if a polynomial, in $\mathbb{Q}_p$, has a uniformizer $\pi$ as its root then the Galois extension is totally ramified?
Comment: @Mathmo123, your comment was helpful. But I need to understand the story behind it. You said, (1) if the polynomial is not completely reducible over the residue field, then the extension is not totally ramified. Why is that ? Next, you said,  (2) the converse holds if you've chosen your polynomial well, namely $\text{if a root of your polynomial generates the ring of integers of K.}$ Why is that ? Can you please explain these two facts in two comments. It will help me
Answer: Let $K$ be a local field with residue field $k$ and uniformiser $\pi$. Let $F$ be a finite extension with residue field $k_F$ and uniformiser $\pi_F$. An extension $F/K$ can take one of two flavours:

If $\pi\mathcal O_F = (\pi_F)^e$, we say the extension is ramified. It is totally ramified if $e = [F:K]$.

If $\pi\mathcal O_F = (\pi_F)$ is still prime, we say the extension is unramified. In this case, we can choose $\pi_F = \pi$.

In the ramified case, the extension is obtained by adding a new uniformiser of smaller valuation: if we normalise the valuation on $F$ so that $v(\pi_F) = 1$, then $v(\pi) = e$. In the totally ramified case, the residue field $k_F = k$.
In the unramified case, the uniformiser does not change. Instead, the extension is happening on the residue field: $[k_F: k] = [F:K]$.
Now, suppose that $F = K(\alpha)$ where $\alpha$ is a root of the irreducible polynomial $f$. We can always assume that $f$ is monic with integer coefficients. In this case, $\alpha$ is an algebraic integer. Let $\overline \alpha$ be its image in $k_F$. Then $\overline \alpha$ is a root of $f\pmod \pi$. In particular, if $F/K$ is totally ramified, then $k(\overline \alpha) = k$. It follows that $f\pmod \pi$ is completely reducible.
The converse is false in general, as $f$ could be a polynomial like $X^2 + p^2$, and $F(\sqrt{-p^2}) = F(\sqrt{-1})$ is unramified if the residue characteristic is not $2$. The problem here is that the map $\mathcal O_K[\sqrt{-p^2}]\to k_F$ is not surjective: its image is exactly $k$! However, if $\mathcal O_F = \mathcal O_K[\alpha]$, then the map $\mathcal O_K[\alpha]\to k_F$ is surjective. In particular, $k_F = k(\overline \alpha)$. So if $f\pmod \pi$ is completely reducible, then $k_F = k$, so $F$ is totally ramified.
Comment: You said $\text{In this case, we can choose $\pi_F=\pi$}$. Do you mean "the case of unramified  extension "?


Dynamic language links from menu?

Question: I am trying to find a way to do the following:

Add languages to Drupal 9 menu items
Translate content/menu links
Provide (from the Main Navigation) a list of languages the current page is translated in

I was able to complete the first two, but I cannot see how to get a menu to list links that output the available language options for the current entity. I see that there is a Language Switcher block from core, but is there a way to make this appear baked into a Drupal menu itself?
Comment: I don't think this has been fully solved in core yet, there are modules to help like https://www.drupal.org/project/menu_block_current_language, https://www.drupal.org/project/menu_manipulator, https://www.drupal.org/project/menu_multilingual
Comment: Hmmm... there must be a way to mimic this. I'll take a look around
Comment: For a code solution you would need a dynamic menu link plugin pointing at the current node derived for each language. Like this example for local tasks https://drupal.stackexchange.com/questions/292739/how-to-get-links-of-translated-node-edit-page-in-the-secondary-tabs
Comment: I see - that would work even if its not a local task? Like how would you get it appended to "Main Navigation"?
Answer: You put the static infos in *.links.menu.yml where you also define dynamic menu link plugins, which provide the infos you can't put in a static yml. And the deriver to produce a plugin for each language. The local task example was just an example for the translation stuff.
A working static example:
mymodule.links.menu.yml
<code>mymodule.language.top:
  title: 'EN'
  menu_name: main
  route_name: '<none>'
  expanded: true
  # Plugin class to override the title dynamically:
  # class: Drupal\mymodule\Plugin\Menu\TranslatedNodeTop
mymodule.language.item:
  title: 'Node 8 spanish'
  parent: mymodule.language.top
  route_name: entity.node.canonical
  route_parameters: { node: '8' }
  menu_name: main
  options:
    attributes:
      class:
        - foo-class
        - bar-class
  # deriver for installed languages
  deriver: Drupal\mymodule\Plugin\Derivative\TranslatedNodeTabDeriver
  # Plugin class extending MenuLinkDefault overriding static properties dynamically,
  # the route parameter from the current route match, the language from the deriver
  # the title from both and link attributes added for the current language:
  # class: Drupal\mymodule\Plugin\Menu\TranslatedNodeItem
</code>
You need to add the two dynamic plugins extending MenuLinkDefault. I've recycled the TranslatedNodeTabDeriver from How to get links of translated node edit page in the secondary tabs.

Dynamic language links from menu?


Arranging a piece for full Orchestra

Question: I have recently finished writing an intermediate level piece for piano duet, and think it would sound pretty good when played by a full orchestra. Only problem is I don't know any one who can arrange it, and I myself am only a pianist. I don't play any strings, winds, or horns. Any advice? Oh, and the piece is in G major.
Update: I have just finished editing the piano duet version, and will posting it to Youtube shortly.
Comment: You can definitely take a stab at it yourself and have fun a learn a lot but I agree you want some software. If you have a Mac Logic Pro X for $200 is a good deal with all the basic orchestral sounds and even a score view of midi. Or you could get some cheaper base software like Reaper and add an orchestral library.
Comment: I suppose you either take a few years off and learn to orchestrate and conduct *or* you work with a composer/conductor?
And yeah, an orchestra.
Comment: Do you have a computer or arranger keyboard you could use to sequence an arrangement on?
Comment: @topomorto, I have a Yamaha P105 Keyboard, and access to the Sibelius 6 program (through my college).
Comment: I would echo what others are suggesting - get a book on orchestration and have a go yourself on the computer. You're probably aware of what Sibelius can do for you.... but your Yamaha can also be connected to a computer (if you have one..?)
Comment: @topomorto I do have a computer at home. Just not a very good one.
Comment: How old is it? It was possible to do all this on computer 15 years ago, so unless it's really old, you may be fine.  It's just a question of getting software it can cope with. If you really want to give the computer an easy life, you can just use it as a MIDI sequencer with an external MIDI module - I was doing that in the early 90s, and I'm sure your computer is better than the one I used then!
Comment: @topomorto My computer is at least 18 years old, and has less then one gig of memory remaining, due to the fact that its not just my computer.
Comment: Well if you like the idea of working with computer it's definitely worth finding something that works - people routinely give away computers that are 8-10 years old which would be fine for your purposes. If it seems too much hassle (getting into computer music can be something of a time-sink!), you could still get a little second hand midi module with some orchestral sounds and a cheap multi-track recorder of some kind - or get some kind of arranger keyboard.
Comment: That's why we orchestra players end up with unrealistic parts nowadays... :p
Comment: Regarding the computer idea.  Buying a computer capable of doing what you want - as suggested in other comments - will be way cheaper than hiring an orchestrator to do it for you.  And afterwards you will have a brand new computer to orchestrate your next piece on.  Just a thought.
Comment: I'm actually in the process of saving for a new one anyway (my computer is so old, it's beige.)
Answer: You don't need to play an instrument in order to write for it.  After all, the vast majority of people don't play every orchestral instrument (at least not well; music ed majors typically have to learn a bit of everything but they're not expected to achieve anything close to mastery).  It's just important that you know how every instrument works so that you can write for it effectively.  It's surprisingly easy to write something insanely difficult without even realizing it.
Pick up a book on orchestration.  There are lots of good ones, and one of the standards is the Rimsky-Korsakov Principles of Orchestration, which is public domain.  A few bits are outdated (don't write for alto trumpet) but you won't do anything too bad if you stick to the guidelines there.
Most importantly, run your parts by good musicians (or just post here) to make sure nothing is terrible.
Comment: That text was okay in 1880s but, as you mentioned, pretty out of date now.  Instruments / aesthetic are different now and information is better / relevant / more practical.
Comment: From there, sure. Nobody got ever fired for reading R-K. By the way I intended the OP's question, she has an actual piece and she *actually* wants to arrange it for an actual orchestra. Like, for real. So in my eyes it's not a matter of "where to start" but "how to realistically get it done", and I don't think there is a DIY way, although having a sequencer draft ready and a general idea of how it's done **will** help when working with the actual orchestrator/conductor.
Comment: I'm not sure I agree with the "read a manual, write a score" approach.
Orchestration is a fine art, it takes a lot of time to learn to produce an acceptable score. I read R-K's manual myself and it helped me a great lot in *understanding* what I hear and in piecing together sequenced pieces, but I would never attempt to write a score and give it to an orchestra. It would be helpful in coming up with a decent rough sequencer  draft, but it **will** need attention by a composer anyway. (If you are Hans Zimmer, the composer will be credited as copyist, but that's another matter)
Comment: @Interwebs - you gotta start somewhere.  Where else would you start?
Comment: I myself don't play any bowed string instruments or have much knowledge on what double stops are hard and which ones are easy, but I still write and arrange both for duets with string instruments(my incomplete Cello Sonata in F for example) and more often, a string quartet(I'm working on an arrangement of K 545 for a string quartet right now and I have reached the second movement).
Answer: As the poster above me mentioned, Rimsky-Korsakov's book is a great resource, along with Kent Kennan's Technique of Orchestration, and Samuel Adler. There's many orchestration books out there, and be sure to do some research on voice leading and counterpoint. Watch some videos showcasing each instruments' ranges, timbres, and qualities. Also, get yourself some kind of Notation software or DAW. While it's important that you don't rely on software for orchestration alone, it can be helpful to hear how your orchestration sounds.
Comment: What do you mean "possibly Samuel Adler"?  - his orchestration book is required reading for practically everyone.
Comment: Good point. I edited my post.
Answer: I think you would have fun learning to orchestrate and using your piano duet as a "guinea pig" test case!
However, if you want results sooner rather than after a long process of learning to do it yourself, do a Google search on "Orchestration Services."  You'll find a slew of people willing to do it for you.  For a fee of course.  If you happen to be located in the Pacific Northwest, or know somebody who is, you might try contacting RPM music services in Seattle.  Robert Puff there (the owner) is a very knowledgeable guy, and can help point you in the right direction.

Arranging a piece for full Orchestra


How can I write apps for the latest Sony Ericsson phones?

Question: For me in particular it's about Sony Ericsson W715.
What languages can I use and what environment do I need?
A tutorial recommendation would also be nice.
Answer: They have a developer page..
http://developer.sonyericsson.com
Answer: Your only option would be J2ME. I recommend using Netbeans with the Mobility Pack for the task. Download the Java version, that includes Java ME.
Here is a tutorial on the net. I am sure you can find many more.
Answer: Well, without more information as to what your applications are supposed to do, I would also recommend J2ME, especially given that SonyEricsson has additional useful proprietary APIs that are available to their partners.
You can also target the web browser on the phone by having a server send dynamic HTML and javascript code.
Flash Lite is also an option.
Recent SonyEricsson phones contain the capuchin technology: Write the GUI in Flash and the application engine in J2ME. That could be worth a look, depending on the skills of whoever is working on your applications.
Answer: You should use J2ME (Java Micro Edition).


Why Progressbar color doesn't consistent with my setting?

Question: I want change progressbar to like this:

,and I set its ForgroundColor in xaml:
<code><ProgressBar x:Name="pbTotal2" Margin="5,0,0,0" Foreground="#008BCA" VerticalAlignment="Center" Height="24" Width="800" ></ProgressBar>
</code>
but the result is:

I tried other colors, but the result doesn't change,Anyone can help me to solve this?
Comment: Possible duplicate of [WPF progressbar style](http://stackoverflow.com/questions/4815175/wpf-progressbar-style)
Comment: @ASh,I don't think it's the same, my code doesn't disagree with his, but i can't change the color as expected, how can you explain this?
Comment: the problem is that your picking up the default windows theme, you need to override this either by choosing a simpler style or just styling the correct sub element of the progress bar
Answer: The difference between the two progressbars is not just the foreground color it is the whole style, so you have to write the style you want by your self, see these pages:
https://msdn.microsoft.com/en-us/library/dd334413(v=vs.95).aspx
https://msdn.microsoft.com/en-us/library/ms750638(v=vs.110).aspx
Comment: you need to quote the correct section of the page as links can more or change over time making your answer meaningless
Comment: I just want to change the color,can't i change the foreground only?
Comment: @starkshang the foreground is the font colour only under the theme on your system
Comment: @MikeT, then what attritute should i change?
Comment: @starkshang you need to override the style of the ProgressBarIndicator look at these sections of the link suggested by ASh
Comment: @starkshang or see the whole description in the links i suggested
Comment: @ZORRO_BLANCOZ, thanks for your suggestion, but if i want to change the color,what attritute should i change, What i need to do is define the style with key "MyProgressbar" and use the style on my progressbar with Style={StaticResource MyProgressbar}?
Comment: you are welcome, and you can change the color in the styles that are in the links by changing the LinearGradientBrush you should add only two GradientStop one with offset 0 and the other with offset 1 and same color for both will give you one color for the whole progressbar:


Factorise Algebraic Expression

Question: Background:
I came across the following problem in class and my teacher was unable to help. The problem was factorise $x^6 - 1$, if you used the difference of 2 squares then used the sum and difference of 2 cubes you came out with the following factorisation; $(x-1)(x+1)(x^2 +x + 1)(x^2 - x + 1)$. However if you used the sum and difference of 2 cubes first you factorised to the following; $(x-1)(x+1)(x^4 + x^2 + 1)$. How would I factorise further from there?
Question
How do you factorise $x^4 + x^2 + 1$?
Thanks
Comment: Can you see a path to writing $(x^2+1)^2 - x^2$? Now, just factor  this expression.
Answer: If you plug in $x^2=y$ then you can easily see that its a factor giving two cube roots of unity thus the factors can be given as $(x^2-\omega)(x^2-\omega^2)$
Answer: In such biquadratic expressions it is often useful to complete the square not as usual from the "quadratic" (=degree 4) and "linear" (=degree 2) terms, but from the "quadratic" and constant terms. Thus consider the best of
$$
x^4+1+x^2=(x^2+1)^2-x^2=(x^2-1)^2+3x^2
$$
Another classical example is
$$
x^4+1=(x^2+1)^2-2x^2
$$
Answer: The answer depends very much on the underlying field (or ring).
Over $\mathbb{Z}$ we have
$$
x^6-1=(x^2 + x + 1)(x^2 - x + 1)(x + 1)(x - 1).
$$
Here we can just write
$$
x^4+x^2+1=(x^2+ax+b)(x^2+cx+d),
$$
because there is no linear factor, obviously. Then multiplying out and comparing the coefficients gives the result.
On the other hand, for cyclic codes, a natural choice would be a finite field, e.g., $\mathbb{F}_2$, $\mathbb{F}_3$, or some $\mathbb{F}_q$ for a prime power $q$. We have
$$
x^6-1=(x^2 + x + 1)^2(x + 1)^2
$$
over $\mathbb{F}_2$, and
$$
x^6-1=(x + 2)^3(x + 1)^3
$$
over $\mathbb{F}_3$. This follows by the Berlekamp algorithm, or by elementary division arguments.

Factorise Algebraic Expression


Converting a Vector of Characters to a Vector of Strings in C++

Question: for the following problem, I need to return a vector of strings, where each element in the vector is of length 1. I have an answer that generates a vector of characters. I think it does what I need, but I'm not sure how to return the result as a vector of strings of length one. See my implementation below. Note, I can't change the return type of the function, it must be a vector of strings. Given that I operate on characters in my solution, I'm not sure how I'd change it.
    vector<string> commonChars(vector<string>& A) {
        vector<char> resVec;
        unordered_map<char, int> mapObj;

        for (const auto& str : A) {
            for (const auto& letter : str) {
                mapObj[letter]++;
            }
        }

        int sizeOfInput = A.size();
        for (int i{}; i < A[0].size(); i++) {
            if (!mapObj.count(A[0][i])) continue;
            resVec.insert(resVec.begin(), mapObj[(A[i])] / sizeOfInput, A[i]);
        }
        return resVec;
    }

Comment: Possible duplicate of [Convert a single character to a string?](https://stackoverflow.com/questions/3222572/convert-a-single-character-to-a-string)
Answer: std::vector<char> resVec;
...
std::vector<std::string> returnVec;
returnVec.reserve(resVec.size());
for (char ch : resVec) {
    returnVec.push_back(std::string(1, ch));
    // or: returnVec.emplace_back(1, ch);
}
return returnVec;

Alternatively:
std::vector<char> resVec;
...
std::vector<std::string> returnVec;
returnVec.reserve(resVec.size());
std::transform(resVec.begin(), resVec.end(), std::back_inserter(returnVec),
    [](char ch){ return std::string(1, ch); }
);
return returnVec;

Alternatively:
std::vector<char> resVec;
...
std::vector<std::string> returnVec(resVec.size());
std::transform(resVec.begin(), resVec.end(), returnVec.begin(),
    [](char ch){ return std::string(1, ch); }
);
return returnVec;

That said, you could just eliminate the std::vector<char> altogether and just populate the final std::vector<std::string> directly from the std::map data:
std::vector<std::string> commonChars(std::vector<std::string>& A) {
    std::vector<std::string> resVec;
    std::unordered_map<char, int> mapObj;

    for (const auto& str : A) {
        for (const auto& letter : str) {
            mapObj[letter]++;
        }
    }

    size_t sizeOfInput = A.size();
    if (sizeOfInput > 0) {
        for (const auto& letter : A[0]) {
            auto iter = mapObj.find(letter);
            if (iter != mapObj.end()) {
                resVec.insert(resVec.begin(), iter->second / sizeOfInput, std::string(1, letter));
            }
        }
    }

    return resVec;
}

Answer: vector<string> ret;
for(char ch: resVec)
    ret.push_back(string(1,ch));
return ret;

This is a simple way of converting a std::vector<char> to a std::vector<std::string>.
If you are interested, you can also take a look at: Convert a single character to a string?
In short string(1,ch) is what does the actual conversion.
Answer: There's a different way to approach the problem. You could count the occurrences of each letter a-z in a vector for each string and loop through each vector, adding the minimum number of times a character occurs in all strings:
vector<string> commonChars(vector<string>& A) {
    const int maxTimes=100;
    vector<string> resVec;
    vector<vector<int>> counts;
    counts.reserve(A.size());

    //Count occurrences of letters in each string
    for (const auto& word : A) {
        vector<int> count(26, 0);
        for (const auto letter : word) {
            count[letter-'a']++;
        }
        counts.push_back(count);
    }

    //Add minimum number of times a letter occurs in all strings
    for (int i=0; i<26; ++i)
    {
        int min=maxTimes;
        for (auto &count : counts)
        {
            if (count[i] < min) {
                min = count[i];
            }
        }

        for (int j=0; j<min; ++j) {
            resVec.push_back(string(1, i+'a'));
        }
    }

    return resVec;
}

Note: string(1, i+'a') creates a string of size 1 from a single char (value: i+'a').
Comment: Great answer! Thanks for this.


SignalR hub with Bearer authentication

Question: I have a problem. I have in my API JWT Bearer authentication. I try to use SignalR hub with authentication but it doesn't work for me. I think I tried everything.
I have something like this:
<code>.AddJwtBearer(conf =>
                {
                    conf.RequireHttpsMetadata = false;
                    conf.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(key),
                        ValidateIssuer = false,
                        ValidateAudience = false
                    };
                    conf.Events = new JwtBearerEvents
                    {
                        OnMessageReceived = context =>
                        {
                            // THIS DOESN'T WORK - empty string
                            //var accessToken = context.Request.Query["access_token"];
                            var accessToken2 = context.Request.Headers["Authorization"];
                            // If the request is for our hub...
                            var path = context.HttpContext.Request.Path;
                            if (!string.IsNullOrEmpty(accessToken2) &&
                            (path.StartsWithSegments("/DebateHub")))
                            {
                                // Read the token out of the query string
                                context.Token = accessToken2;
                            }
                           // return Task.CompletedTask;
                           return Task.FromResult<object>(null);
                        }
                    };
                });
</code>
Register hub:
<code> app.UseEndpoints(endpoints =>
        {
            endpoints.MapAreaControllerRoute(
                name: "AreaAdmin",
                areaName: "Admin",
                pattern: "api/admin/{controller}/{action}");

            endpoints.MapAreaControllerRoute(
                name: "AreaMobile",
                areaName: "Mobile",
                pattern: "api/mobile/{controller}/{action}");

            endpoints.MapControllers();
            endpoints.MapHub<DebateHub>("/DebateHub");
            endpoints.MapHub<OnlineCountHub>("/onlinecount");
        });
</code>
Hub code:
<code>[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class DebateHub : Microsoft.AspNetCore.SignalR.Hub
{
    public override Task OnConnectedAsync()
    {
        string name = Context.User.Identity.Name;

        Groups.AddToGroupAsync(Context.ConnectionId, name);

        return base.OnConnectedAsync();
    }
}
</code>
Client example:
<code>var uri = "https://localhost:44275/DebateHub";

var connection = new HubConnectionBuilder()
                     .WithUrl(uri,options =>
                          {
                               options.AccessTokenProvider = () => Task.FromResult("some_token");
                          })
                     .Build();
connection.StartAsync().Wait();
</code>
It doesn't work. I still have unauthorized when I try to connect to my DebateHub. All other controllers work with my authentication ok.
What am I doing wrong?
Comment: Maybe my workaround might help: https://stackoverflow.com/a/77568827/1081100
Answer: I'm not sure but I think that you should use cookies to authorize to hub.
Look here
Comment: Really? I don't think so....
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: You must uncomment this part of your code;
<code>//var accessToken = context.Request.Query["access_token"];
</code>
when hub connection request comes to the server it only sets the token in 'context.Request.Query', as microsoft docs states not in context.Request.Headers["Authorization"].

The query string is used on browsers when connecting with WebSockets and Server-Sent Events due to browser API limitations.

Confirm in chrome network tab request headers to see where it is being sent.
Alternatively you can use this middleware in startup configure method which dose same thing by taking the token from query and setting it where expected to be.
<code> app.Use(async (context, next) =>
        {
            var accessToken = context.Request.Query["access_token"];
            if (!string.IsNullOrEmpty(accessToken))
            {
                context.Request.Headers["Authorization"] = "Bearer " + accessToken;
            }

            await next.Invoke().ConfigureAwait(false);
        });
</code>

SignalR hub with Bearer authentication


Get Metrics for Soft layer resources

Question: We are looking for API on getting disk related metrics of soft-layer something like Read / Write count.
From documentation it looks like using monitoring service we can get them but that's in beta and we need to activate those services
Updated
Here is how GCP provides metric APIs: cloud.google.com/monitoring/api/metrics_gcp#gcp-compute, wanted something on same line.
Answer: Do you refer to metrics similar to the image below?

If so, this is obtained through 2 ways:
1st When placing the order, if you select one of the 3 options displayed the advanced monitoring will be installed and started when provision is completed.

Basic option selected above has at least: Cpu, Disk (if you refer to metrics related to this) and Memory, Monitoring Agent, etc.
2nd If you navigate to https://control.softlayer.com/devices/monitoring
and click on "Add Monitoring" on Advanced column, then you could order this but you will have to install manually the Nimsoft monitoring app. (http://knowledgelayer.softlayer.com/procedure/install-nimsoft-monitoring-robot)
Or if it´s nothing related to what´s above, please update the question with an image attachment of what do you require specifically on the Portal UI.
Comment: Thanks, I'm looking for option 1 but via calling API,
Here is how GCP provides metric APIs : https://cloud.google.com/monitoring/api/metrics_gcp#gcp-compute
Comment: Currently you`ll only be able to get information using the Api, just like you get through the portal UI, please let me know if you still require the Api call as it will retrieve data to be graphed through https://softlayer.github.io/reference/services/SoftLayer_Monitoring_Agent/getGraph/ and return graph data just like the image, take in count that portal doesn´t return metrics like GCP as you could verify through it.

Get Metrics for Soft layer resources


Displaying Profile2 edit page with Panels

Question: I have a profile2 edit page (Drupal 7) found at user/*/edit/main. It has several fields that the user can edit.
As it stands, all the fields are displayed one on top of the other in one column and that makes a rather long list and lots of scrolling.
I would like to list those fields in an (imaginary) table or grid of 2 or 3 columns.
I tried Display Suite, but it's not compatible.
I am trying Panels but I can't get it to work. I use the user profile template of Page Manager (/user/%user.) The variant's selection rule is Path: user/*/edit/main, no context and the "Profile2 from user" relationship.
I have found all my fields and I have organized them in two columns (2 regions side by side) in the panel content.
The variant is enabled but it doesn't work. There is no change whatsoever when I visit the page (all fields still listed in one column.)
Am I doing something wrong or is Profile2 not compatible with Panels (like with Display Suite?)
Any and all suggestions or workaround would be greatly appreciated.
Thanks. :)
Answer: I guess panel and display suite both dont provide this use case. you could use hook_theme and then render function. Example code
   function modulename_theme(){

        return array
        (
                    'user_profile_form' => array
            (
                'render element' => 'form'
            ),
        );
    }
function theme_user_register_form($variables){
    $form = $variables['form'];
    $output='
';
    if(isset($form['profile_main'])){
     $output.= drupal_render($form['profile_main']['field_profile_main_fname']);
     $output.=  drupal_render($form['profile_main']['field_profile_main_lname']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_phone']);

}
    $output.="
";
$output='
';
if(isset($form['profile_main'])){
    $output.= drupal_render( $form['profile_main']['field_profile_main_gender']);
     $output.= drupal_render( $form['profile_main']['field_profile_main_dob']);
 }
}
    $output.="
";
    $output.= drupal_render_children( $form);
    return $output;
}

Then on css you could add float left and width on divs to make it 2 columns
Answer: Have you checked https://www.drupal.org/project/profile2_panels?
It claims to do exactly what you need


How to disable websockets support in Firefox?

Question: I set network.websocket.enabled to false in about:config.
But when I access the following URL
https://www.aging-us.com/article/102435
a websocket request like the following is still used as shown in the developer tools.
wss://www.aging-us.com/sockjs/829/febrfdll/websocket
What is the correct way to disable websocket in Firefox? Thanks.
Comment: Can you try `network.websocket.max-connextions` per https://stackoverflow.com/q/45963495
Answer: There is no preference network.websocket.enabled in the code, as far as I can see. And there doesn't seem to be any way to completely disable WebSockets, unfortunately.
There was an enhancement request for allowing to temporarily disable certain features via the DevTools, though it got closed due to technical limitations in the engine to do that.
A workaround for that might be to set the preference network.websocket.max-connections in about:config to 0. That doesn't disable the feature completely, though at least suppresses any WebSocket connections.


VBA UserForm Listview control - mouse click coordinates and positioning

Question: VBA userforms, and listviews in particular, are tricky when it comes to spatial distances and coordinates. The question I am trying to solve is: the mousedown event gives the coordinates in pixles - how do I transform that into the units required for repositioning another user control and also incorporate the width property of user controls.
To give the very specific problem:
I have a listview with multiple columns and a horizontal scroll bar. I want to get the selected row and column of the mouse click and then reposition a frame to the point at which the mouse was clicked.
Googling only came up with partial answers - nothing solving the full problem.
Answer: There are three different units of measurement. Pixels, twips and imperial points.

Converting between twips and imperial points is easy - 1 imperial
point is 20 twips.
Converting between pixels and twips is harder -
though many solutions are easily googleable. It is dependant on the
pixel density of your screen.

Once you have gotten your functions/subs down to convert between pixels, twips and imperial points, you can then use the correct coordinate units for each different task:

MouseDown event gives the coordinates in pixels.
HitTest (the listview function to return the selected row -
although not the selected column) takes coordinates in twips.
Column widths and all other user control widths are in imperial
point.
GetScrollPos (the Windows API function to return the scrollbar
position) gives a value in pixels.
Repositioning user controls on the userform takes imperial points.


timidity on Linux produces scratches

Question: I'm using the tool timidity to convert MIDI files to WAV using the timidity file.mid -Ow command. Unfortunately, the output wav file has a scratch sound at the beginning, e.g.

Short of installing a low-latency kernel on my machine, is there a simpler method to avoid those scratches?
(Edit: removed scratchy sound file from SoundCloud)
Comment: I don't have the link nor do I remember how to find it, but this is actually due to a bug in Timidity. There is patched version available somewhere or you can compile the latest version yourself. If I can find that information I'll update with an actual answer but maybe this can help you on your way in the meantime.
Comment: I had a similar problem that was affected by setting the bit-depth on the command line; but I don't remember the details maybe one of the `--output-24bit` flags or similar.
Comment: If you have an "unreasonable" scratch sound at the beginning, as a workaround maybe you could insert a few dummy notes and then a second of _complete silence_ at the beginning in your MIDI file, which you would strip in a wave editor (like Audacity).
Comment: Thanks @bfootdav! I compiled the source for timidity 2.14.0 and it removed the scratches. Problem solved :-)
Answer: Compiling the latest version of TiMidity++ (version 2.14.0) solved the problem for me. Thanks @bfootdav for the hint!
Answer: The easy remedy while the fix makes it into Ubuntu (can't even see it upstream?!?) is to call it as
timidity --output-24bit

I haven't figured out a way how to do this in timidity.cfg though.
Comment: As of Oct 2020, this problem is still there in version 2.13.2 from Ubuntu 18.04. Using `timidity m.midi -Ow -o m.wav`, my .wav file was generated with bad scratching near the beginning. With `timidity m.midi --output-24bit -Ow -o m24.wav` it sounds great. The workaround in this answer is still needed.
Answer: timidity -Ow is not running in realtime, so a low-latency kernel will not make a difference.  There is actually little sense in that noise: either something in your processing chain is expecting raw input and misinterpreting the wav header, or your sound fonts have problems: try installing and configuring a different set (I think there are several).  However, the music sounds as if it were having identical repeats (does it?) in which case it would make little sense if the noise occured only at the start.
So all in all, I can't really produce a sensible interpretation of your described results.  Maybe the description is missing something, and maybe my ideas will help you figuring out something.  I do seem to remember that I had similar noise problems with some music and changing the sound fonts (to "freepats" or the other way round) cured it.

timidity on Linux produces scratches


my ajax request call back whole code page

Question: i just wanna save with button in laravel but when use console log i get whole code in console idk why this happened?
this is my input and button
<form action="{{ url('sendcom') }}" method="post">
                    @csrf
                    <input type="text" id="editor" name="Name">
                    <button type="submit" id="btn" name="submit" value="Submit">
                    submit
                    </button>

                </form>

and i use ajax like this:

and i get it in controller like this :
public function sendcom(Request $request)
    {
        if($request->ajax()){

            $content = $request->data;

            User::updateOrCreate([
                'contract' => $content
            ]);

            return response(['success' => 'contract save success.']);
        }
    }

but when i click on submit button it's get me whole page code
and I don't know where I went wrong
Comment: `$("#btn").click(function(e){
    e.preventDefault()` I don't know if that will stop a form posting - usually, one uses the `submit` event to do what you want
Comment: _"i get whole code in console"_ - What code? Please be more specific. Show us what you actually get (or at least a snippet of it so we can understand it better)
Comment: Exactly all the source code show in console when i click on submit `

` firstname.lastname@example.com
Answer: The response keyword here is actually an instance of Illuminate\Http\Response which can be seen here in the docs. What ajax here is expecting is a JSON response which will, as the name implies, be consumed as a javascript object.
The line:
return response(['success' => 'contract save success.']);

Should be changed to:
return json_encode(['success' => 'contract save success.']);

which will create a new json object to be returned back. We can then access this with res.success to get the message.


GruntJS erro na instalação do plugin usando Vagrant

Question: Tento instalar o puglin

npm install grunt-contrib-uglify --save-dev

no meu projeto usando vagrant e dá erro de permissão segue abaixo :
npm ERR! Please try running this command again as root/Administrator.
npm ERR! Linux 3.13.0-61-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "grunt-contrib-     uglify" "--save-dev"
npm ERR! node v0.12.7
npm ERR! npm  v2.11.3
npm ERR! path npm-debug.log.4d84521811f489f4938c27a69db45fbf
npm ERR! code ETXTBSY
npm ERR! errno -26

npm ERR! ETXTBSY, rename 'npm-debug.log.4d84521811f489f4938c27a69db45fbf'
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     /vagrant/angular-grunt/npm-debug.log

Answer: Voce tem que rodar o comando como root ou usar sudo:
sudo npm install grunt-contrib-uglify --save-dev

Comment: já utiizo o SUDO e mesmo assim não funciona
Comment: Qual erro você tem quando utiliza o sudo?
Comment: o mesmo que reportei :|
Comment: Voce tentou como usuario root? E' estranho voce ter o mesmo erro com sudo....
Comment: eu não sei se é pq to usando vagrant


Wanna save text_format custom form in comment

Question: I'm using a custom form in CTools Modal to alter comment.
$form['subject'] = array(
   '#type' => 'textfield',
   '#title' => t('Title'),
   '#default_value' => $comment->subject,
);
$form['comment_body'] = array(
   '#type' => 'text_format',
   '#default_value' => $comment->comment_body['und'][0]['value']
);

All is good. I get my comment title and my comment body which is pushed in ckeditor field. My submit :
$comment = comment_load($form_state['values']['cid']);
$comment->comment_body['und'][0]['value'] = $form_state['values']['comment_body']['und'][0]['value'];
$comment->subject = $form_state['values']['title'];

comment_submit($comment);
comment_save($comment);

The subject is goodly saved from my form but for the body, it save an empty value.
Ps: when I change text_format for textfield, it work.
Answer: You forgot to add the format:
$comment->comment_body[LANGUAGE_NONE][0]['format'] = $form_state['values']['comment_body'][LANGUAGE_NONE][0]['format'];

Comment: Even with this line, it save me an empty value.
Maybe something to know, when in my validate I put a `form_set_error` in `$form_state['values']['comment_body'] == ''` it doesn't pass even if i let the comment input form empty.
Comment: And you've confirmed that the form state array contains the elements you're trying to access?
Comment: Haha, your comment gave me an illumination : it was `$form_state['values']['comment_body']['value']` missed this final _value_ so, in the submit it looks like : `$comment->comment_body['und'][0]['value'] = $form_state['values']['comment_body']['value'];` (same thing for format). Thanks you @Clive


Python remover() list index out of range

Question: def gera_huffman(simbolosOriginal, probabilidadesOriginal):
# gera_huffman(['a', 'b','c', 'd'], [5, 2, 1, 2])

    simbolos = simbolosOriginal
    probabilidades = probabilidadesOriginal

    lista = []

    while (len(simbolos) > 2):

        ordem = np.sort(probabilidades)
        ordemIndex = np.argsort(probabilidades)

        novaProbabilidades = ordem[0]+ordem[1]
        novoSimbolo = simbolos[ordemIndex[1]] + simbolos[ordemIndex[0]]

        print novaProbabilidades , novoSimbolo, simbolosOriginal[ordemIndex[0]],simbolosOriginal[ordemIndex[1]]
        print simbolos
        simbolos.remove(simbolosOriginal[ordemIndex[0]])

        print simbolos
        simbolos.remove(simbolosOriginal[ordemIndex[1]])

        print simbolos

        probabilidades.remove(probabilidadesOriginal[ordemIndex[0]])
        probabilidades.remove(probabilidadesOriginal[ordemIndex[1]])

        probabilidades.append(novaProbabilidades)
        simbolos.append(novoSimbolo)
        print simbolos

        simbolosOriginal = simbolos
        probabilidadesOriginal = probabilidades

        if(len(simbolos) <= 2):
           lista.append([simbolos, probabilidades])
           lista.sort(reverse = True)
           return lista

Erro: simbolos.remove(simbolosOriginal[ordemIndex[1]])
  IndexError: list index out of range

Nos vários prints que estou a efectuar na lista simbolos, no momento antes do erro estou a obter:
simbolosOriginal[ordemIndex[0]]= 'd'
simbolosOriginal[ordemIndex[1]] = 'bc'

A lista simbolos é ['a', 'bc'].
Sendo que no print simbolosOriginal[ordemIndex[1]] tem o valor 'bc' e ele está na lista não compreendo porque motivo ele diz que o index está out of range.
Como posso arrumar isso?
Answer: Se eu fosse desenvolver o algoritmo de Huffman em python eu não faria dessa maneira, mas sem entrar nesse mérito, alterei ligeiramente o seu código para evidenciar seu erro. Veja:
import numpy as np

def gera_huffman(simbolosOriginal, probabilidadesOriginal):
# gera_huffman(['a', 'b','c', 'd'], [5, 2, 1, 2])

    simbolos = simbolosOriginal
    probabilidades = probabilidadesOriginal

    lista = []

    while (len(simbolos) > 2):

        ordem = np.sort(probabilidades)
        ordemIndex = np.argsort(probabilidades)

        novaProbabilidades = ordem[0]+ordem[1]
        novoSimbolo = simbolos[ordemIndex[1]] + simbolos[ordemIndex[0]]

        print ('\nlen atual de simbolos: ',len(simbolos) )

        # print (novaProbabilidades , novoSimbolo, simbolosOriginal[ordemIndex[0]],simbolosOriginal[ordemIndex[1]])

        print ('\nSimbolos antes da remoção: \n', simbolos)
        simbolos.remove(simbolosOriginal[ordemIndex[0]])
        print ('\nsimbolos depois da primeira remoção: \n', simbolos  )

        print ('\nA expressão abaixo:')
        print ('simbolos.remove(simbolosOriginal[ordemIndex[1]])')
        print ('Resulta em:')
        print ('simbolos.remove(simbolosOriginal[',ordemIndex[1],']')

        print ('\nA Proxima linha tenta remover algo que existe? Lembrando que:')
        print ('simbolosOriginal é = ', simbolosOriginal)
        print ('ordemIndex[1] é = ', ordemIndex[1])

        simbolos.remove(simbolosOriginal[ordemIndex[1]])
        print ('\nSimbolos depois da segunda remoção remoção: \n',simbolos)

        probabilidades.remove(probabilidadesOriginal[ordemIndex[0]])
        probabilidades.remove(probabilidadesOriginal[ordemIndex[1]])

        probabilidades.append(novaProbabilidades)
        simbolos.append(novoSimbolo)

        print ('\n Simbolos apos o append: \n', simbolos)

        simbolosOriginal = simbolos
        probabilidadesOriginal = probabilidades

        if(len(simbolos) <= 2):
           lista.append([simbolos, probabilidades])
           lista.sort(reverse = True)
           return lista

Tentei explicar o erro no própria codificação, reproduzo o resultado abaixo. Clique aqui para ver a execução e o resultado do códido.
len atual de simbolos:  4

Simbolos antes da remoção:
 ['a', 'b', 'c', 'd']

simbolos depois da primeira remoção:
 ['a', 'b', 'd']

A expressão abaixo:
simbolos.remove(simbolosOriginal[ordemIndex[1]])
Resulta em:
simbolos.remove(simbolosOriginal[ 1 ]

A Proxima linha tenta remover algo que existe? Lembrando que:
simbolosOriginal é =  ['a', 'b', 'd']
ordemIndex[1] é =  1

Simbolos depois da segunda remoção remoção:
 ['a', 'd']

Simbolos apos o append:
 ['a', 'd', 'bc']

len atual de simbolos:  3

Simbolos antes da remoção:
 ['a', 'd', 'bc']

simbolos depois da primeira remoção:
 ['a', 'bc']

A expressão abaixo:
simbolos.remove(simbolosOriginal[ordemIndex[1]])
Resulta em:
simbolos.remove(simbolosOriginal[ 2 ])

A Proxima linha tenta remover algo que existe? Lembrando que:
simbolosOriginal é =  ['a', 'bc']
ordemIndex[1] é =  2

Note que o codigo tenta remover um elemento fazendo referencia na lista simbolosOriginal, utilizando o indice 2, mas nesse tempo a lista é =   ['a', 'bc'], isto é, só tem 2 elementos, como o python inicia os indices de listas em 0 (zero), voce só poderia remover com os indices 0 e 1.
DEMO


Big Oh Approximation of a Function

Question: I am learnign the big Oh notation and still very weak at approximating a function by the notation. In this particular example, I am looking for verification of my solution about approximating a function using the big Oh notation. Could you please let me know if the way I did is correct? Furtheremore, if there are any intermediate steps that are not 'refined', please help me correct them. Finally, please feel free to let me know how my solution can be improved.
Let:
$$
f(x) = \frac{1+x-e^x}{x^2}
$$
Then $\lim_{x \to 0}f(x) = -\frac{1}{2}$.
Using Taylor approximation for $e^x$, then:
$$
f(x)=\frac{\frac{-x^2}{2!}-\frac{x^3}{3!}-\frac{x^4}{4!}...}{x^2}=\frac{-1}{2!}-\frac{x}{3!}-\frac{x^2}{4!}...
$$
So,
$$
|f(x)-\frac{1}{2}|=|-\frac{x}{3!}-\frac{x^2}{4!}-...-\frac{1}{4}|\leq |\frac{x}{3!}|+|\frac{x^2}{4!}|+...+\frac{1}{4}\leq|\frac{x}{3!}|+|\frac{x}{3!}|+...+\frac{1}{4}=O(x)+O(x)+O(x)+...+O(x)=O(x) \text{, as x $\to 0$}
$$
Therefore,
$$
f(x)=\frac{1+x-e^x}{x^2}=-\frac{1}{2} + O(x)
$$
Comment: Well done! Correct solution.
Answer: The solution is partially incorrect, and reveals a fundamental error in the handling of $O$-functions. That's why this post is more about showing that error and less about the actual correct argument (which can be found at the end).
The problem occurs when you estimate $|f(x)-{1\over 2}|$ (which should be $|f(x)+{1\over 2}|$, btw., plus there are some more clerical errors in that line).
You correctly get
$$\left|f(x)+{1\over 2}\right| \le \left|\frac{x}{3!}\right| + \left|\frac{x^2}{4!}\right| + \left|\frac{x^3}{5!}\right|+\ldots$$
And you are right that $\left|\frac{x}{3!}\right| \in O(x)$, $\left|\frac{x^2}{4!}\right| \in O(x)$, a.s.o.
But when you are summing up an infinite number of $O(x)$-functions, the sum is no longer guaranteed to be $O(x)$!
To see an example, consider first the following function $g(x)$ defined for $x \in (0,1)$:
$$g(x)=\frac1n, \text{ where $n$ is the unique integer satisfying } \frac1{n+1} \le x < \frac1n$$
It's easy to see that $g(x) < 2x$, because $\forall n \ge 1: \frac2{n+1} \ge \frac1n$.
Now consider the following functions $f_k(x)$, $k\ge 1$ defined for $x \in (0,1)$:
$$f_k(x)=
\begin{cases}
  g(x) & \text{, if } g(x) \le \frac1k\\
  0    & \text{, otherwise.}
\end{cases}
$$
Clearly $f_k(x) \in O(x)$, as $\forall x: f_k (x) < 2x$.
But if you sum up those functions,
$$f(x)=\sum_{k=1}^\infty f_k(x)$$
you'll find that $\forall x:f(x) = 1$. That's because if $g(x)=\frac1n$, we have $f_k(x)=\frac1n$ for $1 \le k \le n$ and $f_k(x)=0$ for $k > n$. So the infinite sum is $n$ terms $\frac1n$ and otherwise $0$.
So clearly $f(x) \notin O(x).$
When you go to infinite or an unlimited number of summands, each part can be 'small' ($O(x)$), but because you get as many summands as you want, these samll contributions can become 'big' (not $O(x)$).
Another way to see this is looking at the definition for $O(x)$. $f(x) \in O(x)$ means there exists some number $M$ such that
$$|f(x)| \le M|x|$$
for $|x|$ 'small enough', that means $|x| < m$ for some $m > 0$.
If you have another function $g(x) \in O(x)$ with $|g(x)| \le N|x|$ for $|x| < n, (n > 0)$ , you get that
$$|f(x)+g(x)| \le |f(x)|+|g(x)| \le M|x| + N|x| = (M+N)|x|$$
for all $x$ that fit both $f$'s and $g$'s definition of 'small enough', that means $|x| < \min(m,n)$.
That's (roughly) the usual proof that the sum of 2 $O$-functions is itself a $O$-function. This proof can be easily expanded to the sum of any finite number of functions, as then the comparison constants ($M,N,\ldots$) get added and can become big, but stay finite and from all the 'small enough' constats ($m,n,\ldots$), the minimum is taken, which is still a small but positve number.
However, whith an infinite sum the argument breaks down on two fronts. First, the sum of $M,N,\ldots$ can get infinite. That's what happened in my example. Also the minimum (infimum) of $m,n,\ldots$ can be become $0$, so any resulting inequality would only apply to $0$, which makes it trivial/useless.
So I hope I could demonstrate that adding an infinte number of $O$-functions may not necessarily be a $O$-function itself.

Let's come back to your problem to prove that in the given case the sum actually is $O(x)$.
Recall
$$\left|f(x)+{1\over 2}\right| \le \left|\frac{x}{3!}\right| + \left|\frac{x^2}{4!}\right| + \left|\frac{x^3}{5!}\right|+\ldots$$
and we have
$$\left|\frac{x}{3!}\right| + \left|\frac{x^2}{4!}\right| + \left|\frac{x^3}{5!}\right|+\ldots = |x|\left(\left|\frac{1}{3!}\right| + \left|\frac{x}{4!}\right| + \left|\frac{x^2}{5!}\right|+\ldots\right)$$
and because we consider $x \to 0$, we can assume $|x| \le 1$ and we have
$$\left|\frac{1}{3!}\right| + \left|\frac{x}{4!}\right| + \left|\frac{x^2}{5!}\right|+\ldots \le \left|\frac{1}{3!}\right| + \left|\frac{1}{4!}\right| + \left|\frac{1}{5!}\right|+\ldots = e-1-1-\frac12$$
That proves finally
$$\left|f(x)+{1\over 2}\right| \le |x|(e-2.5)$$
for $|x| \le 1$, which implies $f(x)+{1\over 2} \in O(x)$ for $x\to 0$.

Big Oh Approximation of a Function


Proof that if $f(x)$ is continuous on $[a,b]$ it is uniformly continuous on $[a,b]$

Question: My textbook gave a proof by contradiction of the following theorem:
Theorem: If $f(x)$ is a real-valued function that is continuous on $[a,b]$ then it is uniformly continuous on $[a,b]$
The proof by contradiction seemed overly complex and indirect. Was wondering if the following direct proof is valid.
Direct proof of Theorem
Since $f(x)$ is continuous on $[a,b]$ then for any $\epsilon > 0$ and $y,x \in [a,b],\; \exists \delta_x(\epsilon)>0 $ such that $|y-x|<\delta_x(\epsilon) \implies |f(y)-f(x)|< \epsilon$.
Letting $\delta(\epsilon) := \min_{x \in [a,b]} \delta_x(\epsilon)$ Then for each $\epsilon > 0$ and $x,y \in [a,b]$, we have $|x-y|<\delta(\epsilon) \leq \delta_x(\epsilon) \implies |f(x)-f(y)|< \epsilon\;\square$
This seems pretty direct to me and was wondering if I am missing something in this proof.
EDIT: As the great answers and comments have shown, my mistake/challenge is due to the ill-defined $\delta_x(\epsilon)$ function. I was assuming there was some (undefined) process that would select a finite positive number for each $\delta_x(\epsilon)$, but I did not specify it. I also rely on the continuity of $\delta_x(\epsilon)$ and that is not assured or proved.
Comment: Your $\delta(\epsilon)$ may be $0$.
Comment: @geetha290krm thanks! yes, what I had in my head and what I wrote were not the same -- I've updated it to better show my actual intent.
Comment: See https://math.stackexchange.com/questions/110573/continuous-mapping-on-a-compact-metric-space-is-uniformly-continuous#:~:text=The%20answer%20is%20yes%2C%20if,%2Cf(x)). If you are not familiar with metric spaces, replace $d(x,y)$ for $|x-y|$
Answer: The problem is in the argument that $\delta(\epsilon)$ exists because the minimum exists. Here, you are using a theorem that says that a minimum of a continuous function over a compact set always exists.
However, you don't have any reason to believe that the function $x\mapsto \delta_x(\epsilon)$ is continuous, so the argument is incorrect.
Comment: @User5678 Also, "The minimum is in the delta of a delta-epsilon definition of continuity" is a pretty hand-wavy sentence, now that I think about it. Consider writing it in a more precise manner, currently it's so vague I don't really understand what you wanted to say with it.
Comment: @User5678 But there is more than one viable $\delta$ for each $\epsilon$. And for each $\epsilon$, the infimum of all $\delta$ values that can satisfy the inequality is actually $0$, because whenever $\delta$ is viable, then $\frac\delta2$ is also viable.
Comment: From continuity of $f(x)$ on $[a,b]$ why doesn't the minimum $\delta$ exist ? The minimum is in the delta of a delta-epsilon definition of continuity.
Comment: What I meant to say is that since the function $f$ is continuous on a closed interval, it then for every $x,y \in [a,b]$ and $\epsilon > 0$ we can find a $\delta_x(\epsilon) > 0$ such that $|x-y| < \delta_x(\epsilon) \implies |f(x)-f(y)| < \epsilon$. I did correct my earlier statement to use $\inf$ vs $\min$ as you correctly pointed out there is no reason that the $\delta_x$ needs to be continuous in $x$.  I also corrected for your above comment that we can take arbitrarily small $\delta$ (I was picturing the largest such $\delta$ for each $x$ and $\epsilon$, so I made that explicit).
Comment: This was a great answer as well! +1 thank you :)
Comment: @User5678 The problem with taking the largest $\delta$ for each $x$ is that in that case, the function might not be infinite, or even well defined. For example, take any constant function $f$. Then, for any $\epsilon$, you can literally take **any** $\delta$, and the statement $|x-y|<\delta\implies |f(x)-f(y)|<\epsilon$ will be true (because $|f(x)-f(y)|$ will always be $0$.
Comment: makes sense to me
Answer: There are numerous problems with this approach:

You are defining a function $\delta$ which depends on $x$ and $\varepsilon$—in your notation, $\delta_x(\varepsilon)$.  However, it is not clear that this function is well-defined.  For example, if $f(x) = C$ is a constant function on $[a,b]$, then it is possible to take $\delta_x(\varepsilon)$ to be any positive value you like for any $x \in [a,b]$.  You are going to have similar problems for any assignment of $\delta_x(\varepsilon)$:  if $\delta$ gets the job done for some particular choice of $x$ and $\varepsilon$, then $\delta/2$ will also get the job done.
How do you choose $\delta_x(\varepsilon)$?

You are attempting to invoke a version of the Extreme Value Theorem, which states

If $g : [a,b] \to \mathbb{R}$ is continuous, then there are $c, d \in [a,b]$ such that
$$ g(c) \le g(x) \le g(d)$$
for all $x \in [a,b]$.

That is, continuous functions on closed, bounded (i.e. compact) domains attain their extreme values.  But, as noted above, you have no control over the choice $\delta_x(\varepsilon)$, which means that you have no control on whether or not $\delta_x(\varepsilon)$ is a continuous function of $x$.
For a rather extreme example, suppose that $f : [a,b] \to \mathbb{R} : x\mapsto C$ is constant function.  Then for any $\varepsilon > 0$, any $\delta > 0$, and any $x\in [a,b]$, it will follow that if $y\in [a,b]$, then
$$ |x-y| < \delta \implies |f(x) - f(y)| = 0 < \varepsilon. $$
So, for example, I could define
$$ \delta_x(\varepsilon) = \begin{cases}
\dfrac{1}{p} & \text{if $x = \frac{p}{q} \in \mathbb{Q} \cap [a,b]$ and $\gcd(p,q)=1$, and} \\[1ex]
1 & \text{if $x \not\in\mathbb{Q} \cap [a,b]$.}
\end{cases} $$
(If $0 \in [a,b]$, adopt some convention regarding the assignment of $\delta_0(\varepsilon)$).  This function does not attain a minimum on the interval $[a,b]$.
How do you know that it is possible to choose $\delta_x(\varepsilon)$ so that it is a continuous function of $x$?
Comment: Again, how do you get *any* control over $\delta_x$, as a function of $x$?  What theorem or result can you invoke which guarantees that you will get a positive lower bound?  If you want a direct proof, I would suggest that you focus not on the Extreme Value Theorem, but on compactness:  The open intervals $\{ (x-\delta_x, x+\delta_x) : x \in [a,b] \}$ form an open cover of $[a,b]$.  The interval $[a,b]$ is compact, so you can extract a finite subcover $\{ (x_n - \delta_{x_n}, x_n + \delta_{x_n} \}$.  Take $\delta = \min_{n} \delta_{x_n}$.
Comment: @nicoyanovsky Indeed.  I threw that out that as a quicky, without thinking about it too hard.  Even taking half the minimal $\delta$ doesn't seem to quite work.  Rather, the best option might be to take something akin to $\delta = \frac{1}{2} \min |x_n - x_m|$, taken over all $n,m$.  In any event, I don't intended for my comments to be a complete answer---rather, a direct proof should probably make use of compactness in this way, with the details "left to the reader".
Comment: Thanks for your thoughtful critique -- I have noted that the use of "min" was problematic and moved to inf. However, that was still problematic b/c, as you and @5xum pointed out, you can chose arbitrarily small values of $\delta$ so it is not well defined. I've attempted to fix this by looking at the *largest* such delta for each $x,\epsilon$, which I think surely exists due to the assumed continuity of $f$, right? Still not sure its right and I've learned a ton from your and 5xum's responses :) +1
Comment: @User5678 I genuinely think that there is no way of patching up your approach.  You simply don't have enough control over the value of $\delta_x$.
Comment: i see -- so the issue is that even though we know we can chose a finite $\delta_x$ for each $x,\epsilon$ that doesn't guarantee that $\delta_x$ is bounded for any given $\epsilon$? maybe I was being too complex and all I need to use is that the continuity of $f$ implies that I can assign a finite $\delta$ to each $x$ for every choice of $\epsilon$, hence the supremum is bounded over $[a,b]$ and then uniform continuity follows?
Comment: so what you did is use compactness to force the (arbitrary) choice of $\delta_x$ down to a finite set and hence one that has a minimum. That is a great suggestion! Thank you. I see my mistake(s) clearly now -- I was trying to get $\delta_x$ to be selected by an undefined choice function over an uncountable set, whereas you were able to sidestep that by constructing a finite set from compactness.
Comment: just for clarity -- does the supremum exist for each set of valid values $\delta_x(\epsilon)$?
Comment: Xander henderson, tanking just min doesnt work. You need $\delta = \min \{\dfrac{\delta_{xi}}{2}\}$ to guarantee than whenever you take $x,y$ such that $|x-y| < \delta$ then both $x$ and $y$ lie on some $(x-\delta_{xi}, x+\delta{xi})$


How to list out Flag content User in event page in Drupal Commons

Question: I tried to create the equivalent of the RSVP module (for which no D7 version exists ...) in combination with Drupal commons. But I didn't succeed in that.
So I then decided to use the Flag module, and created a flag for Participant Flag (Participant/Maybe/No) using the answer to my question about "How to implement RSVP Functionality?".
The implementation of the Flag for this is OK, but my next question now is "How to get the exact list of Participants, with some User details?". Some of the User details I want to get included in the list are:

User Name
User Picture

Assume that user A will attended a "Sample event" and user C will not attended that event. Also assume that user B will maybe attended that event.
How to create these 3 lists, for each of the 3 flags I am using (1 flag for each of these lists):

Participant List
Not attended List
Maybe Attended list

Anybody any suggestions?
Answer: Create a head count for each flag
Refer to listing flagged content with Views for a tutorial about creating a view with flagged content.
Starting from around 6:55 (and up to around 12:05) it explains How to create a view showing flagged content. Before 6:55 it mostly shows how to create that "Sidebar" flag (skip that part if you know that already). Here are the relevant steps in it (that you want to pay special attention to):

Even though the video uses a "global flag", your case is NOT a global flag (i.e. each user can flag/unflag, not just a restricted list of users, such as those with "administrators" or "content editors" role).
The tutorial creates a view of type "block", but you probably want to create a view of type "page" (though a "block" might be sufficient also if you prefer).
Within the "Advanced" link of the Views UI, you must add a "relationship" (think of an SQL "join" if you're not familiar with Views). To add such relationship, enter "Flag" as the "filter" on the popup window (as shown in the video around 8:25). You'll then get a shortlist of about 7 possible relationships to select from. Your question doesn't say (yet) if the flags you use apply to "nodes" or to "users", but I'm about sure (and going to assume) you'll be using "nodes". So use Flags: node flag counter as relationship. You might possibly also be able to use the Flags: node flag relationship instead (which is NOT shown in the video here), because the Flags: node flag relationship brings in more data about the flagging event, such as "who flagged it, when, etc".
As shown/mentioned from around 10:20 in the video, this video is about a "global flag". If it would have been about a none-global flag, then it would count the people who have used the "flag". So with only that, you already have like a "head count" of people who have "set the flag". Something like "number of attendees" already?
After you finish the first view for (say) the first flag, then repeat what is above by cloning that first view into a 2nd (and 3rd) view, and then adapt the 2nd view to use the 2nd (and 3rd) flag, to build a similar list.
As shown/mentioned from around 11:00 in the video (up to around 12:05), if you've selected to create a view of type "block" (not a "page"), then you still have to position the block (created by the view(s)) in an appropriate theme region.

Add more details about the flagging user
Refer to Getting the flagging user into Views for a tutorial about how to add more details about the flagging user (starting from around 2:00, though the real "Views" related part starts from about 4:00). Here are the relevant steps in it (that you want to pay special attention to):

This is about creating a view op type "page" (not block), which is also what you probably want, in the format of a simple tabular display.
The "path" where this view will be shown (around 4:40), like user/%/friends, which in your case I'd suggest something to become like user/%/events.
The "menu tab" that will be created (around 5:10), like Friends, which in your case I'd suggest something to become like Events.
The 2 (not just one ...) relationships that get added here, i.e.: Flags: User Flag (around 5:40) and Flags: User, which is The user that flagged an item (around 6:55)
Note the "contextual filter" that gets added (around 7:40, up to around 9:00), i.e.: User: Uid. It's to answer questions like "what are the events that this user confirmed to be attending so far".
Starting from about 9:10, the actual user details (such as User: Name) get added.

Starting from around 9:45, you get like a summary of it all, i.e.:

Start from a user profile (such as user/1) and use the (new) tab Friends.
A recap of the "crucial part" of this view, i.e. the 2 relationships that this view is using.
Comment: Thanks @Pierre.Vriens..Nice Tutorial.. I refer that Video tutorial but i need to get user details like Username , user Picture just like attendance how to achieved it..is it possible?
Comment: Let me try this concept and update you @Pierre.Vriens.
Comment: Here i just want to know your opinion for this [question](http://drupal.stackexchange.com/questions/169699/how-to-send-bulk-private-message-internal-message-system-in-drupal). Kindly give some idea for this...


Is "in fact" a typical phrase to introduce a quick proof of a claim in mathematics?

Question: One of my mathematics professors, a German native, frequently makes small claims in his lecture notes, which he then justifies in the following sentence, which always begins "In fact, ...".
I was wondering if this is a typical construction in mathematics, as it seems at odds with normal usage of "in fact" in English (i.e., usually to introduce a similar, but stronger point).
I have the impression that this is a mistranslation of the German phrase "in der Tat", which (I believe) is used for this purpose in German mathematics. But I could be wrong.
Example:

The scalar product is Lipschitz on each ball of $X^2$ and thus continuous from $X^2$ to $\mathbb{F}$. In fact, Cauchy-Schwarz yields ...
[inequality demonstrating Lipschitz].
Comment: In my experience, it is usually used to emphasise a point by stating something stronger which implies the result. Example: "$f$ is continuous. In fact, $f$ is differentiable...."
Comment: Instead of "in der Tat" I assume he actually means "und zwar" or "Und tatsächlich" what could be translated into english as "Indeed" … so it's more like "The scalar product is Lipschitz on each ball of $X^2$ and thus continuous from $X^2$ to $\mathbb{F}$. Indeed, Cauchy-Schwarz yields ..."
Comment: I don't know the German. The usage you quote isn't wrong, but it's a little misleading. @Joppy 's comment is what I was about to write.
Answer: Pulling down @Joppy's comment from above.

In my experience, it is usually used to emphasise a point by stating something stronger which implies the result. Example: "$f$ is continuous. In fact, $f$ is differentiable...."


Pointers keeping information throughout function calls

Question: I am a bit confused by what is happening with my pointers between function calls.  It is not what I would expect.  I have the following situation:
SomeClass *p1= 0, *p2 = 0;
SomeMethod(p1, p2);
printf("P1 total: %d\n", p1->total); // crashes
printf("P2 total: %d\n", p2->total); // crashes

// method someMethod, where the values of the pointers are valid
void SomeMethod(SomeClass *p1, SomeClass *p2)
{
    someMethodThatModifiesThePointers(&p1, &p2);
    printf("P1 total: %d\n", p1->total); // prints valid value
    printf("P2 total: %d\n", p2->total); // prints valid value
};

As you can see from my comments, the pointer's .total property (an integer) is valid inside of the method, but is no longer valid outside of it.  Why is this the case?  The pointers shouldn't be losing scope.
To be exact, someMethodThatModifiesThePointers() is opencv's cvExtractSURF.  I pulled away code to keep it simple.
Answer: C is a pass-by-value language.  That means that the pointers in your original function cannot be changed by the call to SomeMethod() (C doesn't have methods, by the way).  You're crashing on the commented lines because p1 and p2 are still null pointers at that time.
The same goes for the pointers inside SomeMethod().  Your lines comented prints valid value will crash for the same reason if you pass null pointers to SomeMethod().  It's impossible for you to be getting the output you say you are, at least given the code you've shown.  If you made a mistake in your example, and you meant this line to be:
    someMethodThatModifiesThePointers(&p1, &p2);

It could be working the way you explain - p1 and p2 are then being passed by reference (that is, you are passing a pointer-to-a-pointer by value), and their values could be valid inside SomeMethod().  The original copies of p1 and p2 in your code up top there would still be null pointers, however.
You can fix your problem by doing the same - pass p1 and p2 to SomeMethod() by reference:
 SomeMethod(&p1, &p2);

That change will require you to make some modifications in SomeMethod():
void SomeMethod(SomeClass **p1, SomeClass **p2)
{
    someMethodThatModifiesThePointers(p1, p2);
    printf("P1 total: %d\n", (*p1)->total);
    printf("P2 total: %d\n", (*p2)->total);
};

After this call, p1 and p2 in your top function will behave the way you want them to.
Comment: Note that you can/must emulate pass-by-reference by another pointer (i.e. `SomeClass **` parameters, passing `&p1` to `SomeMethod`, etc.).
Comment: Sorry, I made a small typo in my original code but I don't think it'll change anything.  Just added & in front of the parameters in the function calls.  someMethodThatModifiesThePointers is cvExtractSURF, which actually allocates and fills the pointers (it gathers SURF points from an image and fills the pointers with the SURF points).
Comment: @vapo, that's what I thought.  The same explanations in my answer still apply.
Comment: Ahhh I understand.  So, If I want the values to be valid on the outside, should I pass a pointer to the pointer as the parameter to someMethod, and then call someMEthodThatModifiesThePointers(p1,p2);?
Answer: What's happening is...
You: create a pointer to an 'instance' of SomeClass.
GCC: no problem! done.
You: assign 0x0 as the value for that pointer. That is, the 'object' it points to is located in memory in position 0x0
GCC: allright, 0x0 does not belong to your program, but I'll roll with it.
You: okay. Next, do something with my brand new SomeClass instance! Compile and run!
Operating System: WOAH WOAH wait a second, buster. You should've thought about using malloc() to ask me for some memory first. That 0x0 memory position belongs to ME, not to you. General Protection Fault, amigo, enjoy crashing.
(By the way, the terms 'class', 'instance', etc. are Object-Oriented Programming terms, they don't quite belong in C. We usually talk about structures, functions and pointers here :)
Comment: LOL I Wish GCC and the OS would talk to me like that.
Comment: My apologies and thanks for the explanation.  I made a slight typo in my code posted above.  Mainly, the parameters passed to someMethodThatModifiesThePointers
Answer:
the pointer's .total property (an integer) is valid inside of the method, but is no longer valid outside of it. Why is this the case?

Given the fact it prints valid value inside SomeMethod prints valid value and crashes up on return of the SomeMethod,I guess that both p1,p2 are passed by value. Upon return of SomeMethod, both p1,p2 are null pointers and dereferencing it explains the crash. You need to post the code of someMethodThatModifiesThePointers(p1, p2);.
Answer: Part of the confusion is that you have chosen the same names for the pointers outside and inside the function. Try this instead:
SomeClass *p1= 0, *p2 = 0;
SomeMethod(p1, p2);
printf("P1 total: %d\n", p1->total); // crashes
printf("P2 total: %d\n", p2->total); // crashes

// method someMethod, where the values of the pointers are valid
void SomeMethod(SomeClass *p3, SomeClass *p4)
{
    someMethodThatModifiesThePointers(&p3, &p4);
    printf("P3 total: %d\n", p3->total); // prints valid value
    printf("P4 total: %d\n", p4->total); // prints valid value
};

The pointers p1 and p2 are copied to p3 and p4 respectively, but not the other way round.


Determining if slopes are zero or slopes are equal- can one actually accept a null hypothesis?

Question: I am not a statistician and would like some help discussing best practices with colleagues.
My understanding is that if I run a linear regression
y = ax +b
the p value I get for x is testing HO:a=0 vs H1:a is not zero
If the p value is low enough, I can reject the null hypothesis and assume that the slope is significant. I believe I cannot say that the slope is zero, i.e. accept the null hypothesis.
I am now looking at discussions of using ANCOVA to compare the slopes of two groups. In that case, I add a categorical value to the equation and I will end up with an interaction term which is evaluated via an F test. I will also get a value for Pr(>|F|).
If that is low enough, I can reject the null hypothesis and assume the slopes are different. Everything I have read on-line seems to make the claim that if the value is high, the slopes are the same.
I mostly compare means, in which case, if I cannot reject the null hypothesis, I switch to an equivalence test (TOST) to see if the means are the same within a predefined threshold.
Perhaps, naively, I would have thought the same would apply to testing for zero slope or whether slopes are the same. I am getting a lot of push-back from colleagues who routinely use a t-test to determine if a slope is zero and ANCOVA as above to indicate the slopes are the same. but there are no statisticians in our company.
Maybe I am just caught up in unfamiliar jargon, but a little understanding of how to think about these questions would be very helpful.
Answer: Yes, you are correct that you can never "accept" a null hypothesis. Hypothesis testing can be seen as a "proof by contradiction". If we assume the null and obtain a very rare finding, we say that with some significance level, we reject the null (and conclude the alternative when it is the complement of the null). However, when you fail to reject, this definitely gives no reason to accept the null. "Absence of evidence is not evidence of absence".
I would highly recommend you to look into equivalence testing if you want to establish equality means. One useful review paper to look at is the following https://www.sciencedirect.com/science/article/pii/S0950329312000961. One approach discussed here is the power approach which says the we can only "accept" the null if we have sufficient power against particular alternatives. If these alternatives would be true, we would have rejected with our test (under a particular significance level). However, this approach also has some drawbacks as discussed by the paper. It also explains TOST in detail and should be possible to follow for non-statisticians.
Comment: Just a quick question. I use TOST for testing for equivalence of means. The question that I am now dealing with is testing either that a slope is zero or that two slopes are the same. I believe the first part of your answer makes it clear that this cannot be done based on not being able to reject the null hypothesis. You then talked about equality of means. Are the approaches for comparing means equally appropriate for slopes?
Comment: Yes I would say so. In the end, both the (underlying) mean and slope are parameters to be estimated. To draw conlusions about the equality of such parameters, not rejecting the null is not sufficient to make a claim. Applying a TOST procedure can help you with that.
Answer: You don't need to explicitly perform two t-tests. It is sufficient to consider the confidence interval and the three hypotheses
$$\begin{array}{}H_0&:& \text{|difference|} = 0\\
H_\epsilon&:& 0 <\text{|difference|} \leq \epsilon\\
H_\text{effect}&:&  \epsilon < \text{|difference|} \end{array}$$

and you can do this for the estimates and confidence intervals of slopes.


Etale groupoid and Morita equivalence

Question: Let $\mathcal{G}=(G_{1}\rightrightarrows G_0)$ be a groupoid, where $G_{0}$ is the space of objects and $G_{1}$ is the space of morphisms. $\mathcal{G}$ is called etale if both the source and target maps
$$
s,t:G_{1}\rightarrow G_{0}
$$
are local diffeomorphisms. Being etale is $not$ invariant under Morita equivalence (equivalence of categories).
Could anyone give me a simple example of this fact?
Answer: Take the action of $R$ on itself. The associated groupoid is the equivalence relation.
This is Morita equivalent to a point (the action is free and proper). $R\times R$ is not etale.
A better example would be to look at the full holonomy groupoid vs the restriction to a complete transversal.

Etale groupoid and Morita equivalence


Question on a measurable function

Question: Suppose $f$ is a nonnegative measurable function on $\mathbb{R}$. We assume that $f$ can take infinite values . The Lebesgue integral of such a function is defined exactly as for functions from the class $K_3$. We also assume that $ \int f dx <\infty $ . Prove that
$$m\{x\in \mathbb{R} : f(x)=\infty \}=0$$. any hint and help will be appreciated .
Answer: Suppose $f\ge 0$, $f$ is measurable and that $\int f < \infty$.  I will use the notation $|\cdot|$ for Lebesgue measure and $[f > \lambda]$ for $f^{-1}(\lambda,\infty)$.
Then by Chebyshev's inequality,
$$ |[f > \lambda]|\le {1\over \lambda} \int f.$$
Since the right-hand side converges to zero as $\lambda\to\infty$, you have
$$|[f = \infty] = \left|\bigcap_{\lambda > 0} [f > \lambda]\right| = 0.$$
Comment: Thanks .. The Proof is clear

Question on a measurable function


Can't make taps gem 0.3.23 working with heroku gem 2.1.4

Question: Anyone have an fix for this problem?
It happens on push and pull.
~ heroku db:push
Taps Load Error: no such file to load -- taps/operation
You may need to install or update the taps gem to use db commands.
On most systems this will be:

sudo gem install taps
~ sudo gem list

*** LOCAL GEMS ***

bundler (1.0.13)
mime-types (1.16)
rack (1.2.2)
rake (0.9.0)
rest-client (1.6.1)
sequel (3.20.0)
sinatra (1.0)
sqlite3 (1.3.3)
sqlite3-ruby (1.3.3)
taps (0.3.23)
~
~ heroku version
heroku-gem/2.1.4

Answer: I had the same issue. I solved the problem by adding taps to my Gemfile and using bundle exec heroku db:push
Answer: If you are using Bundler, you can try to declare in gem "taps" into your Gemfile.
Currently i am using:
taps (0.3.23)
heroku (2.6.1)

working with
rails (3.1.0.rc5)
rack (1.3.2)

Answer: Try downgrading rack version to 1.0.1


in adding values from different fields and add them

Question: I've an issue which is that i've 4 radiobuttons for one service and when user selects any radio button its value is added to total_sum using javascript .change() function. But the problem is it keeps adding false value. Like if you select two radio boxes each at a time. Then it adds false value

jQuery("input:radio").change(function() {
  var total = parseInt(jQuery('#total_sum').val());
  var ischecked= jQuery(this).is(':checked');
  var unchecked = jQuery(this).is(':unchecked');
  var price = parseInt(jQuery(this).val());
  var newprice = total;
  var sum = 0;
  if(ischecked){
    sum = total + Number(price);
    jQuery('#total_sum').val(sum);
  }
  else if(unchecked){}
});
var total = parseInt(jQuery('#total_sum').val());
jQuery('#sqfootage').bind('change', function () {
  var sqfootage = jQuery('#sqfootage').val();
  var sqfootage_val = 0;
  var sum = 0;
  if(sqfootage >= 1 && sqfootage <= 1500)
  {
    sqfootage_val = 10;
  }
  else if(sqfootage >= 1501 && sqfootage <= 1800)
  {
    sqfootage_val = 15;
  }
  else if(sqfootage >= 1801 && sqfootage <= 2100)
  {
    sqfootage_val = 20;
  }
  else if(sqfootage >= 2101 && sqfootage <= 2400)
  {
    sqfootage_val = 25;
  }
  else if(sqfootage >= 2401 && sqfootage <= 2700)
  {
    sqfootage_val = 30;
  }
  else if(sqfootage >= 2701 && sqfootage <= 3000)
  {
    sqfootage_val = 35;
  }
  else if(sqfootage >= 3001 && sqfootage <= 3300)
  {
    sqfootage_val = 40;
  }
  else if(sqfootage > 3300)
  {
    sqfootage_val = 40;
  }
  sum = total + Number(sqfootage_val);
  jQuery('#total_sum').val(sum);
});

  <legend>What is the total square footage?</legend>

    <input name="sqfootage" id="sqfootage" min="1"  type="number" value="" placeholder="SqFootage:">

  <legend>Services</legend>

    <input name="service1" value="10" vt="Standard (one time)" type="radio" i="0">1

    <input name="service2" value="20" vt="Standard (one time)" type="radio" i="0">2

    <input name="service3" value="25" vt="Standard (one time)" type="radio" i="0">3

    <input name="service4" value="30" vt="Standard (one time)" type="radio" i="0">4

<input id="total_sum" name="total_sum" class="medium" type="text" value="89">
Answer: Your code has error. jQuery does not include a :unchecked selector. Instead, you need to invert the :checked selector. So change
var unchecked = jQuery(this).is(':unchecked');
to var unchecked = jQuery(this).not(':checked');
to fix the issue. Not sure though why you are using radio instead of checkboxes.
Comment: yes this is it. And since `unchecked` is not really used in code, commenting it removes `Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: unchecked` and lets the code continue executing
Comment: And not sure why OP is checking `checked` and `unchecked` on the same element.
Comment: @user2233501 Unless you fix this error your code will not execute.
Comment: and regarding radio, you should take Hector advice. Checkboxes are better for your case. and no need to use two variables (`checked` and `unchecked`). Use only one boolean variable. use also `var $this=jQuery(this)` for caching.
Comment: Hi, Thanks for reply guys. I appreciate the answer but unchecked is not the problem that i've asked for. See in code i haven't anything under unchecked condition
Comment: the problem is this

For example
if i select one radio button(it adds 10 + total(89) = 99)
but what if i decide to choose another radio(it gets total which was 99 and adds 20 into 99 which 119)
Comment: What is the expected behavior when you select second radio?
Comment: @HectorBarbossa it adds value to total amount (89). for example if i select one radio it add its value 10 to total and total becomes 99. But if tend to choose another radio it adds the value to new total (99). I dont want this to happen what i want is it should add value of selected radio
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/117150/discussion-between-user2233501-and-hector-barbossa).
Answer: There is no jQuery pseudoselector ':unchecked'
You want this line instead:
var unchecked = jQuery(this).not(':checked');
I ran this in jsFiddle and it works after fixing this error.


How to allow the setting of the Views Exposed Filters one at a time, instead of showing all available exposed filters at once

Question: I have a view with a ton of exposed filters. Placing all in one page (even in a collapsible fieldset) is overwhelming for the users. Is there a module that allows a users to add a filter one-by-one?
Hopefully the screenshot of a third party application helps to explain
Answer: I believe the views dependent filters module will do it for you.
I haven't used it but from what I can see it works just like dependent fields.