Assuming GCH: if $\mathrm{cf}(\kappa) \leq \lambda < \kappa$, then $\kappa^\lambda = \kappa^+$ (Jech Theorem 5.15)

Question: I am trying to fill in the details for part (ii) of Theorem 5.15 in Jech's Set Theory:

Theorem 5.15 If GCH holds and $\kappa$ and $\lambda$ are infinite cardinals, then
(i) If $\kappa \leq \lambda$, then $\kappa^\lambda = \lambda^+$.
(ii) If $\mathrm{cf}(\kappa) \leq \lambda < \kappa$, then $\kappa^\lambda = \kappa^+$.
(iii) If $\lambda < \mathrm{cf}(\kappa)$, then $\kappa^\lambda = \kappa$.

In the proof of (ii) he just states that it follows from these two lemmas:

Lemma 5.7 If $|A| = \kappa \geq \lambda$, then the set $[A]^\lambda$ has cardinality $\kappa^\lambda.$

(Here $[A]^\lambda = \{X \subset A : |X| = \lambda\}.$)

Lemma 5.8 If $\lambda$ is an infinite cardinal and $\kappa_i > 0$ for each $i < \lambda$, then
$$\sum_{i<\lambda}{\kappa_i} = \lambda\cdot\sup_{i<\lambda}{\kappa_i}.$$

I am struggling to construct an explicit proof using these results and a few facts about cardinal arithmetic such as absorption for infinite cardinals and cardinalities of power sets.
Since, assuming GCH, $\kappa^+ = 2^\kappa = |\mathcal{P}(A)|$ for some $A$ with cardinality $\kappa$, I thought I could come up with some sequence $\{\mu_i : i < \mathrm{cf}(\kappa)\}$ such that
$$\kappa^+ = 2^\kappa = |\mathcal{P}(A)| = \sum_{i < \mathrm{cf}(\kappa)} |[A]^{\mu_i}| = \sum_{i < \mathrm{cf}(\kappa)} \kappa^{\mu_i} = \mathrm{cf}(\kappa)\cdot\sup_{i<\mathrm{cf}(\kappa)}\kappa^{\mu_i} = \mathrm{cf}(\kappa)\cdot\kappa^\lambda = \kappa^\lambda$$
Is this approach a good idea? How would I go about finding the appropriate $\mu_i$? I suppose it will have to make use of the assumption that $\mathrm{cf}(\kappa) \leq \lambda < \kappa$, but I don't see how.
I'd much appreciate any hints on how to proceed (either with my suggestion or another way).
Answer: You fell into a trap that also caught me when I was just starting to read mathematical books. When you see a reference to (5.7) it does not mean Lemma 5.7, but rather the displayed formula whose tag is 5.7, which in this case is the formula:
$$\kappa\leq\kappa^\lambda\leq 2^\kappa.$$ Similarly, (5.8) refers to the inequality $$\kappa<\kappa^\lambda\quad\text{ if }\lambda\geq\operatorname{cf}\kappa.$$
And indeed these are the inequalities needed to prove (i) and (ii).
Comment: Oh! That makes a lot more of sense. Thanks! I think it was more confusing as the line immediately above cites Lemma 5.6, then it cites (5.7) and (5.8).


How do I determine if two of my software's representation of algebraic numbers are equal?

Question: I have software which stores information about algebraic numbers with absolute precision. If you build it up by creating instances of a Python representation of an integer, float, Decimal, or string, a binary tree in which each node is either a leaf node containing an integer, or a node storing an arithmetical operation and two order-significant children, the two numbers included in the operation. For the purposes of this discussion, I am ignoring the case of representing computable numbers like π and e, and assuming that all algebraic numbers are a binary tree boiling down to integers and floats.
There are two major liabilities which boil down to one: I don't see how to always know when there is rounding error at a particular node on the binary tree, and I don't know, in terms of math, how to tell if two algebraic numbers are equal. I can pull what is the standard operating procedure for floats, which is to never look for equality, just confirm that their equality is "good enough for government work" by calculating decimal representations to some perhaps configurable number of decimal places. One can of course increase the precision in the hopes of finding a difference, but that technique will perhaps eventually find the most minute inequality, but never prove an absolute inequality rather than a
"looks at least close enough" claim of equality. The sets of "greater than" and "less than" are both recursively enumerable, but unless you can pull a theory-based test for algebraic equality / comparison, equal numbers are not even recursively enumerable.
My program is implemented in Python, as an "executable pseudocode" implementation implemented more than anything else reference implementation than anything else. But my question is not really a Python question; it is a question about an area of math I know little about. My question is this:
Given two representations of algebraic numbers built up by arithmetic on integers (which happens to be a binary tree, but that is not my question): Are there any algorithms that can compare / test for equality?
Comment: It seems a little odd that you are trying to do exact computation with algebraic numbers, but yet allow some quantities to be represented with inexact floating-point approximations....
Comment: @MJD: The same logic could be applied to any representation of numbers to say that they aren't really numbers. :P  Algebraic numbers are definitely decidable, though; in fact, the first-order theory of real closed fields is even *complete*.
Answer: There is a standard way to represent algebraic numbers that also directly suggests the methods to test things like equality: you represent them by specifying their minimal polynomial, and enough supplemental data to indicate which root of the minimal polynomial is intended.
Every algebraic number has a unique minimal polynomial. So with a suitable encoding of the supplemental data, you can even arrange things so that each algebraic number has a unique representation.
It may or may not be easier to use this scheme to represent just the real algebraic numbers, and then represent complexes in the usual way as pairs of real algebraic numbers. This would let you use make use of nice computational techniques like Sturm's theorem
Comment: To give particular examples to illustrate Hurkyl's point: *Mathematica* has `Root[]` objects, and Maple has `RootOf()` objects; both represent algebraic numbers in terms of the minimal polynomial and a particular index (though SFAICT the two environments have a different indexing scheme; see their docs for details).


Trying to inject JS file, getting theme errors...why?

Question: So, my theme.libraries.yml file shows:
global-styling:
  css:
    theme:
      css/style.css: {}
      css/custom.css: {}
  js:
    js/myjavascript.js: {}

In mytheme.theme, hook_preprocess_node() I have added:
$variables['#attached']['library'][] = 'myjavascript.js';

Drupal is throwing this error message:
User warning: The following theme is missing from the file system: myjavascript.js in drupal_get_filename() (line 250 of core/includes/bootstrap.inc).

