xDebug shows up in command line "php -m" , but not in phpinfo()

Question: I am on windows 7, 64bit, with xampp 3.2.1 installed . I got my xdebug dll file through the xdebug.org wizard, and put it where the wizard told me to, C:\xampp\php\etc. Then I made sure to modify the correct (and as far as I'm aware only) php.ini file at C:\xampp\php\php.ini. This is the same ini that phpinfo() reports.
When I run php -m , I can see the xDebug extension listed twice, just as it should be. But going back to a phpinfo() output, the extension is not listed.
I've tried restarting my computer, apache. If I try to run this script to test if xdebug is working, it gives me a error

socket_bind(): unable to bind address [10048]:Only one usage of each socket address (protocol/network address/port) is normally permitted
Comment: `phpinfo()` will tell you exactly which .ini files are being processed. there's generally two of them: one for command line, one for SAPI (webserver). you probably have xdebug only in the CLI .ini file
Comment: But my phpinfo() says "loaded configuration file" : C:\xampp\php\php.ini . when I do "php --ini", there's only that one file
Answer: After hours of hair pulling... and a nap, I came across this config code and it somehow worked. Now that the extension is on firm ground, I can start carefully adding or removing features one at a time.
<code>zend_extension = "C:\xampp\php\ext\php_xdebug-2.2.5-5.5-vc11.dll" // whatever your file name is
xdebug.remote_autostart=on
xdebug.remote_enable=on
xdebug.remote_enable=1
xdebug.remote_handler="dbgp"
xdebug.remote_host= "localhost"
xdebug.remote_port=9000
xdebug.remote_mode=req
xdebug.idekey="netbeans-xdebug"
</code>
The root problem was a messed up php.ini file. The problem is that xampp's php.ini has some defaults listed there that we are told to uncomment by xdebug,netbeans, other online guides. Unfortunately, given the certain combinations of values, that just didn't work. This list of parameters definitely worked for me though.
Comment: Thanks. After hours of trying all kinds of configs, this one also worked for me (using Wamp 2.5).
Comment: Where do I have to add this in the phpini? Under the `[PHP]` tag?


Django - Custom admin save model

Question: I have two models: Page and a custom user model MyUser
These two models have each one a manytomanyfield:
class Page(models.Model):
    members = models.ManyToManyField(settings.AUTH_USER_MODEL)

class MyUser(AbstractUser):
    mypages = models.ManyToManyField(Page)
    objects = UserManager()

When I add a member to the members manytomanyfield via the admin interface, I would like to add the new attributed Page object to the user automatically in the mypages attribute, so I am trying to override the save method of the Page model in the admin.py:
class PageAdmin(admin.ModelAdmin):
    def save_related(self, request, form, formsets, change):
        super(ModelAdmin, self).save_related(request, form, formsets, change)
        if 'members' in form.changed_data:
        #And I am quite lost....

Is it a good idea? Should I do that in the "Page model custom save" method in my models.py file either doing it in the admin.py?
I tried to replace the #And I am quite lost.... part with ideas from:

Link1
Link2

Without any sucess!
Answer: This is completely mistaken. A many-to-many field is already double-ended. You don't need to define it on both ends. When you define a members field on Page, then MyUser will automatically get a page_set accessor which is the other end of the relation, and any page that adds a user to its members will automatically show up in the user's page_set. There is no need for any code.
Comment: Maybe I wasn't clear enough: you should **not define a mypages field at all**. The reverse accessor is called `page_set`, which is defined automatically.
Comment: Maybe I am misunderstanding but I have nothing like that. When I add a new `member` object to the `members` many-to-many field of a `page` object, the many-to-many `mypages` attribute of the user is not populated with the page object! :$
Comment: I just realized that I did not understand the use of a many-to-many field. Thank you. By the way , I am gonna to edit my question and simulate this mistake, or is it better to delete the whole thread?
Comment: No, don't delete the question, it may help other people in the future.

Django - Custom admin save model


How to delete invalid row from datagrid?

Question: Description of application structure:
Language is C# with WPF and MVVM pattern. View is basically a DataGrid for displaying some DataTable values (through ViewModel). User is allowed to add, edit and delete rows from the grid. Some value restrictions apply (no nulls, only numeric, etc...) due to database from where values are retrieved and later inserted back.
Data modifications can be made directly to DataGrid but there is also a separate dialog for editing and adding new rows. A delete button works in a way that ViewModel finds  selected DataGrid rows from DataTable, deletes them and changes are updated automatically to DataGrid as they should.
Problem:
So I'm having this problem where user attempts to insert invalid data to DataGrid and red exclamation mark appears to indicate that there is a problem with inserted data (validation error I guess?). If at this point user wishes to start over and selects invalid row for deletion, he is unable to delete that row as it does not exist in the model but only in DataGrid. Attempting to delete invalid DataGridRow directly from DataGrid throws an exception stating that DataGrid is bound to a Model and any modifications should be made there.
Finally question:
How to delete invalid DataGridRow which is not present in model?
Comment: If the invalid row is not present in the model then there's no way to delete it, but similarly, if it is not there, forcing the DataGrid to re-render the data should only show valid rows. You could try a DataGrid.Items.Refresh() - I'm not certain that this will work, but it's worth a try.
Comment: Thanks for reply. I tried this and got exception stating "'Refresh' is not allowed during an AddNew or EditItem transaction." Apparently invalid data causes Datagrid to get 'stuck' in editing state or something like that.
Comment: You could try calling CencelEdit() before the refresh. This *should* clear the edit mode, although with WPF, I have seen some pretty odd behaviour with DataGrids. I gave up on them in the end and rolled my own component using a list box and an object derived from a panel to represent each row.
Comment: Just a thought, did you try selecting the row and delete using the "DELETE" button?
Comment: @Alex: Tried calling CancelEdit() before refreshing. Same exception as before.
Comment: @ygoku: To be more precise, delete button I have implemented in View fires a command bound to ViewModel which has knowledge (through binding) about selected DataTable rows in DataGrid. As described, deletion works nicely unless selected row is not present in table.
Comment: Can you share some code to make it easier to visualise?
Answer: If you implement MVVM pattern then you don't have to do anything except linking changes in your observablecollection to data layer to connect it to DB.
Also you may define DataGrid as :
<DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding ActiveItem}" .../>

Then you may react to PropertyChanged events of Items and ActiveItem in your code, kind of
ActiveItem.PropertyChanged += ...

Hope it helps


Styling django widget in wizard form

Question: I am facing an issue with widgets in forms. I have 3 steps ( 3 forms ) in a django wizard and I want to style each field.
If I loop the forms to style each field separately it seems to work but, it doesn't work with the fields I have as widgets in my model ( they appear styled but the input is not recognized ).
For example, I have 2 radiobuttons in one form, and if I use type="checkbox" to style the field in the template, it doesn't work. The same with textarea fields, I can render a textarea but the form doesn't recognize the input.
Is there a way to style the widgets ?
{% for form in wizard.form.forms %}
{% for field in form %}
Message
<textarea class="form-control" rows="10" cols="10"
id="id_{{ field.name }}" value="{{ field.value }}"
onblur="if(this.value == '') { this.value='{{field.name}}'}"
onfocus="if (this.value == '{{field.name}}') {this.value=''}" > </textarea>

{{ field.help_text }}

{% endfor %}
{% endfor %}

That renders the widget field (widget=forms.Textarea) as a text area, but as de field is defined as a widget is the value isn't recognized by the form.
Answer: Adding widgets in forms.py is the best way to do so. Like so:
from django import forms
class CabModelForm( forms.ModelForm ):
    descr = forms.CharField( widget=forms.Textarea )
    class Meta:
        model = Cab

Start with this for your form:
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

Does your form worK? It should at least work with this minimal code. If not, you have an error somewhere in your views.py most likely.
Comment: I have that widget, but I cann't apply any style to it in a template. I have updated with the code. If I use the code I've added, I get a text area but not the input.
Comment: I'd say it has something to do with your javascript "onblur" and "onfocus".  the simplest way to test is just to put your form in the template as {{ form.as_p }} and see if it works from there.
Comment: printing directly the form with {{form}} or {{form.as_p}} works, but doing that I cannot put any style on the field.
Comment: you can wrap the form in a  and style it that way. other than that not sure. with javascript. good luck.

Styling django widget in wizard form


Place the same image on screen multiple times whenever button clicked

Question: when the user clicks on the button the same image will display again and again on multiple locations. I am using on touch listener to move images. that is working but I can't create multiple images with the same imageview or with for loop please help. This is the image I want to create multiple time
This is my xml
<code>      <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/main_html"
tools:context="com.incubers.signondoc.ui.HtmlActivity">

<Button
    android:id="@+id/save_edited"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:visibility="gone"
    style="?android:button"
    android:text="@string/hint_save" />

<com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/viewpdfHtml"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/imageSign"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/no_connection" />