I cannot see where I'm going wrong. The javascript is definitely being injected, since it all works. Why am I getting this error?
thanks
Comment: You can follow [topic](https://drupal.stackexchange.com/questions/214014/how-do-i-load-js-file/214019). With Drupal 8, you need to add library not a file.
Answer: To sum it up: You may just omit your manual inclusion/attachment of the JavaScript file in hook_preprocess_node().
Long version:
As @MrD already stated, in Drupal 8 you attach libraries, not files. So with your statement, your Drupal is looking for a library definition myjavascript.js. Which would mean a libraries file like:
myjavascript.js:
  js:
    js/myjavascript.js: {}

As you already added the JavaScript file to your global-styling library, and this library seems to being attached within your theme already, the JavaScript automagically will be included when you use the theme.
For creating an own library that can be attached conditionally, please refer to the answer referenced by MrD.


Separate control of a loop pedal without effecting the main sound

Question: For instance I have a guitar a loop pedal, a distortion pedal, and a volume pedal. Well what I want to get is:
While playing, to be able to increase or decrease the volume of the loop pedal without effecting the solo played over the loop that is effected only by the distortion pedal.
Answer: Controlling the loop volume with your volume pedal without affecting the signal is not really possible with only those three pedals in your pedalboard.
If you have the loop already going, placing the volume pedal before the loop would only allow you to alter the sound played over the loop. Placing the volume after the loop would affect both at the same time.
One option, assuming no other pedals and not touching the loop pedal knobs, would be to do the opposite: instead of lowering the volume of the loop, get a boost on the solo after recording the loop by placing the volume before the loop and altering the solo sound without affecting the looped sound.
Comment: this is absolutely doable, but as Joncour says, not with what you have.
Comment: I need tp change the loop volume 'during playing solo.


High-end headset/lavalier mics vs handheld for vocals

Question: Background:
I have some SM58's (a dynamic mic) that I use for my vocals while I'm putting together songs on my iPad. I've recently tried some cheap $40-50-ish lavalier condensers because my dream is to have a a song sketchpad system that weighs <1kg! I already pretty much have that except for a few extra awkward pounds of SM58+preamp to carry around. These cheap ones sound pretty good but I'm wondering if I spend more I could get a recording-quality vocal mic that fits in my jeans pocket.
Questions:

In general can lavalier/headset (in other words, small) mics capture the "naturalness" and fidelity of a (larger) handheld mics? Or does size really limit the sound quality?
Is there any opinion on whether particular models of $$$ small mics (such as Countryman) sound as crisp and rich as an SM58 or other industry standard mics? If so, which ones?

Note: I realize there's a lot of opinion that singers who are used to using a handheld mic will hate lavalier/headset mics because you can't adjust the distance from your mouth. But I've tried both and it doesn't really bother me, so need to bomb this thread with that.
Comment: This might be good (better?) for sound-design?
Comment: @Dave yes it would, but at the moment Sound Design is unstable and it would be very hard to migrate it there.
Answer: The size of a microphone has little to do with the sound quality. While dynamic mics always require a certain size just to function, condensors can be made really small.
A small condensor will first of all be more noisy than a larger one, which makes it unsuitable for delicate recordings. The sound quality as such is actually more likely to improve. The nonzero diameter of the diaphragm is somewhat of a problem in lager condensors, because it colorizes the directional characteristics (sound changes with angle)
Lavalier microphones are meant to be used on a jacket. They need to make up for the damping of the fabric. When used as a hand-mic they may sound overly crisp.
IIRC Schoeps makes a high-end lavalier.


Does DNSSec NSEC3 require support from the Registrar, DNS Server or both?

Question: I'm interested in getting NSEC3 support for my domain getvalid.com, so that I can prevent name traversal.
DYN doesn't seem to support NSEC3, and it's clear that BIND and the DNS server require the ability to support NSEC3... but I'm unsure if the underlying registrar has any influence on NSEC3 support.
Do I need to do anything with a registrar for NSEC3?
Comment: Based on @Håkan's comment below, I would say that DYN does in fact support it.
Answer: In DNSSEC, the role of the root and intermediate nameservers are to provide a chain of trust until an authoritative nameserver for your zone is reached. Aside from hosting the public DS key associated with your signed zone, they have no role in NSEC3 validation.
For NSEC3 to function, you need to sign your zone using an algorithm that mandates support for the feature. Older algorithms are supported via variants that contain a -NSEC3- identifier. Resolvers will not attempt to utilize the newer functionality unless the support is advertised in this fashion. If the zone has been signed correctly, all you should need to do is follow the usual steps for getting the DS key digest published to the nameserver immediately before yours in the delegation chain.
From RFC5155:

In order to aid deployment, this specification uses a signaling
technique to prevent NSEC3-unaware resolvers from attempting to
validate responses from NSEC3-signed zones.
This specification allocates two new DNSKEY algorithm identifiers for
this purpose.  Algorithm 6, DSA-NSEC3-SHA1 is an alias for algorithm
3, DSA.  Algorithm 7, RSASHA1-NSEC3-SHA1 is an alias for algorithm 5,
RSASHA1.  These are not new algorithms, they are additional
identifiers for the existing algorithms.
Zones signed according to this specification MUST only use these
algorithm identifiers for their DNSKEY RRs.  Because these new
identifiers will be unknown algorithms to existing, NSEC3-unaware
resolvers, those resolvers will then treat responses from the NSEC3
signed zone as insecure, as detailed in Section 5.2 of [RFC4035].
Comment: It's really only the original set of algorithms that were duplicated with `-NSEC3-` in the name to indicate NSEC3 support for compatibility reasons. New algorithms that have been introduced do not make such a distinction, such as the now very common `RSASHA256` (algorithm 8) which [supports both NSEC3 as well as NSEC](https://tools.ietf.org/html/rfc5702).
Comment: @Håkan You're right. I've updated the answer to make this distinction.
Answer: As long as the registrar allows you to add any valid DS record that you want to the delegation of your zone, the registrar will not be a factor.
Some things that a registrar could do that would cause a problem is:

if they do not allow you to add DS records whatsoever you simply cannot have a signed delegation at all (with DLV as a potential workaround), not a problem for NSEC3 specifically but for DNSSEC in general
if they impose limits on the value of the DS record (specifically the algorithm field) that could force you to use an algorithm which predates NSEC3.

The limitation of algorithms is not something I have encountered but it's at least theoretically possible that someone could have outdated validation code in place or something like that.


Taking two sets (A, B) out of the same distribution, merging and then sorting should roughly result in a,b,a,b,a,b?

Question: Suppose I take 2 sets ($A$ and $B$) of 1000 random items out the same distribution; I also suppose that all items are different.
I then create a new set $C$ which is the union of $A$ and $B$, since all items are different it has 2000 elements.
If $C$ is sorted (ascending or descending), should I roughly end up with a sequence: $a_0,b_1,a_2,b_3,a_4,b_5,...a_i,b_j,...b_{2000}$ ($a_i$ is an element of $A$ and $b_j$ is an element of $B$?
Or alternatively should the number of runs (defined by Wald-Wolfowitz) be almost equal to number of elements in $C$? Here a run is a follow up of elements from the same set.  For example:

$a,b,a,b$ has 4 runs
$a,a,a,b,b$ has 2 runs
$a,b,b,b,a,a$ has 3 runs

If this would not be case, what's the reason behind it?
To give a more practical setting, I also implemented this now and asked it on stackoverflow.
Comment: This seems clear enough to me. I'm voting to leave open.
Comment: Some or same?  Either way there is not information to determine the sequence.
Comment: The same distribution, I changed it.
Comment: @gung Do you know what the other eliminates in the sets are either before or after they are merged?
Comment: @MichaelChernick I'm not sure what you mean, but when the sets are merged, the union is taken and no elements are eliminated.
Comment: I think the question has changed considerably.  Is a the only element in A and b the only element in B?  If so the union of the two sets is just {a, b}. I don't think the Wald-Wolfowitz run test came up in the original question. I am still puzzled as to how the elements are randomly drawn.  Are you drawing them out of C 1000 times?  If so is this done without replacement? I still don't see how the question is clear and I don't see what interpretation is being used by those who gave answers.
Comment: I made the confusion around the union clear. The elements are drawn like you would do with python: `A = np.random.chisquare(1, 1000)` and `B = np.random.chisquare(1, 1000)`.
Comment: This is the situation analyzed in the first page of Part I of A. M. Mood, *The Distribution Theory of Runs* (1940): https://projecteuclid.org/euclid.aoms/1177731825.
Comment: Consider this thought experiment: watch the sequence as it is created. At any stage, roughly half the sequence consists of $a$'s and half of $b$'s. Until the end, there is about a 1/2 chance that the next element in the sequence will be an $a$ and a 1/2 chance it will be a $b$, and there is a 1/2 chance the *current* element is an $a$ and 1/2 chance it is a $b$. Therefore there is a 1/2 chance that the next element will be the same as the current element--continuing a run--and a 1/2 chance it will be different, creating a new run. Thus the expected number of runs is close to $2000/2=1000$.
Answer: Cool question! If we generalize your framework and let $n$ represent the number of items in each set, then we can make some headway toward finding the solution. In your case $n = 1000$. But what if we let $n = 1$? There are always ${2n} \choose {n}$ total arrangements so in the simplest case where $n=1$, there are just two possibilities. Both have 2 runs. Now, consider $n=2$. There are ${2n} \choose {n}$ $= 6$ arrangements and the average number of runs is exactly 3. Going further, $n=3$ leads to 20 arrangements and an average of 4 runs. At this point, it seems unlikely that the answer will ever differ from $n+1$ as the average number of runs. This can probably be proved by induction pretty easily.
Comment: your answer actually says I'm wrong because it would mean I end up on average with a,a,b,b,a,a,b,b ... because C has 2000 elements in it and not 1000?
Comment: I'm not sure I understand what you're asking. A and B both have 1000 elements. C is a concatenation of the two which is subsequently permuted randomly. Thus, C has 2000 elements. You're original guess of an average number of runs of 1000 was wrong...but just barely. The answer is actually 1001.
Answer: By comparing your problem to the Mann-Whitney test I guess you are correct, in the sense that the run lengths should not be much different from one. This test is based on summing the ranks of each set (a or b in your case) and then looking at the difference.


Dúvida sobre ajax

Question: Minha dúvida está em saber se este meu codigo está correto.
$(document).ready(function(){
                $("#fechar").click(function(e){
                  e.preventDefault();
                  String lista_Cont = $(this).attr('<?php include "listaUsuario2.php";?>');
                  $("#lista").load(this.lista_Cont);
                });
            });

A função dele é, quando eu fechar o modal, onde eu utilizado para cadastrar um novo usuário, ele recarregue o conteúdo atualizado novamente, porem é na mesma pagina onde já esta.
Eu tenho uma pagina de Admin, onde eu clico em cadastrar e vou em usuários, o sistema em Ajax retorna apenas o conteúdo do meio alterado, neste conteúdo vem o código onde eu listo todos os usuários já cadastrados e dou a opção de cadastrar novo usuário, caso seja escolhida, esta opção abre um modal, onde eu cadastro novo Usuário, porem este modal continua aberto, e quando fecho ele, a pagina não está atualizada. Preciso que quando eu fechar ele já atualize a seção para min, e me possibilite ver os usuários novos cadastrados imediatamente.
MEU CODIGO COMPLETO:

                        <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">
                             Inserir
                        </button>

                <legend>Úsuarios Cadastrados</legend>

                <?php include "listaUsuario2.php";?>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Novo Úsuario

            <form class="form-horizontal" action="" method="post" id="cadUsuario">
            <fieldset>

                        <input id="TXT_NOMEX_USUAR" name="TXT_NOMEX_USUAR" type="text" placeholder="Nome" class="input-large">

                        <input id="TXT_ENDER_EMAIL" name="TXT_ENDER_EMAIL" type="text" placeholder="Email" class="input-xlarge">

                        <input id="TXT_SENHA_USUAR" name="TXT_SENHA_USUAR" type="password" placeholder="Senha" class="input-small">

                    <button type="button" class="btn btn-default" data-dismiss="modal" id="fechar">Fechar</button>
                    <button type="submit" class="btn btn-primary" id="botao_cadUsuario">Salvar</button>

            </fieldset>
            </form>

Answer: Cria uma página com um Select fazendo a busca pelos registros e com a mesma formatação da sua lista.
E no ajax você faz:
$("#lista").load('lista.php');

jQuery.ajax({
   type: "POST",
   url: "salvarUsuario.php",
   data: dados,
   success: function( data )
   {
       $("#lista").load('listausuario.php');
   }
});

Comment: So que tipo, quero fazer isso de forma que so utilize o ajax, e ele carregue esta mesma pagina
Comment: Pode ser a mesma. Desde que seja idêntica sua formatação. Mas não precisa do **include**. O *load* já faz o carregamento da página.
Comment: Ele irá carregar a mesma coisa dentro da minha principal ? Porque esta pagina ja está dentro de uma principal, e se eu atualizo ela volta para home da principal.
Comment: Oh Mano. Você tem uma Div#Lista. Ok ? Dentro dessa Div você carrega um Include pelo que estou vendo. É a lista de Usuários. Beleza. Quando você cadastra alguém novo e fecha o modal você quer recarregar essa lista com a lista nova com o novo usuário cadastrado. Certo ? Então, você pode utilizar a mesma página do Include. Coloca no Load. E coloca um **cache:false** no Ajax.
Comment: Melhor ainda, Cara. Coloca no seu ajax um Success.
Comment: como ficaria  isto ?
Comment: Editei meu Code.
Comment: Obrigado, consiguir obter exito com a sua ajuda. Agora gostaria que me ajuda-se na parte do delete. tem como ?
Comment: Tem sim. Tenta aí alguma coisa e nos fale. Talvez até um tipoco novo.
Comment: http://pt.stackoverflow.com/questions/67212/delete-no-banco-utilizando-ajax-e-jquery

O link de minha outra pergunta.
Answer: Essas linhas não estão nada corretas:
String lista_Cont = $(this).attr('<?php include "listaUsuario2.php";?>');
$("#lista").load(this.lista_Cont);

Variáveis no javascript são tipadas dinamicamente, não tem como fixar um tipo. Para declarar uma variável localmente, utilize o var:
var lista_cont = "lista_cont é uma string agora";

Se quiser declarar uma propriedade pública de instância, então utilize o this:
var minhaClasse = function() {
    this.Foo = "Uma string";

    this.imprimeFoo = function() {
        alert(this.Foo);
    }
}

var a = new minhaClasse();
var b = a.Foo;
a.imprimeFoo();

Logo, essa linhas tem um problema de sintaxe também, nesse contexto, this não existe, pois a variável lista_cont foi declarada localmente
$("#lista").load(this.lista_Cont); // deveria ser $("#lista").load(lista_Cont);

Quanto ao funcionamento do código:
Não é possível inserir código PHP dessa forma em elementos HTML:
$(this).attr('<?php include "listaUsuario2.php";?>');

O interpretador do PHP executa no servidor, antes do navegador receber o HTML. Se quiser atualizar dinamicamente com ajax, pode utilizar:
$("#lista").load("listaUsuario2.php");

O método load do PHP carrega o HTML do servidor e o coloca no elemento selecionado.
Comment: Obrigado, pela contribuição.
Comment: pode me ajuda com o deletar ? como faço para manda o id da tabela ?
Comment: Você pode usar o data attribute do elemento que contem o usuário da lista, ao clicar excluir le esse atributo e chama uma função PHP via ajax. No sucesso remove o HTML. Porém sugiro criar uma nova questão com essa dúvida específica, contendo o HTML da sua lista de usuários.
Comment: http://pt.stackoverflow.com/questions/67212/delete-no-banco-utilizando-ajax-e-jquery

Dúvida sobre ajax


lsass.exe memory leak on windows 2003 server

Question: In the past month or so I noticed that lsass.exe has started to leak memory, getting to 500MB+ of ram in under a week after reboot. Before this I had never noticed it using any significant amount of memory compared to other processes on the system.
This is happening on 2 identical servers, neither of which has anything to do with Active Directory.
Maybe a recent Windows Update has caused this? Any thoughts on things to check?
As a side question is there some way to recycle the memory usage of lsass.exe without rebooting?
Edit:

Here is what I'm seeing in Process Monitor, there are thousands of registry open/query/close a minute from lsass.exe. How can I track down what is triggering these?
Comment: Is the server this is happening on a DC?
Comment: @Zypher No, both computers having this issue have nothing to do with domain/active directory (both setup on a 'workgroup' and all users are local)
Comment: Anything unusual logged in the eventviewer? Is it physical or virtual memory you are seeing increase?
Comment: @SqlACID Nothing abnormal in event viewer. The 'Mem Usage' and 'VM Size' are about the same for lsass.exe, currently at 510M on one server and 380M on the other (the one that has been rebooted most recently).
Comment: Strange; no way to restart it that i know of; I would probably try running sysinternals filemon/regmon/process explorer and looking for anything unusual going on.
Answer: If you have iis on your server,  this microsoft  kb can help you : http://support.microsoft.com/kb/979730
Comment: This looks like exactly the problem, one of the listed updates was installed right before I started noticing this. I haven't yet installed the fix but my guess is that this will fix it.
Answer: Running 3rd-party software with integrated NTLM authentication? Could be that software requesting security info and never freeing it up again.
Also, are you using the "Built-In" groups for anything? Sometimes having a lot of heavily used accounts in the Built-In groups can do this.
Comment: Trying to think what all we have on here that might give you more info. We run cygwin sshd but its not very heavily used and it hasn't been upgraded or usage changed since this started happening. The only thing we use separate accounts for is http authentication on our IIS server (and only 2-3 users), all other apps running on the server are run under a single local user.
Answer: A memory leak occurs in the Lsass.exe process on a Windows XP-based or a Windows Server 2003-based computer:
http://support.microsoft.com/kb/902058
Also consider scanning for trojans
Comment: Already found that, but it is from years ago and these are fully patched servers that did not have any problem until about a month ago.
Comment: As previously mentioned: check for trojans or other undesirables.
Answer: We have also noticed some weird lsass memory usage lately when using SSL.  Eventually it will cause SSL connections to fail.
It looks like there was a patch release this week http://support.microsoft.com/kb/973917 that while not specifically mentioning the problem we have been seeing, seems to have fixed it for us.
Might want to check this out.


Lazarus / Delphi - Create vs TSomeClass.Create inside constructor - why is this causing trouble?

Question:
Highlight
This constructor:
constructor TCoords.Create(const AX, AY: Integer);
begin
    TCoords.Create(Point(AX, AY));
end;

has been confirmed malfunctioning in both Linux Lazarus 2 and Windows Delphi XE6.
Could this be a bug?

I am new to OOP in Lazarus / Delphi, excuse possible newbie error. Thank you.
I can't seem to understand why the following sequence of Lazarus / (Delphi-like) custom, very basic, an object will not work. I'm trying to debug this for hours already, since then I found:
What works:
Calling the one constructor without an argument, and calling the one with TPoint argument directly.
What doesn't:
Calling this one:
constructor Create(const AX, AY: Integer);

However, I found this would work - But only if if called without its class name inside the constructor. Why is that causing trouble?

Declarations
// WORKS - this creates instance of TCoords initialized to PointOutOfReach
constructor Create; reintroduce;
// WORKS - this creates instance of TCoords initialized to user coordinates
constructor Create(const ACoords: TPoint);
// DOES NOT WORK, strangely returns Point(0, 0), if called with class name
// WORKS only if called without class name - confusing or error on my side?
constructor Create(const AX, AY: Integer);

Calls
// OK - WORKING
NewCoords := TCoords.Create;
NewCoords.X:=12;
NewCoords.Y:=120;
ShowMessage(NewCoords.X.ToString + ' : ' + NewCoords.Y.ToString);
NewCoords.Free;

// OK - WORKING
NewCoords := TCoords.Create(Point(12, 120));
ShowMessage(NewCoords.X.ToString + ' : ' + NewCoords.Y.ToString);
NewCoords.Free;

// NOT WORKING as expected
NewCoords := TCoords.Create(12, 120);
ShowMessage(NewCoords.X.ToString + ' : ' + NewCoords.Y.ToString);
NewCoords.Free;

Coords unit with TCoords object definition
unit Coords;

{$mode objfpc}{$H+}

interface

uses
    Classes;

type
    // Flexible X,Y coordinates object.
    TCoords = class(TObject)

    // these declarations are accessible within this unit only
    private
        // this is the variable we are working with
        FCoords: TPoint;
        // property for this function is unnecessary, but I like it as it is
        function IsInitialized: Boolean;

    // these declarations are accessible to all
    public
        // this creates instance of TCoords initialized to PointOutOfReach
        constructor Create; reintroduce;
        // this creates instance of TCoords initialized to user coordinates
        constructor Create(const ACoords: TPoint);

        // THIS ONE DOES NOT WORK, strangely returns Point(0, 0)
        constructor Create(const AX, AY: Integer);

        // this indicates if instance was initialized or not by the user
        property Initialized: Boolean read IsInitialized;
        // this works directly with private FCoords variable storing coordinates
        property P: TPoint read FCoords write FCoords;
        // these two are shortcuts for X,Y coordinates' direct access
        property X: Integer read FCoords.X write FCoords.X;
        property Y: Integer read FCoords.Y write FCoords.Y;

    end;

implementation

var
  // this gets initialized when loading this unit
  PointOutOfReach: TPoint;

constructor TCoords.Create;
begin
    // this is the same as `inherited`, but I like to be explicit
    inherited Create;
    // since called without argument, we have to ensure, there is some nonsense
    FCoords := PointOutOfReach;
end;

constructor TCoords.Create(const ACoords: TPoint);
begin
    // this is the same as `Create`, but I like to be explicit
    TCoords.Create;
    // in the previous mandatory call we have initialized FCoords already
    // but to PointOutOfReach; here we overwrite it with user coordinates
    FCoords := ACoords;
end;

constructor TCoords.Create(const AX, AY: Integer);
begin
    // this is the same as `Create(TPoint)`, but I like to be explicit
//    TCoords.Create(Point(AX, AY));

    // Why can't I call the above, shouldn't it be the very same?
    Create(Point(AX, AY));
end;

function TCoords.IsInitialized: Boolean;
begin
    // this returns True in case FCoords has been initialized
    // initialized means here for the FCoords point to be different from PointOutOfReach
    // achieved either by calling `Create(APoint)`, or later overwriting PointOutOfReach
    Result := FCoords <> PointOutOfReach;
end;

initialization

    // initialize PointOutOfReach to "impossible" coordinates when loading unit
    PointOutOfReach := Point(MAXINT, MAXINT);

end.

Thank you in advance, I myself can't seem to see the difference between those two.

Major error corrected - no change
Missing overload; in constructors' declarations has been corrected. Still getting 0,0 coords from the last constructor, sadly.
Answer: David Heffernan stated the reason for my approach not to work in a comment, let me quote:

TCoords.Create(Point(AX, AY)) creates a new instance. When you do this inside a constructor you now have two instances. Replace it with Create(Point(AX, AY)).

Thank you kindly for the explanation!

If even solved, I think a better approach will be not chaining those constructors.

Applying this rule works, working snippet with unchained constructors:
constructor TCoords.Create;
begin
    inherited Create;
    // since called without argument, we have to ensure,
    // there are some corner-case coordinates, so that we can
    // differentiate between a [0:0] and uninitialized state
    FCoords := PointOutOfReach;
end;

constructor TCoords.Create(const ACoords: TPoint);
begin
    inherited Create;
    FCoords := ACoords;
end;

constructor TCoords.Create(const AX, AY: Integer);
begin
    inherited Create;
    FCoords := Point(AX, AY);
end;

PS: For the code to work, so far I see no need to apply "setters" as in Nasreddine Galfout's answer.
Answer: It is the way you are declaring the properties X and Y change them to this
property X: Integer read FCoords.X write SetCoordX;
property Y: Integer read FCoords.Y write SetCoordY;

procedure TCoords.SetCoordX(const Value: Integer);
begin
  FCoords.X := Value;
end;

procedure TCoords.SetCoordY(const Value: Integer);
begin
  FCoords.Y := Value;
end;

This has to do with how Delphi does assignment of properties. In your case you  are assigning to an implicit variable added by the compiler when retrieving the value of X.
I can't seem to remember where I read about this I will find it and edit my answer


Angular 6: How to get response status code

Question: How do I get the service code? I try the code below, but it does not log anything.
In a service.ts file.
constructor(private http: HttpClient) { }

postForgotPass(email): Observable<Response> {

return this.http.post<Response>(envi.apiUrl +'/user/forgotpassword', {
  "email": email,
  "headers": headers,
  observe: 'response'

})
}

In my component.ts file
sendForgotPass() {
 return this.service.postForgotPass(this.emailFormControl.value)
    .subscribe(
      res => {
        console.log(res.status);
      })
    }

Comment: https://stackoverflow.com/questions/46639154/how-can-get-httpclient-status-code-in-angular-4
Comment: Have you tried `Observable`?
Answer: From Angular docs:
getConfigResponse(): Observable<HttpResponse<Config>> {
  return this.http.get<Config>(
    this.configUrl, { observe: 'response' });
}

Usage
this.configService.getConfigResponse()
    // resp is of type `HttpResponse<Config>`
    .subscribe(resp => {
      // display its headers
      const keys = resp.headers.keys();
      this.headers = keys.map(key =>
        `${key}: ${resp.headers.get(key)}`);

      // access the body directly, which is typed as `Config`.
      this.config = { ... resp.body };
    });

Answer: It is because non 2xx status codes are mapped to an error. You need to hook provide a handler for second parameter of subscribe(errors)
sendForgotPass() {
    return this.service.postForgotPass(this.emailFormControl.value)
        .subscribe(res => console.log(res.status), err => console.log('error', err.status))
    }

Comment: This work, but even 2xx codes are logging as "error:200". Why is that?
Comment: Something else must be wrong. Try logging what is in err variable. Maybe some deserialisation or content type is wrong. Check network tab of browser that you get what you expect.
Answer: if(response === undefined || response === ''  || response === null)
{
    this.isStatusCode[i] = false;
}

Answer: `import { HttpClient } from "@angular/common/http";
constructor(
private httpClient: HttpClient){}
this.httpClient.get<any>(this.API_URL, {observe: 'response'})
        .subscribe({
          next: (res) => {
console.error(res.status)  // api status in header
console.error(res.body) // response from api
}
})`

{observe: 'response'} in get method gives full response object


Adding multiple frames

Question: If I want that on clicking a certain button the current frame should close and a new frame with new content should appear, how can I do that?
For example, I have a login button, which on clicking leads to a new frame and closing the old frame.
public void actionPerformed(ActionEvent evt) {
 setVisible(false);//for closing the old frame

Now how can I add a new frame?
Comment: See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556)
Answer: You should use as you did, this.setvisible(false) or this.dispose(); depending on your requirements.
Theres a few posts that cover it but see here for specifics.
public void actionPerformed(ActionEvent evt) {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.pack();

//added new frame, set it to visible
frame.setVisible(true);
 //hide old one with setVisible or dispose()
this.setVisible(false); //or you'd be better using  this.dispose();
}

Adding multiple frames


Order in entity_load

Question: I see Documentation of entity_load but I didn't find anything about ordering of results,
How can I order the results entity_load by delta?
as example I fetch all product of one node by
<code>$node = node_load(313);
$field = field_view_field('node', $node, 'field_product_select');
$pids = array();
foreach ($field['#items'] as $key => $value) {
  $pids[] = $value['product_id'];
}
$products = entity_load('commerce_product', $pids, array(), TRUE);

$return = array();
foreach ((array) $products as $key => $product) {
  $return[$key]['product_id'] = $key;
  $return[$key]['product_type'] = $product->type;
  if($product->field_is_selected_price['und'][0]['value'])
    $selected_price=$product->commerce_price['und'][0]['amount'];
  $return[$key]['price'] = $product->commerce_price['und'][0]['amount'];
  $images = field_view_field('commerce_product', $product, 'field_product_images');
  foreach ((array) $images['#items'] as $image) {
    $return[$key]['img'][] = $image['uri'];
  }
}
</code>
I want fetch products order by 'delta'(or other field ),(results are order by entity_id by default) , how can I achieve it?
Answer: Most entity controller implementations of ::load() will return entities in the same order as the array of IDs passed in to be loaded. This is the case with DrupalDefaultEntityController and EntityAPIController, which are the two most common controllers.
In this case you could structure your initial query to get a list of IDs to be loaded with EntityFieldQuery and then use the results of that to pass to entity_load.
Looking at your original example, you just need to load a list of products based on the product field on a node. Here's a quick example of what it would take to handle that (since you don't need EntityFieldQuery):

<code>$node = node_load($nid); // If you don't already have access to the node
$wrapper = entity_metadata_wrapper('node', $node);

$product_ids = $wrapper->field_product_select->raw();
$products = entity_load('commerce_product', $product_ids);
</code>
This works because the field data is always queried with order by delta when using Drupal core's field SQL storage: https://api.drupal.org/api/drupal/modules%21field%21modules%21field_sql_storage%21field_sql_storage.module/function/field_sql_storage_field_storage_load/7
Comment: @mikev P, tnx for answer, I complete it with implementation of my solution
Answer: You can load each product separately
<code>foreach ($field['#items'] as $key => $value) {
  $products[] = entity_load('commerce_product', array($value['product_id']), array(), TRUE);
}
</code>
Comment: Depending on the number of fields on the product and the number of products to load, this could cause a larger than necessary number of queries to be run. See [What is the n + 1 select issue](http://stackoverflow.com/questions/97197/what-is-the-n1-selects-issue) for more information.
Comment: Yes, I understand that it's not the best solution. Thank you.

Order in entity_load


How to convert a menu tabs in menu links block?

Question: It would be very useful to be able to change the "tabs menu" in "menu links" to specific pages and users roles. In order to customize the UI.
I have not found any module for this.
Answer: One of the ways is to simply change the menu type from MENU_LOCAL_TASK to MENU CALLBACK, and then simply create a menu item with the path.
Sample Code:
Cherry pick menu tabs and convert:
function MYMODULE_NAME_menu_alter(&$items) {
  $items['node/%node/view']['type'] = MENU_CALLBACK;
  $items['node/%node/edit']['type'] = MENU_CALLBACK;
}

Convert all at once
function MYMODULE_NAME_menu_alter(&$items) {
  foreach ($items as $key => $value) {
    if ($items[$key]['type'] == MENU_LOCAL_TASK) {
      $items[$key]['type'] = MENU_CALLBACK;
    }
  }
}

Comment: But in this way I must reconstruct every path. If I wanted to automatically do it?
Comment: @Daniele I have updated the answer check now if that works for you.


C# New Expression in LINQ

Question: I wrote a code and used LINQ for fun which shows Sum of even and odd numbers. My code is working well but i feel like i could do it much better than this
Click here for image.
<code>        static void Main(string[] args)
    {

        Func<int, int, IEnumerable<int>> NumberRange =
            (startPoint, endPoint) =>
            Enumerable
            .Range(Math.Min(startPoint, endPoint), Math.Abs(startPoint - endPoint) + 1);

        Func<double, double, bool> IsDivisible =
            (value, divisor) =>
                (value % divisor)
                .Equals(0);

        Action<IEnumerable<object>> DisplayItems =
            (data) =>
            {
                Console
                    .WriteLine(String.Join(Environment.NewLine, data.Select(n => n)));
            };

        Func<bool, string> GetState =
            (key) =>
                key.Equals(true) ? "even" : "odd";

        var query =
            NumberRange(1, 20)
                .GroupBy(item => IsDivisible(item, 2))
                .Select(group => new
                {
                    Type = GetState(group.Key),
                    Sum = group.Sum()
                })
                .Select(group => new
                {
                    Output = string.Format("Sum of {0} numbers is {1}", group.Type, group.Sum)
                }
                .Output
                );

        DisplayItems(query);

        Console
            .Read();

    }
</code>
Is there any optimization for new expression ? Thanks.
Comment: I think simple loops (or simple utility functions) would be more readible than this. This makes me fell just *"look, I can write linq"*
Comment: int odds = 0; int evens = 0; foreach(var val in Enumerable.Range(1, 20)) if(val % 2 == 0) evens += val; else odds += val; Agreed with Eser, Linq can be dangerous in performance terms, use it wisely.
Comment: Instead of doing these funcs, put all this stuff into proper extension methods or something.
Comment: I tested with stopwatch Func<> is faster than predicate method. I don't know how. Thanks for you advice @Gusman but my aim is improve my LINQ skills.
Comment: Ok, that's fair enough, maybe you should improve your answer so the people know you are doing this to improve your skills. A good optimization is to use compiled expressions: https://msdn.microsoft.com/en-us/library/bb345362%28v=vs.110%29.aspx
Comment: @JimGarrison Stack Overflow has no such off-topic reason. What you mean is that the question is [off-topic because there is no specific question](http://meta.codereview.stackexchange.com/q/5777).
Answer: Try this, it's simpler:
<code>    static void Main(string[] args)
    {

        int startPoint = 0, endPoint = 20;

        List<int> data = new List<int>();
        int i = startPoint;
        while (i <= endPoint)
        {
            data.Add(i);
            i++;
        }
        Console.WriteLine(string.Format("Sum of even numbers is {0} \r\n", data.Where(x => x % 2 == 0).Sum().ToString()));

        Console.WriteLine(string.Format("Sum of odd numbers is {0} \r\n", data.Where(x => x % 2 != 0).Sum().ToString()));

        Console.ReadLine();
    }
</code>
Comment: I thought .GroupBy is faster because you are checking twice numbers. It can be slow down speed.

C# New Expression in LINQ


Hide Admin Toolbar in iFrame

Question: Is it somehow possible within Drupal 8 to hide the Admin Toolbar when the site is loaded within an iFrame? Like e.g. passing an argument? :-)
I thought about using some sort of preprocess on the page that is getting rendered within the iFrame, but this will not work since the html is cached by Drupal.
Also I thought about doing it within Javascript, but I do not want to include a javascript file on every page but default.
Maybe someone knows a hook_() which will allow me to manipulate the css but is not getting cached?
Comment: can you use a different theme for admin/user? https://www.drupal.org/project/toolbar_visibility
Comment: No, since this is an implementation for a contrib module, I do not want to force the users to install another theme.
Answer: I would use a similar approach as @Hudri and access the site as https://www.mysite.com?is_iframe=true.
Then, add a class to the body tag if the request option is there:
/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_html(&$variables) {
  $is_iframe = \Drupal::request()->query->get('is_iframe');
  if ($is_iframe === 'true') {
    $variables['attributes']['class'][] = 'hide-admin-toolbar';
  }
}

If I remember correctly, Drupal will regenerate the HTML when you access https://www.mysite.com?is_iframe=true vs https://www.mysite.com.

References:

https://drupal.stackexchange.com/a/207046/56157
https://drupal.stackexchange.com/a/210379/56157
Comment: Great solution! I assume you're using CSS to hide the toolbar. That can get a bit gnarly if you're also using admin_toolbar. Another option would be to prevent it from rendering at all, e.g.:

`if ($is_iframe === 'true') { if (isset($variables['page_top']['toolbar'])) { unset($variables['page_top']['toolbar']); }}`
Answer: This should be doable with a cache context:
Drupal core already provides a cache context
url.query_args
which can be used for your query parameter, e.g. an URL
https://www.mysite.com?is_iframe=true
would be a cache context
\Drupal::service('cache_context.url.query_args')->getContext('is_iframe');
AFAIK the cache_context url.query_args is already enabled by default in Drupal core, so you only need to add this cache context to the render array in an appropriate preprocess function.
Note that cache contexts generally do not work with Internal Page Cache module!
For production you should finetune this with a more specific, custom cache-context url.query_args:my_query_param to limit unnecessary cache contexts (dumb bots could trigger a gazillion cache context calculations otherwise)

Hide Admin Toolbar in iFrame


Which font is used for text in Lilypond?

Question: Which font is used for the \sectionMark in Lilypond?

The \sectionMark is defined simply as a formatted text:
sectionMark =
#(define-music-function (parser location text) (markup?)
   #{
     \mark \markup { \box { \bold #text } }
   #})

The screenshot is from a Windows machine.
Edit: I have just ran #(ly:font-config-display-fonts) which showed all the config locations and the fonts available. I'm still not sure which exact font is used, though.
Can this be deciphered from a generated PDF?
Comment: do you mean `\sectionLabel`?
Comment: \mark lets you do that too, e.g., \mark 3
Comment: Not really related to the question, but I don't understand why you don't just use `\mark \default`, which lets LilyPond pick the next letter automatically. If you want boxed rehearsal marks, you can select that as a style option with `\layout { \context { \Score rehearsalMarkFormatter = #format-mark-box-letters } }` (replace `rehearsalMarkFormatter` with `markFormatter` for LilyPond ≤ 2.23.6).
Comment: Also, the `parser location` part is unnecessary in reasonably recent versions and more or less deprecated.
Comment: @ElementsinSpace, thank you for the tip. This is a custom instruction, true! I've updated the question.
Comment: @ABOUSAMRAJean, good questions! :) I have probably found a sample somewhere at the time I was looking to create a sheet. Then have saved that into a separate file, where the mark is defined, and have used it ever after.
I don't use default because I need control of the marks. They repeat afterwards so this seemed more straightforward to me.
Answer: The same font as Lilypond uses for everything else. If you look at https://lilypond.org/doc/v2.23/Documentation/notation/fonts (this is the v2.23 documentation, change this to the version you use) you can see what fonts Lilypond uses by default:

C059, Century SchoolBook URW, Century Schoolbook L, TeX Gyre Schola,
DejaVu Serif, …, serif

So Lilypond tries to find a glyph first in URW C059 (which ships with it), then in Century SchoolBook URW, then in Century Schoolbook L, then in TeX Gyre Schola, then in DejaVu Serif. At some point Lilypond defaulted to TeX Gyre Schola as first option, which is an opentype font created from URW's original postscript fonts release. With URW rereleasing them as opentype fonts Lilypond changed their defaults.
Short Answer: It is some verion of Century Schoolbook.
Comment: If you are using an unstable (2.23) version from the official website, you can compile with `-dbackend=cairo` to get the same fonts (edit: in SVG). Beware though, this is experimental, not enabled in all Linux distros, and doesn't support output-attributes.
Comment: Thank you for the explanation! I have just found the config files but was/am still unsure about which *exact* font was used. :) According to the generated PDF, it is probably C059. The confusion is caused by a different rendering when the same font used in an SVG.
Comment: OK, finally got it. It is indeed C059 Bold.
Answer: To add some details to @Lazy's answer, the command #(ly:font-config-display-fonts) can be used to display configs and paths.
The first config file listed, 00-lilypond-fonts.conf, has these defined:
<family>LilyPond Serif</family>
<prefer>

  <family>C059</family>
  <family>Century SchoolBook URW</family>
  <family>Century Schoolbook L</family>

  <family>TeX Gyre Schola</family>

<family>DejaVu Serif</family>

  <family>Noto Serif CJK JP</famliy>
  <family>Noto Serif JP</family>
</prefer>
<default>

  <family>serif</family>
</default>


Node.js - searching for the "util" module; identify core modules

Question: I'm really a big fan of Swagger's node module, but one thing is driving me crazy:
The sample app contains the following line (api/controller/hello_world.js):
var util = require('util');

But I just can't find this module. I tried to

list it with npm list but nothing
search for it with Spotlight (util.js)

My question is: How can I list the actually loaded modules in nodejs?
Answer: util is part of the node.js distribution: https://nodejs.org/api/util.html
Comment: thank you, but mklement0's answer is general. thanks anyway.
Answer: TimWolla's answer solves your particular problem with respect to the util module.
As for the more generic question:

How can I list the actually loaded modules in nodejs?

This answer tells you how to list the full filenames of currently loaded non-core modules (spoiler alert: Object.keys(require.cache).
For core modules - modules that come with Node.js itself, such as util - there is no way that I know of that tells you which ones are loaded, but given that they're core, they may all implicitly be loaded, for all we know (and should care).
That said, to test if a given module is a core module, you can use require.resolve(), which returns the input module name as-is (rather than a full filename) in the case of core modules; e.g.:
require.resolve('util') // -> 'util', i.e. NOT A PATH -> core module

Note: When require.resolve() returns a filesystem path, the implication is merely that the module is non-core and can be located; it does not tell you whether or not that module is currently loaded (use require.cache for that).


Do clouds charge upon the storage usage or processing power or both?

Question: I am interested to know if I want to deploy my Kubernetes cluster on a cloud service like AWS, do they charge upon the storage my application uses or the processing power it uses or both?
Is there any simple formula to get an idea about how do they charge?
For example which one is better, using more storage but less processing power or vice versa?
Comment: What about going to the clouds and reading their payment basics? It is not like i.e. Microsoft does not have even calculators for every service on their website. AWS must have something similar.
Answer: AWS charges you for CPU / processing, memory, storage, and bandwidth. It depends on the service though. You can use Elastic Kubernetes service, EC2 and install K8S, run ECS, etc. You can use "serverless" fargate containers where you don't manage the instance, or EC2 instances.
To estimate your costs try the AWS price calculator.
Comment: You should benchmark your workload.
Comment: There is no rule of thumb to say using more CPU or memory is more beneficial compare to using more storage for example?


Can you compare AIC values as long as the models are based on the same dataset?

Question: I am doing some forecasting in R using Rob Hyndman's forecast package. The paper belonging to the package can be found here.
In the paper, after explaining the automatic forecasting algorithms, the authors implement the algorithms on the same data set. However, after estimating both an exponential smoothing and ARIMA model they make a statement I do no understand (on page 17):

Note that the information criteria are not comparable.

I thought that an advantage of using AIC for model selection is that we can compare AIC values from different models, as long as they are estimated using the same data set. Is this incorrect?
This matter is of particular interest to me, as I was planning on combining forecasts from different model classes (e.g. exponential smoothing and ARIMA) using so called Akaike weights (see Burnham and Anderson, 2002, for discussion on Akaike weights)
References

Burnham, K. P., & Anderson, D. R. (2002). Model selection and multi-model inference: a practical information-theoretic approach. Springer Verlag.
Answer: The two models treat initial values differently. For example, after differencing, an ARIMA model is computed on fewer observations, whereas an ETS model is always computed on the full set of data. Even when the models are equivalent (e.g., an ARIMA(0,1,1) and an ETS(A,N,N)), the AIC values will be different.
Effectively, the likelihood of an ETS model is conditional on the initial state vector, whereas the likelihood of a non-stationary ARIMA model is conditional on the first few observations, even when a diffuse prior is used for the nonstationary components.
Comment: Thank you! That clears up more than a few things. Loving the forecast package btw!


What is a 7th chord and why is it important?

Question: What is a 7th chord and why is it important?   I keep seeing it over and over again and I don't understand why it's important?
Comment: A little more information is needed to give a good answer. Do you know what "intervals" are? And do you know what the "root" of a chord is?
Comment: In addition to the above comment, it would help to know if you are asking about 7th chords in general (there are a variety of different ones) or a specific 7th chord.
Answer: They sound cool for one.  But there is more to it than that.
The "7th" chord, also called dominant 7th, is the following set of notes (1, 3, 5, b7) relative to the Major scale.  For example a C7 = (C, E, G, Bb).
In any key a 7th chord occurs naturally on the 5th degree.  If you take the notes (5, 7, 9, 11) or (5, 7, 2, 4) from the major scale of the key signature this is a 7th chord.  We denote it V7 to specify that its root is on the 5th degree.
For example, in the Key of C there is a 7th chord on G consisting of the following notes (G, B, D, F).
Where it arises is in chord progressions and specifically the authentic cadence, which is the movement V7 --> I, or in our example G7 --> C.  This has the strongest sense of completion of any chord change.  Within this movement there are 2 half steps moving in opposite direction, 7 --> 8 and 4 --> 3.  The interval (7, 4) or (4, 7) is a diminished 5th and the interval (3, 8) is a minor 6th, and (1, 3) is a major third.  This is the prime example of resolving dissonance into consonance.
For this reason it is one of the most important chords in Western harmony theory.  If you analyze oodles of classical music you will find V7 --> I all over the place.  There are other cadences like IV --> I, etc.  But V7 --> I is considered the strongest.
There are other 7th chords.  But the term X7 is reserved for the dominant 7th chord (1, 3, 5, b7).  You can put a maj or min 7 on any triad.  Examples are XMaj7 = (1, 3, 5, 7), Xmin7 = (1, b3, 5, b7), Xmin7(b5) = (1, b3, b5, b7), Xmin(Maj7) = (1, b3, 5, 7), etc.
The "7th" chord is used very often in the Blues where it likely occurs on every degree,
I7 IV7 I7 I7
IV7 IV7 I7 I7
V7 IV7 I7 V7
Comment: Sometimes you may also see 7th chord inversions, e.g. G/F (G over base F) is actually an inversion of G7, (F, G, B, D) instead of (G, B, D, F), which also sound great before the I chord.
Answer: Chords in Western music are usually built from thirds. We start on one note of a scale (the root of the chord), go up a third and add that as the next note (the third of the chord), then go up another third and add that as the next note (the fifth of the chord)...
...and the most commony-mentioned kinds of chords, called 'triads', stop there, with three notes. Standard major and minor chords are examples of these.
...but you can keep going up: go up another interval of a third (from the fifth) and you end up adding the seventh, making a seventh chord. And you can add a ninth (making a ninth chord), eleventh... and so on.
ggcg's answer contains some excellent points about seventh chords, but perhaps one useful way of thinking about them is that there isn't really anything super special about seventh chords; they're simply the kind of chord that adds one more third than the triad, but one less than a ninth chord.


How to measure bandwidth within the last 15 minutes?

Question: I would like to log my bandwidth into a database and find out when my windows server 2003 is being used the most.
I want to feed the database with the bandwidth passed from the last feed (let's say it's 15 minutes).
I know that the netstat -e command returns the bandwidth passed since interface's start.
Is there a way to somehow reset that counter without disabling and reenabling the interface?
If not, is there a better way than caching the last sample and calculating the difference each time?
I'm scripting in python if it's related.
Answer: With some smarts, the built in Windows Performance Monitors (perfmon) can do this.
Basically, if you set up Windows Performance Monitors to log bytes/sec on the interface into an SQL database, you can then graph that over a period of time - any period of time you choose, assuming the logging was running then.
That's basically what most central monitoring systems do. I can go back over the past 12 months and see how much bandwidth went in/out of our database server down to uselessly small increments.
Answer: One idea that comes to mind is to use WMI to query the Network Interface.  Since I am not familiar with python a quick search online seems to indicate there is a Python WMI module that will let you query WMI from within Python directly.  Querying WMI can be daunting.
There is a small .vbs example here http://msdn.microsoft.com/en-us/library/windows/desktop/aa394595(v=vs.85).aspx that should get you started.  If you can figure out how to do it in python you should be all set and have access to more info than you know what to do with.  I think the example you are looking for will be the one titled "...get information about network adapters without also retrieving information about things like RAS and VPN connections?".


Type coercion with Java generics

Question: Here I have the following code:
public final class Generics {
    private Generics() {}

    public static <T> T unchecked(Object obj) {
        return (T)obj; //unchecked cast warning
    }

    public static void main(String[] args) {
        //correct
        ArrayList<String> str = new ArrayList<String>();
        str.add("Hello");
        str.add("World");
        System.out.println(str);

        //"correct" - not type safe at all but due to type erasure this is almost legal
        ArrayList<Object> obj = Generics.<ArrayList<Object>>unchecked(str);
        obj.add(1);
        System.out.println(obj);

        //obviously wrong but still compiles (ClassCastException at runtime)
        Exception except = Generics.<Exception>unchecked(str);
        System.out.println(except);
    }
}

Normally a cast of the form ArrayList<Object> obj = (ArrayList<Object>)str would be a fatal compile error because that would violate the expectations of the use of that list. (you could insert objects that aren't strings into a string-only list)
What is the "unchecked" warning in this scenario, and how is the use of the unchecked() method different from casting the reference directly? How does this bypass the compiler's type checking?
Answer:
What is the "unchecked" warning in this scenario

Unchecked casts are simply casts which don't actually result in a checkcast instruction in the bytecode.
public static <T> T unchecked(Object obj) {
    return (T)obj; //unchecked cast warning
}

Here, it's an unchecked cast because the erasure of T is Object, so it's effectively a no-op, because obj is already an Object.
But the pernicious thing is that there is a checked cast inserted at the call site:
Exception except = Generics.<Exception>unchecked(str);
               // ^ cast here!

Upon erasure, the code that is effectively executed is:
Exception except = (Exception) Generics.unchecked(str);

and this fails with a ClassCastException. But you don't get warned about that, because the method's return type says that this will be safe, and so the compiler trusts that it is safe at the call site.
There is no way at the call site to know that the unchecked method is doing something dangerous. In fact, the only thing it could do which is safe would be to return null. But the compiler doesn't consider whether it is doing this or not: it simply takes the unchecked method's claim at face value.

how is the use of the unchecked() method different from casting the reference directly?

It's not, really. The only difference is that you're implicitly casting via Object. So whilst this doesn't compile:
Exception except = (Exception) str;

this does:
Exception except = (Exception) (Object) str;

and would fail at compile time with the same ClassCastException.
Answer:
Normally a cast of the form ArrayList<Object> obj = (ArrayList<Object>)str would be a fatal compile error because that would violate the expectations of the use of that list.

That cast is a compile error because ArrayList<String> is not a sub-type of ArrayList<Object> - it is the same compilation error you get when casting a Double to String.
You can actually avoid using the unchecked method by using instead
  // ArrayList<String> to ArrayList (raw) is legal
  ArrayList<Object> obj = (ArrayList<Object>)(ArrayList) str;
  // you can also cast to an interface-
  // at runtime, str could as well extend that interface!
  // and then Runnable can be downcasted to Exception
  // obviousy wrong, but still legal
  Exception except = (Exception)(Runnable)(str);

Casting to an interface (Runnable) which is not a supertype of ArrayList is legal, because we could very well have a class which extend ArrayList and implements Runnable. (though it would be a strange class..)
This type of casting is a "Narrowing reference conversion", as defined in JLS, 5.1.6
Comment: It's worth mentioning a bit more clearly why you can cast to an interface even when the class doesn't implement that interface. I can't really see it in the comment :) Pull it out to plain text, rather than putting it in code.

Type coercion with Java generics


Probability of rolling a sum of $9$ with $6$ dice

Question: Like in topic, you have 6 dice. You sum their values. What is the probability you get 9? How do I calculate it?
Comment: $$\frac{\text{number of outcomes where the sum of the dice is $9$}}{\text{total number of possible outcomes}}$$
Comment: But How Can I calculate number of outcomes?
Comment: I'm ashamed to admit that these sorts of problems always make me second-guess myself due to the following concern:  Suppose we have numbered the dice $1-6$.  Let's say in first scenario, all dice come up $3$ except die $\#6$.  In the second scenario, all dice come up $3$ except die $\#2$.  Are these scenarios distinct?  I.e. should the dice be considered "distinguishable"?  Would it even matter as long as we are consistent?--I.e. both the total number of possible outcomes *and* the total number of outcomes with a given hypothesis would increase, possibly proportionally.
Comment: @KajHansen: I'd say yes, since the question actually asks for the probability, rather than the number of ways.  If you didn't consider them distinguishable, the different ways wouldn't be equiprobable in general, and then there's no benefit to counting the number of ways (as far as eventually computing the probability is concerned).
Comment: For example, for two dice, we have 2 (probability is 2/36), 3 (3/36) for 3 dice we 3 (probability is 1/216), what if we have 6 dice and we're looking for 9 (x/46656)? How Can I calculate x?
Answer: Let's assume the dice are six-sided and distinct (each of a different color, say).  Then there are $6^6$ possible outcomes in the sample space.  Let $x_k$ be the outcome on the $k$th die.  Then
$$x_1 + x_2 + x_3 + x_4 + x_5 + x_6 = 9 \tag{1}$$
Equation 1 is an equation in the positive integers subject to the restriction that $x_k \leq 6$ for $1 \leq k \leq 6$.  Notice that if $x_k > 6$ for some $k$, then the sum is at least $7 + 5 = 12 > 9$, so we do not need to worry about that restriction (as Brian Tung demonstrated in his answer).
A particular solution to equation 1 corresponds to the insertion of addition signs in five of the eight spaces between successive ones in a row of nine ones.  For instance,
$$1 1 + 1 + 1 1 + 1 + 1 + 1 1$$
corresponds to the outcome $x_1 = 2$, $x_2 = 1$, $x_3 = 2$, $x_4 = 1$, $x_5 = 1$, and $x_6 = 2$, while
$$1 1 1 + 1 1 + 1 + 1 + 1 + 1$$
corresponds to the outcome $x_1 = 3$, $x_2 = 2$, $x_3 = x_4 = x_5 = x_6 = 1$. Hence, the number of solutions of equation 1 is the number of ways we can select five of the eight spaces between successive ones in a row of nine ones, which is $\binom{8}{5}$.  Hence, the probability of obtaining a sum of $9$ when six six-sided dice are thrown is
$$\frac{\binom{8}{5}}{6^6}$$
Comment: In case others are not familiar with this technique: this is sometimes called the ["stars and bars"](https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)).
Answer: General approach. There aren't that many ways to get $9$ from six dice.  (I assume these are ordinary six-sided dice.)  Up to reordering, there are only the following three combinations:
$$
1, 1, 1, 1, 1, 4
$$
$$
1, 1, 1, 1, 2, 3
$$
$$
1, 1, 1, 2, 2, 2
$$
Calculate the number of ways to get each of these (including their reorderings), and divide by $6^6$ to obtain the probability.  You should obtain the same value as Matthew Conroy in his answer, hopefully with a lot less computation.  (Generating functions are a convenient way to obtain all of the probabilities at once, though.)
Comment: @MatthewConroy: Oh, well, it's certainly up to you, but I think multiple different answers is always better than a single answer.  (Witness N.F. Taussig's combinatoric symbol approach.)  And although I might quibble about the typesetting (I'm not sure, honestly), I wouldn't personally delete the answer because of that.  But again, it's ultimately up to you.
Comment: Just so you know: I deleted my answer. Cheers!
Comment: @MatthewConroy: Why?  It's a reasonable approach, and more general.  I would prefer it if the desired total were, say, $20$.
Comment: Oh, I just figured that if you went to the trouble to post a different solution that your solution was all that was needed.  Plus someone complained about some of my typesetting, so I just figured the easiest thing to do was delete it.  Cheers!


Fluentd not able to upload logs to Elasticsearch

Question: I have downloaded the elasticsearch & kibana on my Ubuntu18.04 machine. Both of them are running fine and I can access them. Below is the elasticsearch details:
{
  "name" : "TX-G1-000",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "AobC_iiNSyyNftYl3pUJ7w",
  "version" : {
    "number" : "7.14.1",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "66b55ebfa59c92c15db3f69a335d500018b3331e",
    "build_date" : "2021-08-26T09:01:05.390870785Z",
    "build_snapshot" : false,
    "lucene_version" : "8.9.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

I have also installed Fluentd and its service td-agent is running fine.
● td-agent.service - td-agent: Fluentd based data collector for Treasure Data
   Loaded: loaded (/lib/systemd/system/td-agent.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2021-09-20 21:18:12 IST; 7min ago
     Docs: https://docs.treasuredata.com/display/public/PD/About+Treasure+Data%27s+Server-Side+Agent
  Process: 5486 ExecStop=/bin/kill -TERM ${MAINPID} (code=exited, status=0/SUCCESS)
  Process: 5491 ExecStart=/opt/td-agent/bin/fluentd --log $TD_AGENT_LOG_FILE --daemon /var/run/td-agent/td-agent.pid $TD_AGENT_OPTIONS (code=exited, status=0/SUCCESS)
 Main PID: 5498 (fluentd)
    Tasks: 12 (limit: 4915)
   CGroup: /system.slice/td-agent.service
       ├─5498 /opt/td-agent/bin/ruby /opt/td-agent/bin/fluentd --log /var/log/td-agent/td-agent.log --daemon /var/run/td-agent/td-agent.pid
       └─5501 /opt/td-agent/bin/ruby -Eascii-8bit:ascii-8bit /opt/td-agent/bin/fluentd --log /var/log/td-agent/td-agent.log --daemon /var/run/td-agent/td-agent.pid --under-supervisor

Sep 20 21:18:11 TX-G1-000 systemd[1]: Starting td-agent: Fluentd based data collector for Treasure Data...
Sep 20 21:18:12 TX-G1-000 systemd[1]: Started td-agent: Fluentd based data collector for Treasure Data.

Below is my td-agent.conf file:
<source>
  @type tail
  path /home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_health.json
  pos_file /home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_health.json.pos
  format json
  time_format %Y-%m-%d %H:%M:%S
  tag health01
</source>

<source>
  @type tail
  path /home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_cycle.json
  pos_file /home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_cycle.json.pos
  format json
  time_format %Y-%m-%d %H:%M:%S
  tag cycle01
</source>

<match health*>
  @type elasticsearch
  hosts http://localhost:9200/
  index_name health_skl_device
  type_name health
</match>

<match cycle*>
  @type elasticsearch
  hosts http://localhost:9200/
  index_name cycle_skl_device
  type_name cycle
</match>

When running the td-agent, below are its logs:
2021-09-20 21:18:12 +0530 [info]: parsing config file is succeeded path="/etc/td-agent/td-agent.conf"
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-elasticsearch' version '5.1.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-elasticsearch' version '5.0.5'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-flowcounter-simple' version '0.1.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-kafka' version '0.16.3'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-prometheus' version '2.0.1'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-prometheus_pushgateway' version '0.1.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-record-modifier' version '2.1.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-rewrite-tag-filter' version '2.4.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-s3' version '1.6.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-sd-dns' version '0.1.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-systemd' version '1.0.5'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-td' version '1.1.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-utmpx' version '0.5.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluent-plugin-webhdfs' version '1.4.0'
2021-09-20 21:18:12 +0530 [info]: gem 'fluentd' version '1.13.3'
2021-09-20 21:18:12 +0530 [info]: using configuration file: <ROOT>
  <source>
    @type tail
    path "/home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_health.json"
    pos_file "/home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_health.json.pos"
    format json
    time_format %Y-%m-%d %H:%M:%S
    tag "health01"
    <parse>
      time_format %Y-%m-%d %H:%M:%S
      @type json
      unmatched_lines
      time_type string
    </parse>
  </source>
  <source>
    @type tail
    path "/home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_cycle.json"
    pos_file "/home/user/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_cycle.json.pos"
    format json
    time_format %Y-%m-%d %H:%M:%S
    tag "cycle01"
    <parse>
      time_format %Y-%m-%d %H:%M:%S
      @type json
      unmatched_lines
      time_type string
    </parse>
  </source>
  <match health*>
    @type elasticsearch
    hosts "http://localhost:9200/"
    index_name "health_skl_device"
    type_name "health"
  </match>
  <match cycle*>
    @type elasticsearch
    hosts "http://localhost:9200/"
    index_name "cycle_skl_device"
    type_name "cycle"
  </match>
</ROOT>
2021-09-20 21:18:12 +0530 [info]: starting fluentd-1.13.3 pid=5491 ruby="2.7.4"
2021-09-20 21:18:12 +0530 [info]: spawn command to main:  cmdline=["/opt/td-agent/bin/ruby", "-Eascii-8bit:ascii-8bit", "/opt/td-agent/bin/fluentd", "--log", "/var/log/td-agent/td-agent.log", "--daemon", "/var/run/td-agent/td-agent.pid", "--under-supervisor"]
2021-09-20 21:18:13 +0530 [info]: adding match pattern="health*" type="elasticsearch"
2021-09-20 21:18:13 +0530 [warn]: #0 Detected ES 7.x: `_doc` will be used as the document `_type`.
2021-09-20 21:18:13 +0530 [info]: adding match pattern="cycle*" type="elasticsearch"
2021-09-20 21:18:13 +0530 [warn]: #0 Detected ES 7.x: `_doc` will be used as the document `_type`.
2021-09-20 21:18:13 +0530 [info]: adding source type="tail"
2021-09-20 21:18:13 +0530 [info]: adding source type="tail"
2021-09-20 21:18:13 +0530 [info]: #0 starting fluentd worker pid=5501 ppid=5498 worker=0
2021-09-20 21:18:13 +0530 [info]: #0 following tail of /home/thingtrax/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_cycle.json
2021-09-20 21:18:13 +0530 [info]: #0 following tail of /home/thingtrax/PycharmProjects/Td-Agent/logs/TX-S2-SKL-001_health.json
2021-09-20 21:18:13 +0530 [info]: #0 fluentd worker is now running worker=0

I do not see any error logs but not sure why its not able to upload data. I try to create index pattern, it doesnt matches on Kibana. Can anyone please help me in debugging this issue. Thanks
Logs after adding debug
2021-09-23 07:41:50 +0530 [debug]: 'host localhost' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'host: localhost' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'index_name health_skl_device' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'index_name: health_skl_device' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'template_name ' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'template_name: ' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'logstash_prefix logstash' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'logstash_prefix: logstash' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'logstash_dateformat %Y.%m.%d' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'logstash_dateformat: %Y.%m.%d' has timestamp placeholders, but chunk key 'time' is not configured
2021-09-23 07:41:50 +0530 [debug]: 'logstash_dateformat %Y.%m.%d' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'logstash_dateformat: %Y.%m.%d' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'deflector_alias ' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'deflector_alias: ' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'application_name default' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'application_name: default' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'ilm_policy_id logstash-policy' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'ilm_policy_id: logstash-policy' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: Need substitution: false
2021-09-23 07:41:50 +0530 [debug]: 'host_placeholder localhost' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'host_placeholder: localhost' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'host localhost' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'host: localhost' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'index_name cycle_skl_device' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'index_name: cycle_skl_device' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'template_name ' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'template_name: ' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'logstash_prefix logstash' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'logstash_prefix: logstash' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'logstash_dateformat %Y.%m.%d' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'logstash_dateformat: %Y.%m.%d' has timestamp placeholders, but chunk key 'time' is not configured
2021-09-23 07:41:50 +0530 [debug]: 'logstash_dateformat %Y.%m.%d' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'logstash_dateformat: %Y.%m.%d' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'deflector_alias ' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'deflector_alias: ' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'application_name default' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'application_name: default' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: 'ilm_policy_id logstash-policy' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'ilm_policy_id: logstash-policy' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: Need substitution: false
2021-09-23 07:41:50 +0530 [debug]: 'host_placeholder localhost' is tested built-in placeholder(s) but there is no valid placeholder(s). error: Parameter 'host_placeholder: localhost' doesn't have tag placeholder
2021-09-23 07:41:50 +0530 [debug]: No fluent logger for internal event

Comment: Since you're running ES 7.14, you need to remove the `type_name` property in the output, as it's not needed anymore (see the two warnings). It's probably not the issue, but it will be more correct. As mentioned by Yuri you should increase the log level so we can get more insights
Comment: add `@log_level debug` to the match configs
Comment: @YuriSh I have added more logs after adding debug log level
Comment: @Val I have removed type name and added more logs
Answer: I think you have incorrect match tags. Nowhere in documentation does it mention that asterisks can be used that way, they should either take a place of a whole tag part or be used inside a regular expression. According to this section, Fluentd accepts all non-period characters as a part of a tag. So in fact health* is a valid name for a tag, fluentd expects exact matches of that string.
You should try using /health.*/ and /cycle.*/ instead.
Better yet, you can go the intended way, change the tag names to health.01 and cycle.01 and use health.** and cycle.** for matching.
Comment: @SAndrew no, you still need to use `health.**`.

`.**` at the end matches any amount of *tag parts* (zero or more). Tag parts are everything in-between dots. `health.EAB2` has tag parts `health` and `EAB2`
Comment: That also explains why it hasn't reported any errors.
Comment: Why does the info log state `adding match pattern="health*" type="elasticsearch"` then?
Comment: @Val `health*` is a valid matching "pattern", but only one tag can satisfy it - `health*` letter for letter. It will match `health*` and won't match `health01`.
Comment: Thank you for the explanation, I'm not a Fluentd expert, but glad I learned something new ;-)
Comment: What if I have tag as `health.EAB2`, `health.ECB2`, `health.7CDE` so as per your suggestion, I should use match tag has `health.****` so that it matches data from all the 3 input health.?
Comment: @YuriSh Well I don't exactly agree on this, if the tag is `health01` I can use `health*` in match pattern. `health*` means anything after health will be matched and pushed to elasticsearch. But anyways thanks for your help. I have resolved the problem. Issue was not in fluentd configuration file. It was actually on how I was saving my `TX-S2-SKL-001_health.json`. I will answer to update


How do I create a new variable?

Question: I want to use a new variable in a view using global PHP. Between the available variables, I have $row->my_field, and I want to put its value in a new variable.
$new = $row->my_field;
echo $new

I'm using this code in Output Code. I get the following error:

Syntax error, unexpected 'echo' (T_ECHO) ...

I cannot even use array_unique().
Is it possible to add a new variable? and Is it possible to use a function like array_unique()?
Answer:
Is it possible to add a new variable?

YES

Is it possible to use a function like array_unique()?

Yes, as long as you have an array to pass as a parameter.
PS: You shouldn't be using Views PHP to begin with; you should create a template file for your view and add the PHP code there.
What are the downsides of using PHP Filter code in blocks, nodes, views-args, etc?
Comment: Thank you. I have a problem about array_unique function, May you see it? http://drupal.stackexchange.com/questions/214829

How do I create a new variable?


Euler formula, polyhedron with a hole

Question: I'd like to ask help for this question. I know that I need to have a little more concept on what kind of polyhedra that Euler's formula is valid.
Choose the false alternative:
a) F = 12
b) V = 20
c) E = 30
d) Euler's formula F + V - E = 2 applies
e) All above are true
Actually, by looking at this picture we can conclude that E is correct, since all of them seem to be true. However, shouldn't this formula be F + V - E = -2, since the genus is 2 ?
Comment: They must have made a typo.
Comment: If one among a-d is false, then e is false too. But if a-d are all true, then e) is true and can't be a "false alternative".
Comment: Actually in this exam it is understood that the "False" is valid for letters a-d. We should not interpret this so logically for letter e. The question is to be understood as: Choose the false alternative among a-d or e if all of them are true.
Answer: The number of faces is listed as 12.  There are ten vertical faces and two "horizontal" faces (namely, top level and bottom level of the polyhedron).  However, the latter pair are not admissible as faces because a face has to be a convex polygon for the formula to apply.
Comment: So, they want the falsa alternative. Should it be D ?
Comment: Depends on how you define a face.
Answer: See: https://en.wikipedia.org/wiki/Polygon_with_holes#In_polyhedra
$\chi =V-E+F-\text{holes}=2(1-g)$
$V=20, E=30, F=12, H=4$ (2 faces each with 2 holes)
$\chi=20-30+12-4=-2=2(1-g)
\implies g=2$ so it's $2$-holed polyhedron.

Euler formula, polyhedron with a hole


Alfresco 5.1 CE: Deactivating __CheckInOut.exe and __ShowDetails.exe

Question: we intend to upgrade vom Alfresco 4.2f to Alfresco 5.1 CE and are currently testing, whether required features are available in the new version, too.
One stop point is the chance to deactivate the two files __CheckInOut.exe and __ShowDetails.exe which are created in every directory.
We managed to do this in 4.2f and according to the documentation of 5.1, all we have to do is to copy the directory of the subsystem "fileServers" to the directory of the new version.
We did this an had to deactivate e.g. some NFS instructions (which prooves that Alfresco is reading this directory). But although the required line are set as a comment in subsystems/fileServers/default/file-servers-context.xml:
<code><!--
                 <bean class="org.alfresco.filesys.repo.desk.CheckInOutDesktopAction">
                    <property name="name">
                       <value>CheckInOut</value>
                    </property>
                    <property name="filename">
                       <value>__CheckInOut.exe</value>
                    </property>
                 </bean>
                 <bean class="org.alfresco.filesys.repo.desk.JavaScriptDesktopAction">
                    <property name="name">
                       <value>JavaScriptURL</value>
                    </property>
                    <property name="filename">
                       <value>__ShowDetails.exe</value>
                    </property>
                    <property name="scriptName">
                       <value>alfresco/desktop/showDetails.js</value>
                    </property>
                    <property name="attributeList">
                       <value>anyFiles</value>
                    </property>
                    <property name="preprocess">
                       <value>copyToTarget</value>
                    </property>
                 </bean>
            -->