</com.github.barteksc.pdfviewer.PDFView>`
</code>

This is my ontouchlistener for moving images and other code
<code>ImageView imageView;
 ViewGroup mainLayout;
 private View.OnTouchListener onTouchListener() {
    return (view, event) -> {
        final int x = (int) event.getRawX();
        final int y = (int) event.getRawY();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {

            case MotionEvent.ACTION_DOWN:
                RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams)
                        view.getLayoutParams();
                xDelta = x - lParams.leftMargin;
                yDelta = y - lParams.topMargin;
                break;

            case MotionEvent.ACTION_UP:
                float xD = event.getX();
                float yD = event.getY();
                DisplayMetrics displayMetrics = this.getResources().getDisplayMetrics();
                float   XDis = displayMetrics.xdpi;
                float  YDis = displayMetrics.ydpi;
                finalX = xD/XDis*100;
                finalY  = yD/YDis*100;

                break;
            case MotionEvent.ACTION_MOVE:
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                        .getLayoutParams();
                layoutParams.leftMargin = x - xDelta;
                layoutParams.topMargin = y - yDelta;
                layoutParams.rightMargin = 0;
                layoutParams.bottomMargin = 0;
                view.setLayoutParams(layoutParams);

                break;

        }
        mainLayout.invalidate();
        return true;
    };
}
</code>
this is the button which should show images on  click
<code>  buttonSign.setOnClickListener(view ->{

            }

        });
</code>
Answer: You need to create ImageView dynamically to make this work, this might help you :
Create ImageViews dynamically inside a loop
Comment: I have added that code inside onclick method and got this error   The specified child already has a parent. You must call removeView() on the child's parent first.
Comment: Have you removed the ImageView from your layout? Please update your code in the question so that i can help you.
Comment: one more thing if you can help that how can I remove these images from view?
Comment: how are you setting the images in code ? If you are using image.setImageDrawable(drawable); set it to image.setImageDrawable(null);
Comment: i am getting it from phone storage image.setImageURI
Comment: try setting image.setImageURI(null)
Comment: i have created another button for clear images should i placed image.setImageURI(null) inside it?
Comment: i have defined ImageView image; globally and it is working but just clearing the last image
Comment: final ImageView[] image = new ImageView[1];
Comment: You need to somehow keep track of every ImageView you create, use an array of ImageView and keep adding new ImageView's in it, clear the ImageView based on their position.


chrome app how to triger chrome.printerProvider events

Question: I am developing a chrome app and it needs to communicate with printer very often so I will be sending data directly to the printer without a print dialog, for this chrome provides chrome.printerProvider api. But the api contains only events with callbacks I cant see a way to trigger this events. Am I missing something here?
Answer: There is no way to trigger those events outside of the print dialog.
printerProvider is an API to provide a new printer "driver", not to use an existing one.
Comment: Or, a real driver together with `chrome.usb` or `chrome.bluetooth` or `chrome.sockets`.. Probably more targeted towards ChromeOS.
Comment: what is the use case of such api
Comment: "Save to WhatsTheNextFormatAfterPDF", "Save to YourCloudDriveDuJour" for instance.


Is it possible to hook a non-configurable property like window.location.hostname, in JavaScript?

Question: I would like to know if there is a way to hook a non-configurable property, like window.location.hostname.
By this, I mean if it's possible to get an event/do something when a non-configurable property is accessed?
For example, it is currently possible to be notified and to do something when the window.navigator.userAgent property is called:
(function() {
    var userAgent = window.navigator.userAgent;
    Object.defineProperty(window.navigator, "userAgent", {
        get: function() {
            console.log("hello from useragent");
            return userAgent;
        }
    });
})();

However, in my case, I need to do the same thing when the window.location.hostname property is accessed, but I can't find anything that allows me to do this.
Thank you very much for your help,
Bests!
Answer: You can save the domain in a global variable and then take advantage of your existing onload event to check each time for change, like this...
var Saved_Domain=''; // global

//----------------------------
window.addEventListener('load',function(){

 if((Saved_Domain!=='')&&(window.location.hostname!==Saved_Domain)){

  // The domain changed so do something here

  Saved_Domain=window.location.hostname; // save it again

 }

 // other after-load tasks continue running here

},false);

Actually scratch that...
If window.location.hostname has changed then a new document has loaded into the window... in which case you can't keep track of a domain change from the same document!
Or are you in control of the window/frame but haven't mentioned it?
Comment: In fact, I just want to hook the `window.location.hostname` in order to be notified when this property is used. For example, if there is a snippet code that is trying to compare the `window.location.hostname` with a hard-coded value, I would like to be able to modify the result of the `window.location.hostname` property. In other words, I would like to be able to override the property. I know that's possible with some properties, but idk how to do that (and if it's possible) with non-configurable properties.


Inserir itens em uma tabela usando Jquery

Question: Tenho uma formulário onde insiro no banco a venda e os itens da venda.
Ao abrir uma determinada venda, logo é exibido em uma tabela os itens dessa venda.
Quando desejo adicionar um novo item a essa venda, meu formulário fica "doidão". Desaparece da tela a tabela e os campos para inserir novo item e trava o html, preciso dar um refresh para voltar a funcionar.
Segue abaixo o código de quando eu abro e venda e exibe os itens dessa venda e o código de quando insiro um novo item da venda e a tabela deve ser atualizada com o novo item.
Código abrir venda (Esse tá beleza)
function abrirVenda() {
    var idvenda = $("#idVenda").val();
    var page = 'abrir_venda.php';
    $.ajax({
        type: 'POST',
        dataType: 'html',
        url: page,
        data: {idvenda: idvenda},
        success: function (msg) {
            msg = $.parseJSON(msg);
            if (msg.sucesso == true) {
                // exibe o formulário para adicionar novos itens dessa venda
                $('#itensVenda').css("display", "block");
            }
        },
    }).done(function () {
        buscarItensDaVenda();
    });
}
$(document).on("click","#abrirVenda",function(e){
//$("#abrirVenda").click(function () {
    abrirVenda();
});

Código para inserir um novo item da venda (Esse dá problema)
function gravarItenVenda() {
    var idvenda  = $("#idvenda").val();
    var idproduto = $("#idproduto").val();
    var preco = $("#preco").val();
    var qtde = $("#qtde").val();
    var subtotal = $("#subtotal").val();
    var page = 'gravar_itenvenda.php';
    $.ajax({
        type: 'POST',
        dataType: 'html',
        url: page,
        async: false,
        data: {idvenda:idvenda, idproduto:idproduto, preco:preco, qtde:qtde, subtotal:subtotal},
        success: function (msg) {
            msg = $.parseJSON(msg);
            if(msg.sucesso == true){
                alert(msg.mensagem);
            } else {
                alert(msg.menssagem);
            }
        },
    }).done(function () {
        buscarItensDaVenda();
    });
}

$(document).on("click","#additen",function(e){
//$("#additen").click(function (){
    gravarItenVenda()
});

E a função que é usado em .done nas duas funções acima
function buscarItensDaVenda(){
    var idvenda = $('#idVenda').val();
    var page = "busca_itensvenda.php";
    $.ajax({
        type: 'POST',
        dataType: 'html',
        async: false,
        url: page,
        data: {idvenda:idvenda},
        success: function (msg) {
            // arqui eu exibo em uma div o resultado da consulta dos itens da venda
            $("#divItensvenda").html(msg)
        }
    });
}

As inserções e as consultas no banco estão ok, o problema está mesmo na hora de exibir no browser. O html, jquery ou sei lá o que faz com que o formulário perca as referencias. Tento exibir o código fonte o navegador dá a mensagem que tenho que dar um refresh na página para exibir.
Acredito que o problema esteja no assicronismo do AJAX, não domino muito bem. Se algum puder ajudar.
Comment: Quando manda gravar, no retorno do Ajax está exibindo o `alert` em `alert(msg.mensagem);`?
Comment: coloquei o 'async:false' para entrar em 'success' e exibir o 'alert(msg.mensagem);' se deixar como default não entra no 'success', nem no 'error' e nem no'complete'.
Comment: Notei uma diferença em `$("#idvenda").val()` na função `gravarItenVenda`... o "v" está minúsculo, enquanto que nas outras funções está maiúsculo: `$("#idVenda").val()`....
Answer: A função html do jquery reseta tudo dentro do elemento dado, ou seja apaga tudo e insere o codigo que passaste por parâmetro.
tenta usar a função append, esta mesma, adiciona e não limpa tudo antes de inserir:
$("#divItensvenda").append(msg);

Atenção no teu backend(php), tem em conta o retorno, ou seja tenta retornar somente os dados, e no front end, adiciona html etc..
Supondo que o tua requisição ajax ao arquivo gravar_itenvenda.php, retornava isto:
$item = ['id' => 2, 'nome' => 'Relogio', 'mensagem' => 'boa qualidade'];
die(json_encode($item));
// Return irá ser: {"id":2,"nome":"Relogio","mensagem":"boa qualidade"}

No teu frontend irias fazer algo do tipo:
var msg = JSON.parse(msg); // converter JSON para objeto javascript
$("#divItensvenda").append('
' + msg.id + ' | ' + msg.nome + ' | ' + msg.mensagem + '
');

Comment: Já tentei o append, mas não deu certo. Sobre adicionar o html da tabela somente no front-end, tem algum problema em deixa no back-end?
Comment: Resposta editada, não é aconselhável, pois não faz muito sentido se no teu front-end consegues faze-lo, PHP = trata / adiciona informação, JAVASCRIPT = busca / monta / organiza informação, isto é a minha opinião entanto, pois tento separar html de php assim formando um back-end limpo e estruturado


What is the best way for implementing multilanguage support in J2ME applications?

Question: What is the best way for implementing multilanguage support in J2ME applications? I want my application in different languages, but up to know have not found any appropriate way to do that. Could you please help me in this issue?
Answer: hey you can check out j2me polish it supports localization and it is very easy to use


I need to solve an integral equation with feedback

Question: I've encountered the following equation:
$p_t = \pi_t + c \int_{-\infty}^te^{-\gamma(t-\tau)}dp_\tau, \quad 0<\gamma, 0<c<1$.
It is claimed that it can be rewritten as follows:
$p_t = \pi_t + \frac{c}{1-c}(\pi_t-\bar\pi_t)$,
where,
$\bar\pi_t = \lambda\int_{-\infty}^te^{-\lambda(t-\tau)}\pi_\tau d\tau, \quad \lambda = \frac{\gamma}{1-c}$
Do you have an idea why this is the case?
Any help is appreciated,
Comment: I tried to integrate by parts the second term of the first equation, i.e.

$\int_{-\infty}^t e^{-\gamma(t-\tau)}dp_\tau = \int_{-\infty}^t e^{-\gamma(t-\tau)}\dot p _\tau d\tau$

but I haven't found anything that solves my problem
Answer: Let's first differentiate the first equation with respect to $t$:
\begin{align}
\dot{p}_t&=\dot{\pi}_t+c\dot{p}_t-\gamma c\int_{-\infty}^te^{-\gamma(t-\tau)}dp_{\tau} \\
&=\dot{\pi}_t+c\dot{p}_t-\gamma(p_t-\pi_t). \tag{1}
\end{align}
Rearranging terms, we obtain
$$
(1-c)\dot{p}_t+\gamma p_t=\dot{\pi}_t+\gamma\pi_t \implies
\dot{p}_t+\lambda p_t=\frac{\dot{\pi}_t}{1-c}+\lambda\pi_t. \tag{2}
$$
The general solution to the above ODE is
$$
p_t=e^{-\lambda t}\left\{A+\int_{-\infty}^t e^{\lambda\tau}\left(\frac{\dot{\pi}_{\tau}}{1-c}+\lambda\pi_{\tau}\right)d\tau \right\}. \tag{3}
$$
Integrating by parts the first term of the integral yields
\begin{align}
p_t&=e^{-\lambda t}\left\{A+\frac{e^{\lambda t}\pi_t}{1-c}+\int_{-\infty}^t e^{\lambda\tau}\left(-\frac{\lambda}{1-c}+\lambda\right)\pi_{\tau}\,d\tau \right\} \\
&=Ae^{-\lambda t}+\frac{\pi_t}{1-c}-\frac{c\lambda}{1-c}\int_{-\infty}^t e^{-\lambda(t-\tau)}\pi_{\tau}\,d\tau \\
&=Ae^{-\lambda t}+\pi_t+\frac{c}{1-c}\left(\pi_t-\lambda\int_{-\infty}^t e^{-\lambda(t-\tau)}\pi_{\tau}\,d\tau \right).
\tag{4}
\end{align}
The first term on the RHS of $(4)$ can be eliminated if we impose the condition that $p=0$ if $\pi=0$. Then, using the definition of $\bar{\pi}_t$, we finally arrive at
$$
p_t=\pi_t+\frac{c}{1-c}(\pi_t-\bar{\pi}_t).\quad{\square} \tag{5}
$$


Erro 500 ao usar .htaccess

Question: Rescrevi um regra no .htaccess para retirar a extensão .php da minha página dashboard.php mas o WAMP me retorna:

erro 500
Comment: faltou dizer qual o código que adicionas-te para este erro aparecer.
Comment: Seria bom postar o .htaccess na pergunta.
Answer: Provavelmente é um problema de mod_rewrite desabilitado, siga os passos abaixo.
Abra o arquivo httpd.conf, procure pela linha:
#LoadModule rewrite_module modules/mod_rewrite.so
e descomente removendo o símbolo "#" do início da linha para ficar assim:
LoadModule rewrite_module modules/mod_rewrite.so
Procure também pela linha
AllowOverride None
e altere para
AllowOverride All

Após isso reinicie o wampserver!
Comment: Obrigado, realmente era esse o problema.
Comment: Por nada, se resolveu você pode estar marcando minha resposta como a correta :) obrigado!

Erro 500 ao usar .htaccess


Packet drop on HP ProLiant DL360 G9 running RHEL 6.10

Question: We have a HP ProLiant DL360 G9 running RHEL 6.10 with 2 X Intel 82599ES 10-Gigabit SFI/SFP+. HP product name is HP Ethernet 10Gb 2-port 560SFP+ Adapter
eth5 and eth6 showing a lot of packet drop (rx_missed_errors)
I disabled flow control at NIC level then rx_missed_errors stopped increase but rx_no_dma_resources started increase daily.

They both standalone interfaces not part of a bonding.
Eth5 and eth6 are on different cards
Both cards installed to a PCIe 3.0 X16 slot
irqbalance is running on the server

Update 1
Ring parameters for eth5 and eth6 are the same and already at max.
Pre-set maximums:
RX:             4096
RX Mini:        0
RX Jumbo:       0
TX:             4096
Current hardware settings:
RX:             4096
RX Mini:        0
RX Jumbo:       0
TX:             4096

I noticed following for eth6 in /proc/interrupts
 Sun Jun  2 19:39:42 EDT 2019

            CPU0       CPU1       CPU2       CPU3       CPU4       CPU5       CPU6       CPU7       CPU8       CPU9       CPU10      CPU11      CPU12      CPU13      CPU14      CPU15      CPU16      CPU17      CPU18      CPU19
 165:          0          0          0          0          0     484430     111744     333783     458868     577617          0          0          0          0          0      17978     402211      84832     183482   10567190   PCI-MSI-edge      eth6-TxRx-0
 166:          0          0          0          0          0      92569    2522312      36248      19459       1970          0          0          0          0          0      10140      33710      10180    1071214     651534   PCI-MSI-edge      eth6-TxRx-1
 167:          0          0          0          0          0      41060    2532170      37345      10970      92570          0          0          0          0          0       3055      22158      12485    1203344     494179   PCI-MSI-edge      eth6-TxRx-2
 168:          0          0          0          0          0     218925       8555    2312817     115650     126113          0          0          0          0          0      14575       3965     114145     995924     538667   PCI-MSI-edge      eth6-TxRx-3
 169:          0          0          0          0          0       7354       7781     199591    2262057      45221          0          0          0          0          0      34813     176350     105008     649389     962393   PCI-MSI-edge      eth6-TxRx-4
 170:          0          0          0          0          0      27982      23890      44703     162340    2597754          0          0          0          0          0      25991      22873      11846     885511     943057   PCI-MSI-edge      eth6-TxRx-5
 171:          0          0          0          0          0      16710        370        155   17725587    7504781          0          0          0          0          0 1054801625    1644839      14655  583745291  266971465   PCI-MSI-edge      eth6-TxRx-6
 172:          0          0          0          0          0       9823       6688     407394      11207      44103          0          0          0          0          0      88057    2496075       9284      56799    1391075   PCI-MSI-edge      eth6-TxRx-7
 173:          0          0          0          0          0      21175       1995     125490     151465      27120          0          0          0          0          0      19960     177195    2288457     787724     848755   PCI-MSI-edge      eth6-TxRx-8
 174:          0          0          0          0          0       7835       2210       3990      56075     106870          0          0          0          0          0     109740      24135      27720    2599827    1510934   PCI-MSI-edge      eth6-TxRx-9
 175:          0          0          0          0          0      42450       2605      39545      54520     162830          0          0          0          0          0      56035      11380      33815      52905    3993251   PCI-MSI-edge      eth6-TxRx-10
 176:          0          0          0          0          0      92335      33470    2290862       7545     227035          0          0          0          0          0       7550      25460      17225      65205    1682649   PCI-MSI-edge      eth6-TxRx-11
 177:          0          0          0          0          0      81685      56468    2273033     264820     195585          0          0          0          0          0     120640      36250      29450     244895    1146510   PCI-MSI-edge      eth6-TxRx-12
 178:          0          0          0          0          0      39655      24693     703993    1680384      22325          0          0          0          0          0     147980      27170      41585      72085    1689466   PCI-MSI-edge      eth6-TxRx-13
 179:          0          0          0          0          0     108905       1335      48265    2415832      19985          0          0          0          0          0       3545      23360      12590      35185    1780334   PCI-MSI-edge      eth6-TxRx-14
 180:          0          0          0          0          0     134826     291569      98014       9159    2262093          0          0          0          0          0     128867      18499      20078      39858    1463678   PCI-MSI-edge      eth6-TxRx-15
 181:          0          0          0          0          0       3220      37430      39030     129550      11070          0          0          0          0          0    2382452      24840      10860     146795    1664089   PCI-MSI-edge      eth6-TxRx-16
 182:          0          0          0          0          0      23120      28700     134025      96455      31545          0          0          0          0          0      30340    2262857      24485     144620    1673189   PCI-MSI-edge      eth6-TxRx-17
 183:          0          0          0          0          0       8900      29070      22490     112785     186240          0          0          0          0          0      40690      31665    2274862      37160    1705474   PCI-MSI-edge      eth6-TxRx-18
 184:          0          0          0          0          0      77090      18270      68465      53235     142648          0          0          0          0          0      16295      33770      29175    2367462    1642926   PCI-MSI-edge      eth6-TxRx-19
 185:          0          0          0          0          0         11          0          0          0          0          0          0          0          0          0          0          0          0          0          4   PCI-MSI-edge      eth6

So looks like CPU/Core 15/18/19 are under stress to process traffic on eth6
Basically I have no idea where to look next, I am guessing this may have something to do with irq affinity but not sure. I am also think of disable irqbalance but not sure if that is going to make any difference.
any suggestions?
Update 2
NIC Driver info and I don't think we have that bug. As that was in 2009.
driver: ixgbe
version: 4.2.1-k
firmware-version: 0x800008ea
bus-info: 0000:08:00.1
supports-statistics: yes
supports-test: yes
supports-eeprom-access: yes
supports-register-dump: yes
supports-priv-flags: no

The data arrived on both eth5/6 are multicast data. Is that enough, setup port mirroring needs a ticket to network engineer team and will take time. I also not sure what to tell them to look for.
If I understand your comments correctly, there is a way to balance eth6-rxtx queue to more than one CPU core. I did some search myself and collected following information, hopeful that is useful to you.
ethtool -x eth5 and eth6
RX flow hash indirection table for eth5 with 20 RX ring(s):
    0:      0     1     2     3     4     5     6     7
    8:      8     9    10    11    12    13    14    15
   16:      0     1     2     3     4     5     6     7
   24:      8     9    10    11    12    13    14    15
   32:      0     1     2     3     4     5     6     7
   40:      8     9    10    11    12    13    14    15
   48:      0     1     2     3     4     5     6     7
   56:      8     9    10    11    12    13    14    15
   64:      0     1     2     3     4     5     6     7
   72:      8     9    10    11    12    13    14    15
   80:      0     1     2     3     4     5     6     7
   88:      8     9    10    11    12    13    14    15
   96:      0     1     2     3     4     5     6     7
  104:      8     9    10    11    12    13    14    15
  112:      0     1     2     3     4     5     6     7
  120:      8     9    10    11    12    13    14    15
RSS hash key:
3c:f9:4a:0e:fc:7e:cb:83:c2:2a:a4:1c:cf:59:38:1c:ca:54:38:b9:6b:e8:2b:63:6e:d2:9f:eb:fc:04:c2:86:6d:e3:54:f2:73:30:6a:65

ethtool -n eth5 rx-flow-hash udp4 and eth6
UDP over IPV4 flows use these fields for computing Hash flow key:
IP SA
IP DA

I also run set_irq_affinity on both eth5 and eth6
sudo ./set_irq_affinity local eth5

IFACE CORE MASK -> FILE
=======================
eth5 0 1 -> /proc/irq/144/smp_affinity
eth5 1 2 -> /proc/irq/145/smp_affinity
eth5 2 4 -> /proc/irq/146/smp_affinity
eth5 3 8 -> /proc/irq/147/smp_affinity
eth5 4 10 -> /proc/irq/148/smp_affinity
eth5 10 400 -> /proc/irq/149/smp_affinity
eth5 11 800 -> /proc/irq/150/smp_affinity
eth5 12 1000 -> /proc/irq/151/smp_affinity
eth5 13 2000 -> /proc/irq/152/smp_affinity
eth5 14 4000 -> /proc/irq/153/smp_affinity
eth5 0 1 -> /proc/irq/154/smp_affinity
eth5 1 2 -> /proc/irq/155/smp_affinity
eth5 2 4 -> /proc/irq/156/smp_affinity
eth5 3 8 -> /proc/irq/157/smp_affinity
eth5 4 10 -> /proc/irq/158/smp_affinity
eth5 10 400 -> /proc/irq/159/smp_affinity
eth5 11 800 -> /proc/irq/160/smp_affinity
eth5 12 1000 -> /proc/irq/161/smp_affinity
eth5 13 2000 -> /proc/irq/162/smp_affinity
eth5 14 4000 -> /proc/irq/163/smp_affinity

sudo ./set_irq_affinity local eth6

IFACE CORE MASK -> FILE
=======================
eth6 5 20 -> /proc/irq/165/smp_affinity
eth6 6 40 -> /proc/irq/166/smp_affinity
eth6 7 80 -> /proc/irq/167/smp_affinity
eth6 8 100 -> /proc/irq/168/smp_affinity
eth6 9 200 -> /proc/irq/169/smp_affinity
eth6 15 8000 -> /proc/irq/170/smp_affinity
eth6 16 10000 -> /proc/irq/171/smp_affinity
eth6 17 20000 -> /proc/irq/172/smp_affinity
eth6 18 40000 -> /proc/irq/173/smp_affinity
eth6 19 80000 -> /proc/irq/174/smp_affinity
eth6 5 20 -> /proc/irq/175/smp_affinity
eth6 6 40 -> /proc/irq/176/smp_affinity
eth6 7 80 -> /proc/irq/177/smp_affinity
eth6 8 100 -> /proc/irq/178/smp_affinity
eth6 9 200 -> /proc/irq/179/smp_affinity
eth6 15 8000 -> /proc/irq/180/smp_affinity
eth6 16 10000 -> /proc/irq/181/smp_affinity
eth6 17 20000 -> /proc/irq/182/smp_affinity
eth6 18 40000 -> /proc/irq/183/smp_affinity
eth6 19 80000 -> /proc/irq/184/smp_affinity

Update 3
I modified upd4 rx-flow-hash to include source and destination port but it did not make any difference.
ethtool -n eth5 rx-flow-hash udp4

UDP over IPV4 flows use these fields for computing Hash flow key:
IP SA
IP DA
L4 bytes 0 & 1 [TCP/UDP src port]
L4 bytes 2 & 3 [TCP/UDP dst port]

Disabled irqbalance and manually update /proc/irq/171/smp_affinity_list to include all 10 'local' CPU cores.
cat /proc/irq/171smp_affinity_list

5-9,15-19

Here is grep 171: /proc/interrupts after I made above change(Add src and dst port to udp4 rx-flow-hash and added 5-9,15-19 to /proc/irq/171/smp_affinity_list) Let's call it before.
Here is grep 171: from /proc/interrupts this morning, let's call it after.
Before 171:          0          0          0          0          0      16840        390        155   17725587    7505131          0          0          0          0          0 1282081848  184961789      21430  583751571  266997575   PCI-MSI-edge      eth6-TxRx-6
After  171:          0          0          0          0          0      16840        390        155   17725587    7505131          0          0          0          0          0 1282085923  184961789      21430  583751571  267026844   PCI-MSI-edge      eth6-TxRx-6

As you can see from above, irq 171 only handled by CPU 19.
If irqbalance is running a different CPU will handle irq 171, it seems for some reason, irq 171 can't be balanced to more than one CPU.
Here is the packet drop updates
Wed Jun 5 01:39:41 EDT 2019
ethtool -S eth6 | grep -E "rx_missed|no_buff|no_dma"
rx_no_buffer_count: 0
rx_missed_errors: 2578857
rx_no_dma_resources: 3456533

Thu Jun 6 05:43:34 EDT 2019
njia@c4z-ut-rttp-b19 $ sudo ethtool -S eth6 | grep -E "rx_missed|no_buff|no_dma"
rx_no_buffer_count: 0
rx_missed_errors: 2578857
rx_no_dma_resources: 3950904

Time does not matter here, as multicast data stops after 16:00 PM each day.
I found this article on Red Hat site Packet loss when multiple processes subscribe to the same multicast group.
Our developer also mentioned if we only have one instance of our application running the number of drops reduced significantly. Usually there are 8.
Increased net.core.rmem_default from 4Mb to 16Mb
sysctl -w net.core.rmem_default=16777216
net.core.rmem_default = 16777216

Here is current Udp stack status, will check again tomorrow.
Fri Jun  7 00:40:10 EDT 2019
netstat -s | grep -A 4 Udp:

Udp:
    90579753493 packets received
    1052 packets to unknown port received.
    1264898431 packet receive errors
    1295021855 packets sent

Comment: What is in /etc/sysctl.conf?
Comment: @ewwhite Please clarify, what variables you interested in.
Comment: I want the tuned-adm settings and any network related sysctl.conf settings.
Answer:
Check the driver version. There was the bug with correct accounting of the rx_no_dma_resources, when the rx buffer is full. So check the length of the ring buffers (ethtool -g <iface>)  and increase it (ethtool -G <iface> rx <size> tx <size>, but it will cause a short time break in the packet processing).

Note: After update of the question you've know there isn't a bug, but, I think, the issues should be solved in the order of importance. So, let's solve the issue with missing errors and only then try to solve the rx_no_dma_resources errors.

The rx_missed_errors means the system doesn't have enough cpu resources to process the incoming packets. In most cases it happens when the cpu core, that should execute the irq handler, is under a load. Check the output of the cat /proc/interrupts command. Investigate how the NIC irq counters distibute between CPU cores. Disable the irqbalance and use the set_irq_affinity script to bind the irq handlers to the cores. If your system has multiple NUMA domains, you should use local or remote options of this script.

Check the output of perf top command to investigate what cause the cpu load at network packets processing.

Update 1
As you can see in /proc/interrupts, some CPU cores (15, 18, 19) handle very much more (in hundreds times) interrupts from the eth6-TxRx-6 queue irq handler, than other cores. Check the load of these cpu cores. Likely, they are under overload very often.
So, except the incorrect CPU affinity and irqbalance, you have other issue. You should investigate the preponderant traffic type that pass through queue 6 of eth6 NIC. Use a switch port mirroring and wireshark (start from Statistics - Protocol Hierarchy). After this you can tune the RSS hashing with the ethtool to share this traffic between several NIC queues. It'll avoid the overloading of some cores.
Some notes about NUMA
You've asked the details about local and remote options of set_irq_affinity script. To answer this question I've draw the simplified diagram of a dual socket system.

The modern CPUs have integrated memory controller and PCI-express controller. In a case of multi socket systems there is an interprocessor link to provide data exchange between processors. Every processor can get access to all memory. But in case if a processor works with a data in a memory area, which is managed by a memory contoller of an other processor, this entails the overhead to request to this remote memory controller and penalty for data transfer on the interprocessor link.
Data transfer between a PCI-Express device and a system is implemented with DMA (Direct Memory Access), what able to a peripheral device read/write data into RAM without explicit requests to CPU. Obviously, it's very implementation specific, but it also inherit the same memory access limits.
So, how the irq affinity envolved in that all? Roughly, when the PCI-Express NIC receives a data from outside, it stores this data in the system RAM with DMA and generate the interrupt to notify the system. What happens if interrupt handler will be execute on the other CPU, not local? Naturally, the interrupt handler need the received data to process it. And the all overheads and penalties for the remote memory will be gotten. In the worst case it can lead to overload the interprocessor link.
So, as you can see, the correct setup of the irq affinity for NUMA systems is very important. The set_irq_affinity script automates the binding of NIC queues irq handlers to CPU cores. In the best case you will see the "stair" of non-zero counters in /proc/interrupts. Obviously, the irqbalance tries to play in own game and kills the benefits from this irq affinity completely.
Update 2
So, what information we have at current moment:

There is a lot of multicast traffic, that is processed by eth6-TxRx-6 interrupt handler.
The RSS hash of UDP4: ip source address and ip destination address.
After run of set_irq_affinity the handler of this queue is binded to the 16th core.

What you can do now:

Monitor the statistics and the core loading, especially, the 16th core. Is there still overloading and missing errors?

Is this multicast traffic the only one flow or several? If there are several flows, you can tune the hashing of udp4 with ethtool. If the NIC will use not only the ip addresses for hash, but and port numbers, likely it can able to share the processing between several receive queues, and, conseqencially, between several cpu cores. If this is the only one flow, then you can try to bind to corresponded irq handler more cpu cores.

Update 3
So, you have several issues simultaniously.

In the netstat output you have:

1264898431 packet receive errors

But these errors don't relate to missing errors. When the systen doesn't have enough cpu resources to handle the irq, the packet will lost before any protocol handler will be executed. If memory for UDP socket buffers isn't enough, you will see corresponded errors in the output of the nstat -az UdpRcvbufErrors command. Monitor it and increase memory limit with sysctl variables. You can also monitor a receive queue of sockets with ss tool. It can be helpful too.

Investigate, what proccesses consume the cpu time. After this you can profile the workload with perf record or perf top. It's really softirq overloads single core? This kernel process maintains many things, so perf top will be helpfull to investigate what exactly consume the most of cpu time.

If you have only single multicast group, only single irq will be executed for this flow, because the n-tuple-hash will be same always. I don't know any workaround for this case. Only way is to use a faster processor. Also you can check the results of i7z tools to monitor the sleep states of the CPU.

I don't know your application architecture specifics, but may be you also have issue with loss of multicast udp datagrams when several instances are run. Maybe it also related with incorrect binding of the application instances to the CPU cores. Try to bind the application processes to the cpu cores.

P.S. I will extend the answer when you provide the information about results of the steps above.
Comment: I've updated the answer. Check, please.
Comment: I have provided ring buffer settings and `/proc/interrupts` sections related to `eth6`. I believe our application is developed to utilize `irqbalance` so I have to ask if I can stop that. Could you please explain a little bit more about 'local' and 'remote' options for `set_irq_affinity`. Thanks
Comment: Is there some changes?


Prove the function $u(x):=1-|x|^{2-N}$ is in $W^{2,p}$ on $\{x\in \mathbb R^N;\,\,|x|>1\}$

Question: This is exercise 10.11 from Leoni's book.
Take $\Omega:=\{x\in  \mathbb R^N;\,\,|x|>1\}$ and let
$$u(x):=1-|x|^{2-N}$$
 for $N\geq 3$.
I am trying to prove that $\frac{\partial^2u}{\partial x_i\partial x_j}\in L^{p}(\Omega)$ for all $1\leq p<\infty$. Clearly, I have
$$\frac{\partial^2u}{\partial x_i\partial x_j} = (N-2)\frac{\delta_{ij}|x|^N-Nx_ix_j|x|^{N-2}}{|x|^{2N}} $$
Suppose $i\neq j$, I have
$$\int_{\Omega}\left|\frac{\partial^2u}{\partial x_i\partial x_j}\right|^p\leq \int_\Omega \frac{1}{|x|^{Np}}dx = \int_1^\infty r^{-Np+N-1}dr$$
To have integration convergen, I need $-Np+N-1<-1$ which is $p>1$...
I have no idea about how to prove the case $p=1$.
Also, when $i=j$, I just don't know how to deal with
$$ (N-2)\frac{|x|^N-Nx_i^2|x|^{N-2}}{|x|^{2N}} $$
Any help is really welcome!
Answer: The exercise is incorrectly stated: the second derivatives of $u$ are in $L^p$ for $1<p<\infty$ (in fact, also for $p=\infty$), but not for $p=1$.
The case $i=j$ is not much different from $i\ne j$: just use the triangle inequality to estimate the derivative by $C|x|^{-N}$.

Remark: disregarding $1$, we have a function $|x|^{2-N}$, which is homogeneous of degree $2-N$. Each derivative of order $k$ is homogeneous of degree $2-N-k$. This is already enough to determine its degree of integrability. For a function $\phi$ homogeneous of degree $d$, the integral of $|\phi|^p$ over dyadic shell $2^m<|x| \le 2^{m+1}$ is $C 2^{mpd} 2^{mN}$, and the series $\sum_{m\ge 0} 2^{mpd} 2^{mN}$ converges iff $pd+N<0$.
Comment: Thx! I am trying to prove rigorously that $p=1$ is indeed diverge. Also, thx for the remark!
Comment: The remark at the end of my question should help with that. With $d=-N$ and $p=1$, the series is $C\sum_{m\ge 0} 2^0$.


Buffer comparison in Node.js

Question: I'm new in Node.js. There aren't Buffer comparison and I should use modules like  buffertools for these feature.
But I see a pretty strange behaviour when I compare Buffer objects in pure Node.
> var b1 = new Buffer([170]);
> var b2 = new Buffer([171]);
> b1
<Buffer aa>
> b2
<Buffer ab>
> b1 < b2
false
> b1 > b2
false
> b1 == b2
false

and
> var b1 = new Buffer([10]);
> var b2 = new Buffer([14]);
> b1
<Buffer 0a>
> b2
<Buffer 0e>
> b1 > b2
false
> b1 < b2
true
> b1 == b2
false

What actually happens under the hood?
Comment: How are you declaring `b1` and `b2` in both scenarios?
Comment: Could you provide b1 and b2 definition.
Comment: (1) never ever use `==` in JavaScript except you know what you're doing; instead, always use `===` (2) there are no equivalence tests in JavaScript except for `undefined`, `null`, `true`, `false`, numbers (including `Infinity`, but excluding `NaN`), and strings; nothing else can be meaningfully compared with `===`, bc that is essentially a value *identity* operator. `x === y` means `x` and `y` share the same allocated memory / are the identical same object. `x === y` is always `false` otherwise, hence e.g. `[] === []` is `false`.—Also see my comment to the accepted answer, below.
Answer: That's how the comparison operators work on objects:
var a = {}, b = {};
a === b; //false
a == b; //false
a > b; //false
a  d; //false
c < d; //true

Under the hood
(sort of)
Part 1 : Equality
This is the easiest part. Both abstract equality (==, spec) and strict equality (===, spec) check if you're referring to the same object (sort of comparing references). In this case, they are obviously not, so they answer is false (== spec step 10, === spec step 7).
Therefore, in both cases:
b1 == b2 //false
b1 === b2 //false

Part 2: The Comparison strikes back
Here comes the interesting part. Let's look at how the relational operators (< and >) are defined. Let's follow the call chain in the two cases.
x = b1 //<Buffer aa>
y = b2 //<Buffer ab>

//11.8.5 The Abstract Relational Comparison Algorithm (http://es5.github.com/#x11.8.5)
Let px be the result of calling ToPrimitive(x, hint Number).
Let py be the result of calling ToPrimitive(y, hint Number).

//9.1 ToPrimitive (http://es5.github.com/#x9.1)
InputType is Object, therefore we call the internal [[DefaultValue]] method with hint Number.

//8.12.8 [[DefaultValue]] (hint) http://es5.github.com/#x8.12.8
We try and fetch the object's toString method. If it's defined, call it.

And here we've reached the climax: What's a buffer's toString method? The answer lies deep inside node.js internals. If you want, have at it.  What we can find out trivially is by experimentation:
> b1.toString()
'�'
> b2.toString()
'�'

okay, that wasn't helpful. You'll notice that in the Abstract Relational Comparison Algorithm (what a big fancy name for <), there's a step for dealing with strings. It just converts them to their numeric value - the char codes. Let's do that:
> b1.toString().charCodeAt(0)
65533
> b2.toString().charCodeAt(0)
65533

65533 is an important number. It's the sum of two squares: 142^2 + 213^2. It also happens to be the Unicode Replacement Character, a character signifying "I have no idea what happened". That's why its hexadecimal equivalent is FFFD.
Obviously, 65533 === 65533, so:
b1 < b2 //is
b1.toString().charCodeAt(0) < b2.toString().charCodeAt(0) //is
65533 < 65533 //false
b1 > b2 //following same logic as above, false

And that's that.
Dude, what the hell?
Okay, this must've been confusing since my efforts of explanation haven't been well thought through. To recap, here's what happened:

You created a buffer. Benjamin Gruenbaum helped me recreate your test case by doing:
var b1 = new Buffer([170]), b2 = new Buffer([171]);
When outputting to console, the values are turned into their hex equivalent (see Buffer#inspect):
170..toString(16) === 'aa'
171..toString(16) === 'ab'
However, internally, they represented invalid characters (since it's not hex encoding; again, you're free to delve into the implementation nitty gritty, I won't (oh the irony)). Therefore, when converted to a string, they were represented with the Unicode replacement character.
Since they're different objects, any equality operator will return false.
However, due to the way less-than and greater-than work, they were turned into strings (and then to numbers) for comparison. In light of point #3, that's the same value; therefore, they cannot be less-than or greater-than each other, leading to false.

Finally, just to put a smile on your face:
b1 <= b2 //true
b1 >= b2 //true

Comment: Awesome answer to an interesting question :)
Comment: what you call "abstract equality" (`==`) should really be called "bogus equality" or "well-meant but badly implemented fancy equivalence"; what you call "strict equality" (`===`) is neither about strictness nor equality, rather it checks value identity. Read an in-depth discussion of these issues on https://github.com/loveencounterflow/jseq
Answer: There's already an accepted answer but I thought I might still as well chime in with a remark since I don't find the accepted answer particularly clear or helpful. It's even incorrect if only because it answers questions that the OP didn't ask. So let's boil that down:
> var b1 = new Buffer([170]);
> var b2 = new Buffer([171]);
> b1 < b2
> b1 > b2
> b1 == b2

All that is asked for is: "how do I perform equivalence and less than / greater than comparison (a.k.a. (total) ordering) on buffers".
The answer is:

either do it manually by stepping through all the  bytes of both buffers and perform a comparison between the corresponding bytes, e.g. b1[ idx ] === b2[ idx ],
or use Buffer.compare( b1, b2 ) which gives you one of -1, 0, or +1, depending on whether the first buffer would sort before, exactly like, or after the second (sorting a list d that contains buffers is then as easy as d.sort( Buffer.compare )).

Observe I use === in my first example; my frequent comments on this site concerning the abuse of == in JavaScript should make it abundantly clear why that is so.

Buffer comparison in Node.js


TCP: Redundant checksum avoidance specification

Question: TCP provides a mechanism to change the checksum scheme used by the two parties in a TCP session. There are four allowed checksum schemes according to this table, the last being "Redundant Checksum Avoidance".
As far as I understand from this Q&A, the Redundant Checksum Avoidance scheme essentially removes the checksum. Is the checksum then required to be all 0s? Is the checksum altogether removed?
The only RFC covering the change the checksum scheme I found does not cover the Redundant Checksum Avoidance scheme. Where can I find an RFC discussing it?
Comment: @MV see http://serverfault.com/questions/454886/is-the-tcp-checksum-over-the-payload
Comment: What problem are you trying to solve?
Answer: I think the closest protocol, based on your specifications is: DCCP as defined by RFC 4336. The RFC1146 you mentioned is obsoleted by RFC6247. See also: Wikipedia: Comparison of transport-layer protocols
Comment: Thanks. I'm stuck with TCP. See my comment in the question mdpc linked for a description what I want to do.


Highlight the argument passed in the exposed filters

Question: I have a view page like http://localhost/drupal/myviews, which looks like in the following screenshot:

I pass arguments to this page using a URL like http://localhost/drupal/myviews/voc3; the page looks like in the following screenshot:

So all this works fine.  When the argument is passed within the URL, can I highlight that argument in the exposed filter?
Answer: I was able to create a solution for a regular Taxonomy: Term ID (no depth) filter, so this may not be applicable for you (the filter with depth was behaving erratically for me).
This code will set the dropdown element to the term provided in the argument, and will defer to the dropdown selection if one is chosen.
Add this to your custom module and then flush caches:
<code>function mymodule_form_views_exposed_form_alter(&$form, &$form_state) {
  if($form_state['view']->name == 'name_of_view') {
    if(!isset($_GET['tid'])) {
      $arg = arg(1);
      if(isset($arg)) {
        $selected_value = array_search($arg, $form['tid']['#options']);
        if(isset($selected_value)) {
          $form_state['input']['tid'] = $selected_value;
        }
      }
    }
    else {
      $form_state['view']->args = array();
    }
  }
}
</code>
You can try changing every instance of 'tid' to 'term_node_tid_depth' if you are going with a Taxonomy With Depth filter (use a dpm($form) to verify the filter name).


Spring Boot - nesting ConfigurationProperties

Question: Spring boot comes with many cool features. My favourite one is a type-safe configuration mechanism through @ConfigurationProperties and corresponding yml/properties files. I'm writing a library that configures Cassandra connection via Datastax Java driver. I want to allow developers to configure Cluster and Session objects by simply editing yml file. This is easy in spring-boot. But I want to allow her/him configure multiple connections this way. In PHP framework - Symfony it is as easy as:
doctrine:
  dbal:
    default_connection: default
    connections:
      default:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
      customer:
        driver:   "%database_driver2%"
        host:     "%database_host2%"
        port:     "%database_port2%"
        dbname:   "%database_name2%"
        user:     "%database_user2%"
        password: "%database_password2%"
        charset:  UTF8

(this snippet comes from Symfony documentation)
Is it possible in spring-boot using ConfigurationProperties? Should I nest them?
Comment: I'm pretty sure you can't type-safely nest arbitrary numbers of subobjects (such as your `connections`), although it's possible you might be able to declare a `Map connections`. If that doesn't work, perhaps make a feature request on GitHub.
Answer: You could actually use type-safe nested ConfigurationProperties.
@ConfigurationProperties
public class DatabaseProperties {

    private Connection primaryConnection;

    private Connection backupConnection;

    // getter, setter ...

    public static class Connection {

        private String host;

        // getter, setter ...

    }

}

Now you can set the property primaryConnection.host.
If you don't want to use inner classes then you can annotate the fields with @NestedConfigurationProperty.
@ConfigurationProperties
public class DatabaseProperties {

    @NestedConfigurationProperty
    private Connection primaryConnection; // Connection is defined somewhere else

    @NestedConfigurationProperty
    private Connection backupConnection;

    // getter, setter ...

}

See also the Reference Guide and Configuration Binding Docs.
Comment: As of spring boot 1.3.0.RELEASE, the inner class needs to be public, otherwise I get
java.lang.IllegalAccessException: Class org.springframework.beans.BeanUtils can not access a member of class ...DatabaseProperties$Connection with modifiers "private"
Comment: How will be the getter and setter for regular class(non-inner class)?
Comment: These are regular getter and setter, just the same like in inner-classes. If you want to set the property `primaryConnection.host`, Spring invokes for you `getPrimaryConnection().setHost(value)` (very abstract and internally maybe not correct)
Comment: Why in Documentation nested class defined in PRIVATE? https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/html/configuration-metadata.html#configuration-metadata-nested-properties
Comment: I defined my classes based on your syntax. How can these properties  from other class, since they are not visible from outside
Comment: Having defined the configuration as in the first example, I now need to inject two instances - one `DatabaseProperties dbProperties` and the second is `DatabaseProperties.Connection connectionProperties`, right? Doesn't look very convenient.
Comment: @Scadge you only need to inject `DatabaseProperties dbProperties`, from there you can call `dbProperties.getPrimaryConnection()` and `dbProperties.getBackupConnection()`
Comment: @RolandWeisleder I'm talking about the case when I need to retrieve the fields from the inner class, e.g. `host` in the current example
Comment: @Scadge inject `DatabaseProperties dbProperties` and call `dbProperties.getPrimaryConnection().getHost()`. If your property is `prefix.host` (without `primaryConnection`) then your class `Connection` must also be annotated with `@ConfigurationProperties`
Comment: You may use `lombok` @Data on both the outer & inner classes to have the setters and getters generated


What is the correct syntax of Delete(node ) for SLL in C?

Question: Assuming the relevant header files, functions for Singly Linked List in C are declared.
Is the following definition of Delete() correct?
 /* The Structure for SLL
     typedef struct SLL
     {
       int data;
       struct SLL *next;
      }node;
    Function Delete() deletes a node*/

    void Delete( node **head)
    {
      node *temp, *prev;
      int key;
      temp = *head;
      if(temp == NULL)
      {
        printf("\nThe list is empty");
        return;
      }
      clrscr();
      printf("\nEnter the element you want to delete:");
      scanf("%d", &key);
      temp = search( *head , key);//search()returns the node which has key
     if(temp != NULL)
      {
         prev = get_prev(*head, key);
         if(prev != NULL)
         {
            prev->next = temp->next;
            free(temp);
         }
         else
          {
             *head = temp->next;
              free(temp);
          }
          printf("\nThe node is deleted");
          getch();
       }
     }

1) What happens if I replace(node ** head) with (node *head)?
2) What happens if I replace void Delete (node **head) with node
*Delete(node *head)?
3) Is there an alternate way to delete a node in C?
Thanks in advance
Comment: Perhaps you should do some research about *passing arguments by value* and *emulating pass by reference in C*?
Comment: So you know how *emulating pass by reference in C* works? Then I don't really see the point of your first question.
Comment: _[Here is a good tutorial site for types of linked list manipulations](https://www.geeksforgeeks.org/linked-list-set-3-deleting-node/)_  This particular page deals with deleting.
Comment: Yeah I did some research. I found the above code works as it should. I cannot understand the working behind it.
Comment: I'm sorry. I don't know what emulating pass by reference means.
Answer: This isn't a tutorial site, but here goes...
You do know that arguments in C are passed by value? Meaning the value is copied.
For example:
void some_function(int a)
{
    // ...
}

When calling the function above, like
int x = 5;
some_function(x);

Then the value in x is copied into the argument a in the function. If the code inside the function assigns to a (e.g. a = 12;) then you only modify the local variable a, the copy. It does not modify the original variable.
Now, if we want the function to modify x, then we must emulate pass by reference, which is done using pointers and the address-of operator:
void some_function(int *a)
{
    *a = 12;  // Modify where a is pointing
}

Now to call that, we don't create a pointer variable and pass that (though it's possible as well), instead we use the address-of operator & to pass a pointer to the variable:
int x = 5;
some_function(&x);  // Pass a pointer to the variable x

The pointer &x will be passed by value (since that's the only way to pass arguments in C), but we don't want to modify the pointer, we want to modify the data where it points.

Now back to your specific function: Your function wants to modify a variable which is a pointer, then how do we emulate pass by reference? By passing a pointer to the pointer.
So if you have
node *head;
// Initialize head, make it point somewhere, etc.

Now since the Delete function needs to modify where head points, we pass a pointer tohead`, a pointer to the pointer:
Delete(&head);