</code>
still every directory contains the two files.
Does anyone know how they are hidden/deactivated in the new version?
Thanks for any help or hint,
Stefan
Answer: I was able to answer the question myself:
With Alfresco 5.1 the files file-servers-context.xml and file-servers.properties have to be saved in the directory /opt/alfresco-community/tomcat/shared/classes/alfresco/extension/subsystems/fileServers/default/default, then the two exe files will disappear.
Regards,
Stefan


Bind 9.2 server refuses to resolve CNAME from sub-zone

Question: I've got an old master nameserver running Bind 9.2 and a newer slave running 9.8. Right now we've got a project going on where we're essentially splitting a cloud in two and we're using subzones and CNAMEs to keep our services running smoothly. However, the cranky old 9.2 server doesn't seem to want to resolve the CNAMEs to the subzone and returns REFUSED: recursion requested but not available. On the other hand the 9.8 server serves the requests just fine.
Disclaimer: I know these nameservers are horribly out of date, and even worse the one running 9.2's OS is waaaaay out of support as well, so I'm not likely to find a reputable package to upgrade it. The project immediately after this cloud split is rebuilding our DNS servers/services from scratch.
How can I get the older server to resolve these CNAMEs properly?
dig results
dig @ NS1 [Bind 9.2]
# dig foo.domain.com @ns1.domain.com

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.30.rc1.el6_6.3 <<>> foo.domain.com @ns1.domain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 5937
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;foo.domain.com.        IN      A

;; Query time: 116 msec
;; SERVER: 22.214.171.124#53(126.96.36.199)
;; WHEN: Fri Jul 31 16:18:36 2015
;; MSG SIZE  rcvd: 48

dig @ NS2 [Bind 9.8]
# dig foo.domain.com @ns2.domain.com

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.30.rc1.el6_6.3 <<>> foo.domain.com @ns2.domain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 59986
;; flags: qr aa rd; QUERY: 1, ANSWER: 2, AUTHORITY: 2, ADDITIONAL: 2
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;foo.domain.com.        IN      A

;; ANSWER SECTION:
foo.domain.com. 300 IN  CNAME   foo.sub.domain.com.
foo.sub.domain.com. 300 IN A     18.104.22.168

;; AUTHORITY SECTION:
sub.domain.com.  300     IN      NS      ns1.domain.com.
sub.domain.com.  300     IN      NS      ns2.domain.com.

;; ADDITIONAL SECTION:
ns1.domain.com.     30      IN      A       22.214.171.124
ns2.domain.com.     30      IN      A       126.96.36.199

;; Query time: 80 msec
;; SERVER: 18.104.22.168#53(184.108.40.206)
;; WHEN: Fri Jul 31 16:22:29 2015
;; MSG SIZE  rcvd: 161