The Delete function of course must accept that type, a pointer to a pointer to node, i.e. node **. It then uses the dereference operator * to get where the pointer is pointing:
*head = temp->next;

Comment: @ryyker Well maybe some of my answers tend to be a little "tutorial-y", and maybe I should refrain from writing so many of them (or at least not write it here). Then on the other hand, writing tutorials on other places and then add comments here linking to them seems like a little selfish and egocentric. And I I just can't be bothered to write more detailed and extensive tutorials, the "answer" here is just about all I can muster on a good day. :)
Comment: Thanks a lot for such a detailed explanation.
Answer: 1) If you replace node** head with node* head you won't modify the original head pointer. You probably have a head somewhere that marks the beginning of the linked list. When you delete a node, there's a chance that you want to delete head. In that case you need to modify head to point to the next node in the linked list.
         *head = temp->next;
          free(temp);

This part of your code does exactly that. Here, temp == head. We want head to point to head->next, but if we pass in node* head to the function, the pointer will get modified but the changes will disappear because you're passing the pointer by value. You need to pass in &head which will be of type node ** head if you want the changes to be reflected outside of the function.
2) You will then change the function definition to return a void pointer (which is a placeholder pointer that can be converted to any pointer. Take care to not break any aliasing rules with this. But the problem from (1) remains, although, you could return a modified head, and assign it to the returned value. In that case define the function won't fit well with other cases where the head doesn't need to be modified. So you could return a pointer for head if it's modified or return NULL when it doesnt. It's a slightly messier method of doing things imho, though.
3) Yes, but that depends on the way a linked list is implemented. For the datatype shown here, the basic delete operation is as given.
Comment: @AndrewJoel No prob :)
Comment: @AndrewJoel Not quite. There's this pointer and let's call it `t`. We want to change the pointer itself (ie the address that's stored in it, not the thing it ints to) in a function. That obviously means we need to pass it by reference, and in C we use pointers to do that, so you'd need to pass in `&t` which is of type `typeof(t) *`. Here `t` is a pointer of `struct node`, so it's type is `node*`, so the parameter we pass into it must be of type `node**`. Hope that made sense.
Comment: Thanks for the swift reply.
Comment: I have some residual doubts.. 1)passing a pointer to a function doesn't mean that its address is passed too? So, what you mean to say is that (node **head) is same as (node *(&head)) , but not for (node *head)?
Comment: Oh okay. So by default in C, any pointer can be pointed by itself if i use ** as its prefix?
Comment: No, that's the type of the pointer. `type**` simply means it's a pointer to a pointer to a node. You always use `&variable` to get its address.