Config
Below are the config files for the servers, trimmed down to the bare essentials.
NS1 [Bind 9.2]
options {
        recursion no;
        additional-from-auth no;
        additional-from-cache no;
        blackhole { bogon; };
        directory "/var/named";
        notify yes;
};
zone "domain.com" {
        type master;
        file "/var/named/domain.com.hosts";
        also-notify { 18.104.22.168; };
        notify yes;
};
zone "sub.domain.com" {
        type master;
        file "/var/named/sub.domain.com.hosts";
        also-notify { 188.8.131.52; };
        notify yes;
};

NS2 [Bind 9.8]
options {
        directory       "/var/named";
        recursion no;
        blackhole{ bogon; };
        dnssec-enable yes;
        dnssec-validation yes;
        dnssec-lookaside auto;
};
zone "domain.com" {
        type slave;
        masters { 22.214.171.124; };
        allow-transfer { 126.96.36.199; };
        file "/var/named/slaves/domain.com.hosts";
};
zone "sub.domain.com" {
        type slave;
        masters { 22.214.171.124; };
        allow-transfer { 188.8.131.52; };
        file "/var/named/slaves/sub.domain.com.hosts";
};

domain.com.hosts
$ORIGIN .
$TTL 300        ; 5 minutes
domain.com      IN SOA  ns1.domain.com. servers.domain.com. ( ... )
    NS      ns1.domain.com.
    NS      ns2.domain.com.