A question on summation of series...

Question:
If $$\frac{\left(1^4+\frac14\right)\left(3^4+\frac14\right)\ldots\left((2n-1)^4+\frac14\right)}{\left(2^4+\frac14\right)\left(4^4+\frac14\right)\ldots\left((2n)^4+\frac14\right)}=\frac1{k_1n^2+k_2n+k_3}$$ then $k_1-k_2+k_3$ is equal to . . . ?

What I  basically tried was simply putting the value of $n$ from $1$ to $3$. By doing so I got $3$ simultaneous equations and hence I calculated the desired answer.
What I want to know is that is there any other elegant way to solve the above problem  because my process is very time consuming ..looking forward to here from my friends thanks in advance......
Comment: What if you put n = -1 in the above equation? I know it might seem outlandish but the answer comes out to be 1/5...
Answer: Use the Sophie-Germain identity: $$a^4+4b^4=(a^2+2b^2)^2-(2ab)^2=(a^2-2ab+2b^2)(a^2+2ab+2b^2)$$Using this, we can factor an expression of the form $m^4+\frac{1}{4}$ into $$m^4+4\bigg(\frac{1}{2}\bigg)^4=(m^2-m+\frac{1}{2})(m^2+m+\frac{1}{2})$$Therefore, the LHS of your equation is equal to $$\frac{\displaystyle\prod_{i=1}^{n}\bigg((2i-1)^2-(2i-1)+\frac{1}{2}\bigg)\bigg((2i-1)^2+(2i-1)+\frac{1}{2}\bigg)}{\displaystyle\prod_{i=1}^{n}\bigg((2i)^2-(2i)+\frac{1}{2}\bigg)\bigg((2i)^2+(2i)+\frac{1}{2}\bigg)}$$Note that $$(2i-1)^2+(2i-1)+\dfrac{1}{2}=(2i)^2-4i+1+2i-1+\dfrac{1}{2}=(2i)^2-(2i)+\dfrac{1}{2}$$and $$(2i-2)^2+(2i-2)+\frac{1}{2}=(2i)^2-8i+4+2i-2+\frac{1}{2}=(2i-1)^2-(2i-1)+\frac{1}{2}$$So after cancelling, our expression above is just $$\frac{(2-1)^2-(2-1)+\frac{1}{2}}{(2n)^2+(2n)+\frac{1}{2}}=\frac{1}{8n^2+4n+1}$$and the answer is $8-4+1=5$.
Comment: Nice solution, man!
Comment: Awesome solution man.........

A question on summation of series...


Como manter os valores do input quando o usuário ir para outra página

Question: Bom, montei um form bem simples para explicar meu problema.
<?php
$action = filter_input(INPUT_GET, 'action', FILTER_DEFAULT);

if ((!empty($action)) && ( $action === "add")) {
?>

    <?php
}
?>

<form action="form.php?action=add" method="post">
    <input type="text" name="nome">
    <input type="text" name="email">
    <input type="password" name="senha">
    <input type="submit" name="enviar" value="enviar" />
</form>

Quando há algum erro no meu formulário eu envio um alert para o usuário e ele é redirecionado para página anterior para que corrija o erro. O problema é que todos os dados do formulário são perdidos quando ele retorna. Existe alguma maneira de resolver isto? Uma maneira em que os dados sejam mantidos e só sejam apagados quando o formulário estiver correto?
Comment: @h3nr1ke, o form action está levando para a mesma página.. Não há necessidade de redirecionar. Basta pegar os valores de $_POST... A edição do título desfigurou o contexto, dando margem a interpretação errônea.
Comment: isso não resolve meu problema, pois em alguns input já uso o `value` para carregar informações.
Comment: Se você entender como funciona compreenderá que pode resolver sim. Independente das distintas situações, a técnica é a mesma. Note que ainda pode resolver com Ajax, Cookies ou Sessions. O Ajax pode ser mais interessante pois não redireciona a página. Assim os dados persistem, além de economizar tráfego de dados.
Comment: e se ao invés de window.history vc usar window.location? então adicionar os campos que foram inseridos como query string... com isso ser eles vierem vc carrega no seu form...  algo do tipo window.location= document.referrer + '?index=1';
Answer: Troque window.history() por window.history.back() (equivale a clicar no botão Voltar do navegador), quando você usa o botão voltar do navegador ou mesmo a função back o próprio navegador recupera os dados do <form> (desde que a requisição tenha vindo pelo próprio <form>)
<?php
$action = filter_input(INPUT_GET, 'action', FILTER_DEFAULT);