$ORIGIN domain.com.
sub NS ns1.domain.com.
sub NS ns2.domain.com.
foo CNAME foo.sub

sub.domain.com.hosts
$ORIGIN .
$TTL 300        ; 5 minutes
sub.domain.com   IN SOA  ns1.domain.com. servers.domain.com. ( ... )
    NS      ns1.domain.com.
    NS      ns2.domain.com.
$ORIGIN sub.domain.com.
foo A 184.108.40.206

Comment: Your question is too obfuscated for us to be able to tell you the problem, unfortunately. A status code of `REFUSED` means that ns1 does not consider itself authoritative for the domain. ns2 does, and answers properly; the status code is `NOERROR` and the warning about recursion is normal. Run your query with `+norecurse` to remove the warning. We cannot tell you why the server considers itself authoritative without the unredacted config. There is obviously something wrong and it is likely in the redacted text.
Comment: *Recursion requested but not available* should simply lead to only available (authoritative and already cached) data being used in answering the query. Query response type REFUSED means just that: the server is refusing to tell you anything. I don't remember off the top of my head, but double-check what the default values for `allow-query{};` is in the respective versions. Global and per zone. That's most likely the culprit here. Normally you want `allow-query { any; };` at least on all authoritative zones, with possibly a more restrictive setting globally.
Comment: You can try checking the logs on ns1. Make sure there is not a syntax error that is preventing the zone from loading.
Comment: [Please do not redact the domain name in this question](http://meta.serverfault.com/questions/963/what-information-should-i-include-or-obfuscate-in-my-posts/6574#6574).  If you feel you absolutely must, then at least [do it properly](https://tools.ietf.org/html/rfc6761#section-6.5).
Answer: I tossed this question at some smart dudes on IRC and got the answer:
options {
    additional-from-auth yes;
    additional-from-cache yes;
}

Where both were explicitly set to no in my config.
http://www.zytrax.com/books/dns/ch7/queries.html#additional-from-auth

additional-from-auth and additional-from-cache control the behaviour when zones have additional (out-of-zone) data or when following CNAME or DNAME records. These options are for used for configuring authoritative-only (non-caching) servers and are only effective if recursion no is specified in a global options clause or in a view clause. The default in both cases is yes. These statements may be used in a global options or in a view clause. The behaviour is defined by the table below:

And then the table basically boils down to:

If they're not both set to yes the type of query referenced in this question is going to be refused more or less all the time.
Comment: That last sentence is so blatantly wrong in the context you're presenting it that I have to downvote this. Nothing personal. All `REFUSED` means is that 1) the server is not configured to provide recursion to the requesting IP address, and 2) the server does not consider itself authoritative for the domain that you are requesting. The `additional-from-*` options have nothing to do with `REFUSED`.
Comment: @AndrewB I've amended the answer somewhat, but it's only out of context if you completely neglect reading the actual question. I'd love to have included the table, but SO markdown doesn't allow for tables. Also, the `additional-from-*` options clearly *do* have everything to do with the `REFUSED` response in this case as they were preventing the server from looking up additional records from a different zone.
Comment: I've had to delete two prior versions of this comment, sorry for the spam. My final conclusion is that your answer still has nothing to do with the problem as presented, despite your strong conviction to the contrary. See answer below. I think I was premature in retracting the downvote but it's not worth bothering at this point. Good luck!
Answer: It's extremely difficult to troubleshoot DNS problems with obfuscated examples and we say this frequently. (as MadHatter already pointed out) When we're confronted with a non-sequitur, we basically have to assume that there's something that you're not showing us or that you've tainted the example due to mistranslation. Your comment seems to suggest that the context of your answer should be "obvious" to anyone who reads your Q&A, but that's demonstratively bunk.
This is supposedly the content of your domain.com zone on both servers:
$ORIGIN .
$TTL 300        ; 5 minutes
domain.com      IN SOA  ns1.domain.com. servers.domain.com. ( ... )
    NS      ns1.domain.com.
    NS      ns2.domain.com.
$ORIGIN domain.com.
sub NS ns1.domain.com.
sub NS ns2.domain.com.
foo CNAME foo.sub

Yet you're telling us that the requests for foo.domain.com are returning REFUSED on one of your servers?
# dig foo.domain.com @ns1.domain.com

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.30.rc1.el6_6.3 <<>> foo.domain.com @ns1.domain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: REFUSED, id: 5937
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;foo.domain.com.        IN      A

;; Query time: 116 msec
;; SERVER: 220.127.116.11#53(188.8.131.52)
;; WHEN: Fri Jul 31 16:18:36 2015
;; MSG SIZE  rcvd: 48

Sorry, no. That's a misconfiguration if you're presenting it accurately, as it should not be possible for the server to return that answer when that's the actual zone file loaded into memory. (assuming that it did load -- which we couldn't verify with a SOA query for obvious reasons)
REFUSED means that the server is rejecting the query outright because it's interpreting a query as a request for out of zone information. It doesn't matter what the target (right hand side) of your CNAME record is in this case; the left hand side is the only thing that matters. Even if the target is out of zone, that's fine, it just means that your server will provide the answer to the CNAME without providing the corresponding A record. (barring the case where the other zone is located on the same server, which should be the case here) That's still NOERROR though, not REFUSED. The presence of the recursion desired (rd) flag will have no influence on this behavior in an authoritative context either.
I understand that you want us to believe that your answer solves the question you presented us, but it doesn't. I can't speak to what else changed that might have fixed the issue for you, but your example configuration clearly indicates that this data should have been in-zone. The options you tweaked should have no influence on this. We can take your word that your changes have addressed the problem somewhere along the way, but this truly is a case of 1 + 1 = zucchini.
Please make sure the aa flag is present in the response from NS1, for your own sake.