if ((!empty($action)) && ( $action === "add")) {
?>

    <?php
}
?>

<form action="form.php?action=add" method="post">
    <input type="text" name="nome">
    <input type="text" name="email">
    <input type="password" name="senha">
    <input type="submit" name="enviar" value="enviar" />
</form>

Sobre a API history: https://developer.mozilla.org/en-US/docs/Web/API/History#Methods
Comment: deu certo em partes, todos os campos ficaram mantidos, porém o se senha foi apagado, como mantenho ele também?
Comment: @HugoBorges isso é questão de segurança, nenhum navegador mantém estes dados na camada que entendemos como "front-end", se notar em formulários de cadastro como do Gmail e Yahoo quando erra algo quase todo form é recuperado, com exceção da "senha" e do "repita a senha" (ambos usam ``), não é grande segurança, mas é algo padrão do input=password, eu posso até lhe dar uma sugestão, mas só se realmente você achar que é algo muito necessário, se for um form de login eu não recomendaria forçar isto
Comment: entendo, bom em questão do `` tudo bem, o problema e que uso um auto-complete. E quando o a algo errado o input dele é apagado, queria que esse input não fosse apagado.
Comment: Mas a opção de autocompletar senhas é ação do usuário, o site não pode ter controle sobre isto @HugoBorges
Comment: uso o auto completar para lugar cidade e não senha. Ai quando a algo errado o usuário tem que informar a cidade novamente.
Comment: @HugoBorges é que você meio que **mudou de assunto**, esta parte do autocompletar com cidade também não está no corpo da pergunta, pela lógica o .back deveria funcionar, se puder mostrar como esta em um exemplo simples eu posso testar e ver o que é possivel fazer.
Comment: bom acho melhor postar outra pergunta, vou fazer um exemplo e postar ok.
Comment: @HugoBorges não acho que seja necessário, inclusive se for um problema real eu até posso votar para reabrir a pergunta, pois parece diferente da outra que marcaram aqui


Por que minha imagem está passando da minha div?

Question: Defini uma altura para minha div, com 300px de altura e largura, porém a imagem está saindo fora da minha div, porém quando eu utilizo o bootstrap em um cartão a imagem fica totalmente certa dentro da div por que isso acontece ?
Exemplo
<!DOCTYPE html>

    <title>Teste imagem</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

        Go somewhere

Comment: Pois a imagem esta sendo formatada para o mesmo tamanho da `div`, manualmente é só adicionar `height` e `width` na tag ``, no seu caso `height = 300px`
Comment: Uma maneira de resolver isso é colocar as dimensões direto na tag da imagem: ``
Comment: @RafaelPassos se fizer isso vai quebrar a proporcionalidade da imagem pois ele não é quadrada.
Comment: @PedroRoweder Mesmo problema do comentário acima.
Answer: <!DOCTYPE html>

    <title>Teste imagem</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

        Go somewhere

assim sua div terá um tamanho na qual a sua imagem irá pegar e se encaixar com 100% do tamanho dela
Answer: Acontece que na imagem dentro do Card tem a classe card-img-top, e essa classe define a imagem com width de 100%, isso significa que a imagem vai ficar com 100% da largura do elemento que ela está dentro.
Se vc colocar uma imagem com 100% de width dentro de uma div com 300px, essa imagem fica com 300px de largura, mas se vc colocar uma imagem de 500px dentro de uma div de 300px a imagem vai estourar o tamanho da div, ela não vai respeitar a largura da div, por isso é comum declarar width:100% nas imagens, para que ele tenha no máximo a largura do elemento no qual está dentro.
Comment: Acho que o problema é que está _saindo fora_, pois se estivesse _saindo pra dentro_ acho que resolveria rsrs
Comment: Ele se refere à primeira imagem e não a que está dentro do card. No caso a resposta do DbaAlone atende, porque faltou colocar a classe .conteudo na div.
Comment: @Sam o que eu tinha entendido era *" porém quando eu utilizo o bootstrap em um cartão a imagem fica totalmente certa dentro da div **por que isso acontece ?**"* acho que vc tb tinha olhado por esse ponto
Comment: Sim, mas depois reli novamente a pergunta e ficou evidente o que ele quis dizer, embora haja uma certa confusão na elaboração da pergunta.
Comment: @Sam ficou confuso sim, até pq no código ele não usa a classe .conteudo. Parece que ele estava testando e no meio de erros e acertos ele ficou na dúvida e colou o código que estava na tela no momento... vai saber...
Comment: Daqui a pouco ele vai dizer "_foi mal, esqueci de colocar a classe na div_"... veja só rs
Comment: @Sam hahaha, típico


Supremum of $\frac{(x+y)^{2}}{2^{xy}}$

Question: How to find the supremum of
$$
\frac{(x+y)^2}{2^{xy}}
$$
for $x\ge 1$ and $y\ge 1$
I have no idea how to start with it and when try to find it in WolframAlpha it only gives my numeric value.
Comment: What do you know already. Do you know how to find a local maxima/minima? Lagrange multipliers? Please include it in your question.
Answer: Hint On each line $x+y=c+1$ where $c\geq1$, the numerator is fixed and the denominator attains minimum when $x=1, y=c$.
Answer: Hints:  Let $f(x,y) = (x+y)^2/2^{xy}$.  There are three possibilities:

there exists an unbounded sequence of points $\{(x_n, y_n)\}$ (i.e. either $x_n$ or $y_n$ is going to positive infinity) such that $f(x_n, y_n)$ converges to the supremum of f,
the supremum of f is achieved on the boundary where $x=1$ or $y=1$, or
the supremum of f is achieved at a point $(x_1, y_1)$ where $x_1>1$, $y_1>1$, and the gradient at that point is the zero vector.

When considering possibility 1., think about what happens when $x$ or $y$ is large.
When considering possibility 2, notice that $f(1,1) = 2$.  If you compute the gradient at (1,1), it indicates that the supremum does not occur at (1,1).  Alternatively, compute f(1.1,1.1) which is larger than 2.
The only way the maximum can occur on the line $x=1$ with $y>1$ is if the gradient is in the direction $(-1,0)$.  The only way the maximum can occur on the line $y=1$ with $x>1$ is if the gradient is in the direction $(0,-1)$.
When considering possibility 3, the gradient must be the zero vector.  You can use that fact to restrict the possible locations of the maximum to a very simple set.
That should be enough to get you started.
Or, you could look at AdditIdent's answer which is a very big hint.

Supremum of $\frac{(x+y)^{2}}{2^{xy}}$


Quaternions vs. Euler Angles

Question: Hi
What is the pros and cons of "Quaternions" and "Euler Angles" Method
- Which one is faster?
- Which one need less Computational Effort?
- which one is more accurate, (in round off error)?
Comment: personally I prefer using matrices
Comment: @mrbm Could be. But just do not let it confuse you with it's "3-dimensional complex number" explanation. Just take it as is. Except for the multiplication by sin and cos it's just another representation of rotation axis and angle, but in a more efficient way (with the encoded sin/cos) to facilitate fast multiplication and matrix conversion.
Comment: I found this my self  [http://biomch-l.isbweb.org/threads/11415-Summary-Quaternions-vs.-Euler-angles](http://biomch-l.isbweb.org/threads/11415-Summary-Quaternions-vs.-Euler-angles)
But its some obscure
Comment: @David quaternions are represented as matrices.
Comment: @ross I mean rotation matrices
Comment: Thank you all,   - which one is more accurate, (in round off error)?   I think Quaternions is faster and more accurate, so why some one may uses Euler Angles?
Comment: I think Quaternions are not used because
they are difficult to interpret, Is this right?
Comment: @mrbm I have named one reason for using them (euler angles) in my answer, but that for me is the only reason where they make sense, as they just have too many disadvantages. Often people prefer them for their more human-understandable form, but that is really the only advantage of euler angles.
Comment: @Christian Rau : Ok, thank you again.  I think I got my answer.
Answer: Euler angles are more human understandable and also good for decomposing rotations into individual degrees of freedom (for kinematic joints and the like) but have disadvantages like ambiguity and gimbal lock. In practice I would prefer quaternions, as they are easier to compute with (for the computer, not for humans) and more efficient. You have to make three rotations and multiply them together when rotating by Euler angles, whereas a Quaternion is only one rotation and as it already encodes the sin and cos, the conversion from quaternion to matrix is quite efficient.
Answer: Quaternions avoid Gimbal lock. More here.
Comment: Thank you for link, It seems useful, I am on it
Comment: I can conform this. Used quaternions in Molecular Physics simulations and Gimbal lock is the main reason to use them. This makes one numerical problem less.
Answer: Expanding a bit on a point from Christian Rau's answer:
There's an ambiguity in the specification of Euler angles: which angle applies to which axis? Code that uses the convention (yaw, pitch, roll) won't interoperate with code that assumes (roll, pitch, yaw), and it may not be obvious, from looking at the code, which interpretation is being used.
Quaternions don't suffer from this ambiguity, since they only represent a single rotation, with a well-defined axis.
Comment: I also meant the ambiguity, that different angle triples (of a single convention) can refer to the same rotation.
Comment: This needn't be the extreme gimbal lock case, every rotation can be represented by multiple euler angle triples, even in the same convention.
Answer: Quaternions have many advantages over Euler angles, as pointed out in the other answers. However, Euler angles do have one advantage over Quaternions:
Euler angles can tell you the direction and magnitude of a rotation. When you convert a Euler angle to a Quaternion, that information is lost. For example, the Euler rotations of (-270°, 0, 0) and (1170°, 0, 0) produce the identical Quaternions (-0.7071, 0, 0, -0.7071).
Comment: Yes no one knows this basically. Internally one should always store orientation values as Euler Angles to prevent this information loss. Only temporarily convert that value into a quaternion to do other calculations. Should you ever need the Magnitude of Yaw from an orientation and you only stored the Quaternion in memory give it up... that information is lost to you forever.

This is a definitive benefit.
Comment: This is a very situational advantage though. If you have an application where there is the need to keep track of how often you've rotated about an axis (for example due to winding numbers or something) then you would probably not take care of this with euler angles anyway.
Comment: @Blackclaws That may be true, but you'd still use something other than Quaternions. Otherwise you'll be faced with the same problem as trying to determine RPM from video footage - once you rotate more than half a revolution in one frame, there's no way to tell which way or how fast anymore (assuming infinite shutter speed).
Answer: Euler angles are better than quaternions. You should always store Euler angles in memory and use quaternions only for calculations. Nobody knows this but what I say is absolutely true. If you're lurking around, know that this is important. Hear me out.
The reason is because you can always easily derive a quaternion from a Euler angles. The conversion is trivial. However the conversion from quaternion to Euler angles is fundamentally broken. There are two possible Euler angles for every quaternion and you cannot know which of the two possibilities your quaternions came from.
For virtual worlds and 3D games you can always just use quaternions. This is because your computer can just draw a picture of the object at an orientation without actually yawing and pitching an actual physical gimbal to achieve that orientation.   However for robots and other real world applications there is real information loss when converting to a quaternion.
If you have a real physical gimbal and you are given a quaternion that represents the orientation of that gimbal you absolutely cannot ever extract the original yaw, roll or pitch the gimbal used to achieve that orientation UNLESS the gimbal is restricted in it's range of motion somewhere.
Remember this. If you're in robotics or some mechanical setting save the orientation value as the original Euler angles. Only convert to quaternions temporarily only for a calculation.
There's basically no return trip back to Euler once you convert to quaternion. So don't make that trip permanent, store all your information as Euler angles.
Comment: While I find your answer useful and informative, I still don't think that it makes Euler "better" than quaternions. If anything I'd say Euler has its uses and it *could* be better in some scenarios. Even in robotics you can get away without them, and the only place where it'd make sense to use them would be when controlling a physical gimbal, as you mentioned.
Comment: @Trap I should say Euler angles are better for storage or data transfer. Temporarily convert to quaternions for calculations and transforms but for data storage keep it as a Euler angle.
Comment: @BrianYeh Stating that the conversion is trivial is not quite true. There are 4 cosines and one sine involved in the calculation which, depending on your use case, might take quite a long time to calculate especially if you have to do it often. In the use case of a single robot with 3 joints this might not be significant however.
Comment: @Blackclaws actually coming back to this question a year later. Pitch is limited from -180 to 180 deliberately in the official definition of euler angles to prevent this problem from occurring. That means only one euler angle represents 1 orientation. This makes my statement wrong from the perspective of how a euler angle is officially defined. However if your robot has joints that exceed the artificial limits imposed by the official definition of euler angles then this problem still applies. And yes I see what you're saying as well.
Answer: Euler angles is faster.
Euler angles requires less computational effort.
Quaternions are absolutely more accurate.
There is a problem called Gimbal lock which was found in Euler angles. It happens when two axis align together.
On the other hand quaternions are more flexible and solved this problem as it is more axis oriented. Yet, it is complicated to understand.
Well, to make it easy to understand Quaternions. Let's divide the four components to two: An angle and x,y,z point that is connected to the origin of the axis say P.
The (x,y,z)-P line representing a new axis.
The angle represents the angle between the axis and real orientation.
To visualize this answer you need to check this 5-minutes video.
https://eater.net/quaternions/video/intro
Comment: This is unfortunately very misleading. Euler angles are not faster in most situations.

Quaternions vs. Euler Angles


criar botão para cancelar função fullscreen

Question: Quero criar um botão para cancelar um evento/função fullscreen sem função toogle
apenas clicar no botão e fechar o modo tela cheia.
alguém pode me ajudar  ?
Answer: Consegui resolver meu problema com o JavaScript
Solução:
<code>   <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

    <script>

function exitFullscreen() {

        if(document.exitFullscreen) {
            document.exitFullscreen(); }

        else if(document.mozCancelFullScreen) {
            document.mozCancelFullScreen();}

        else if(document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        }
    }
    </script>

html:

    <button class="fechar" onclick="exitFullscreen();"> X </button>
</code>
Comment: Só salientando que o uso do `jQuery` é opcional.
Comment: Obrigado,  @Valdeir Psr , sou novo estava tentando deixar os códigos visíveis. Como adiciono demonstração ?
Comment: Basta selecionar todo o código e apertar `Ctrl + K`
Comment: não funcionou, fiz como voce disse
Comment: Você **deve** selecionar apenas o código. Ou você pode inserir 4 espaços em cada linha; ou ainda poderá clicar no ícone `{}`


Augmented triads in classical music

Question: I would like to know of examples of augmented chords of type 5# (I do not refer to 6th) in classical music, I know the theory for the formation of this type of chords (C aug or C+ or C(5#)-> C, 3ª major interval -> E and 5ª augmented interval -> G#), I have learned many examples in popular music and jazz but I would like to know in as much detail as possible examples in classical music.
Comment: Definitely check out some of Debussy's work.  He did some compositions that focus entirely on the Whole Tone scale, which can only create triads of the augmented type.  There's also this wikipedia article: https://en.wikipedia.org/wiki/List_of_pieces_which_use_the_whole_tone_scale
Comment: Ok, if you know more examples write here, I will try to study them all. And many thanks to all.
Answer: Before I start, note that oftentimes these "augmented triads" in classical music are not bonafide augmented triads but actually just dominants with a brief chromatic passing tone. But not always!
Now, there's really no better one-stop shop than this terrific minuet by Mozart (K 355). Here's a score, and below is a sample of the opening measures; check out the augmented triads in mm. 1, 5, 7, and 9. (Whether they truly "are" and function as augmented triads is a much longer discussion; but they do momentarily create augmented harmonies.)

And since I've got Wagner on the brain, here are some other ideas.
I've linked the music; I'll leave it up to you to find the scores:

Wagner, Siegfried, Act I Scene 3 (beginning in m. 2430), at the famous "Nothung!" calls. The calls themselves are above an F augmented triad, and there's a brief intro that could be understood as a D augmented triad.
Wagner, Siegfried, Act III Scene 2 (m. 440), as Siegfried confronts The Wanderer. The opening progression, in A flat, alternates between I and V+.
Similarly, check out Beethoven's Op. 119 No. 1 Bagatelle in G minor. In m. 17, a V chord in A flat has a chromatic passing tone B-natural that briefly creates a V+.
Comment: I would analyize MM. 5, 7, 9 differently. The "augmented triad" is just an written-out appoggiatura before a Bm/D chord (in M.5) followed by an augmented 6th and C# (again, with a written-out appoggiatura). As for MM. 1 and 2, I would call that "counterpoint" not "harmony." The harmonic progression is just D A7. The Wagner example is unambiguous, though.
Comment: I so glad this post reappeared with recent activity, because I discovered this K355 in your answer. I never heard it before. What a great example of harmony! I analyzed the whole thing last night. I will post a new question about one particular part that confused me. Anyway, thanks!
Comment: I agree 100%; I tried to hint at this in the parenthesized section of my second paragraph.
Comment: Sorry, I read it too fast and thought you meant a *bona fide* example of *augmented* triads, not *ambiguous* ones!
Comment: I tried to make it a bit clearer, in any event!
Answer: You will find plenty of augmented chords in the music of Edvard Grieg.  For instance, Measures 11 and 13 of "To Spring", Op. 43 no. 6.
Answer: Beethoven actually uses them quite functionally in the first movement of Eroica, right in the beginning of the development. Here, the Ab augmented triad resolves into G7 with Ab moving down to G and E natural up to F. Then with the same melody he moves from C major to F minor, then again from Ab augmented to G7, where he stays for four bars before modulating to G major, using the Ab major chord as a Neapolitan.
Comment: What are your thoughts on that E-natural just being a lower neighbor tone to the F, and this chord being a `iv6` instead of A-flat augmented?
Answer: Mozart used augmented triads in his sonata in A major (3rd variation for example).
Chopin used augmented triads in his prelude in e minor (augmented triad with a major 7th)
and a full augmented triad in his prelude in c minor.

Augmented triads in classical music


How to add an existing variation to a product

Question: How to add an existing variation to a product?
When I create a product the form forces me to create a new variation, but I also want to add an existing one to the same product.
Comment: It would be helpful if you provided some background information.  Otherwise, your question runs the risk of being closed.
Comment: Thank you. Drupal commerce kickstart 2.32. when i am creating a new product display  i also have to create a new variation of the product. I would like to know if i can add an existing variation. not to create a new one.
Answer: Turns out I know what you're talking about Nikolaos, and you're in luck! There's a checkbox!
Here's an animated gif that walks you through the steps that I've outlined below:

Navigate to your Content Types
Manage Fields on your Product Display (you may have more than one of these)
Locate the Product Reference or Product Variations Field, click "Edit"
Scroll to the middle and locate the checkbox "Allow users to add existing variations"
...
Profit!


equalto query firebase angularjs giving null values

Question: I have a database structure in firebase like this:

I wan't to query the database through child 'organization' then child 'access_points' to match SSID is equalTo Abacus and return that access_point. For that I have written this code :
       var ref1 = new Firebase("FIREBASEURL/organization");
   var name = ref1.child("access_points").orderByChild('SSID').equalTo('Abacus')
   .on('value', function(snap) {

  $scope.acc_pt = snap.val();

      console.log($scope.acc_pt);
  });

But the query is not even going to SSID and thus returning null values in console. I don't know how to query the nested nodes. Can somebody help?
Answer: var ref1 = new Firebase("FIREBASEURL/organization"); here you are making reference on the organization node and "access_points" is not the direct child of that reference , the direct child is -Kh3dXkTBUPqhs_bL5D- your query must be :
var name = ref1.child("-Kh3dXkTBUPqhs_bL5D-").child("access_points").orderByChild('SSID').equalTo('Abacus')