SPF SOFTFAIL domain of transitioning email@example.com does not designate X.X.X.X as permitted sender)

Question: in my company I have the following error.
softfail (google.com: domain of transitioning email@example.com does not designate X.X.X.X as permitted sender) client-ip=X.X.X.X;

Let's say my mail.company.com server is Y.Y.Y.Y, every user connects to his/her mail account from Thunderbird, the SMTP/POP3/IMAP is served by DirectAdmin hosted on Y.Y.Y.Y domain. Some of users who uses GMail to download mails from external POP3 server (mail.company.com) are receiving the above error and email is in SPAM directory. The SPF record which I had was:
v=spf1 a mx ip4:Y.Y.Y.Y ~all

The thing which I don't understand is how is it possible that IP marked as designated IP is X.X.X.X and it differs sometimes but still it's not SMTP server's ip Y.Y.Y.Y?
I changed SPF record to:
v=spf1 mx a ptr ~all

But I don't this it's the best solution.
I have my domain stored behind cloudflare but mail.company.com is not proxied only company.com is proxied.
Thank you for any help.
Comment: Because that's where the mail came from. If you didn't expect mail to be sent from those IP addresses, you need to investigate why it is happening.
Comment: Sure bot how is it possible if email was sent using company's SMTP server and I see user settings in Thudebird that are set for the company's server?
Comment: We have no way of knowing the context here. It is your company!
Comment: The problem is the designated IP X.X.X.X is client's ip not not SMTP server's ip Y.Y.Y.Y.
Comment: Then you need to go look at that machine and figure out what it is doing.
Comment: Sure this is some kind of error with DirectAdmin and EXIM described here https://support.google.com/mail/thread/15252844?hl=en but I don't know how to change EXIM settings.
Answer: I solved this by setting custom received header in exim config (/etc/exim.conf).
In above file I've added:
received_header_text = ${if def:authenticated_id {Received: from $primary_hostname ([X.X.X.X] helo=[s1.example.com]) by $primary_hostname with ESMTP\n\t(Exim $version_number)\n\t${if def:sender_address {(envelope-from <$sender_address>)\n\t}}id $message_exim_id${if def:received_for {\n\tfor $received_for}}\n\t}}Received: ${if def:sender_rcvhost {from $sender_rcvhost\n\t}{${if def:sender_ident {from ${quote_local_part:$sender_ident} }}${if def:sender_helo_name {(helo=$sender_helo_name)\n\t}}}}by $primary_hostname ${if def:received_protocol {with $received_protocol}} ${if def:tls_cipher {($tls_cipher)\n\t}}(Exim $version_number)\n\t${if def:sender_address {(envelope-from <$sender_address>)\n\t}}id $message_exim_id${if def:received_for {\n\tfor $received_for}}

where X.X.X.X is mail server IP and s1.example.com is mail server hostname or ip address.
I've put that after:
#EDIT#1:
# primary_hostname =
smtp_active_hostname = ${if exists{/etc/virtual/helo_data}{${lookup{$interface_address}iplsearch{/etc/virtual/helo_data}{$value}{$primary_hostname}}}{$primary_hostname}}

After that I've restarted exim:
service exim restart

And now Google is not failing spam checks due to SPF SOFTFAIL.

SPF SOFTFAIL domain of transitioning XX@company.com does not designate X.X.X.X as permitted sender)


Openconnect and Pulse Stopped Working

Question: I connect to a pulse VPN via
sudo openconnect --juniper {{myserver}}

and it has worked for months.
This morning when I try to get in, after accepting the cert and doing username/password it just ends with
Connected to HTTPS on {{myserver}}
Got HTTP response: HTTP/1.1 400 Bad Request
Unexpected 400 result from server
Creating SSL connection failed

Is there a change I need? A workaround?
Answer: I just got this working.  There is a bug reported
http://lists.infradead.org/pipermail/openconnect-devel/2016-September/003951.html
which causes the pulse server to reject clients that do not present a content header of 256 bits on certain packets.  This has been fixed in the source code, but has not been compiled into the ubuntu xenial releases yet (most likely other releases).  to install from source I had to:

copy vpnc-script from the following link to /etc/vpnc/vpnc-script http://git.infradead.org/users/dwmw2/vpnc-scripts.git/blob_plain/HEAD:/vpnc-script
chmod +x /etc/vpnc/vpnc-script
clone the source git://git.infradead.org/users/dwmw2/openconnect.git
cd openconnect
git checkout v7.08
sudo apt-get install automake libtool liblz4-1 libxml2-dev openssl libssl-dev
sudo ./autogen.sh
sudo ./configure  You may need to add --without-openssl-version-check to squelch a warning.
sudo make
sudo make install

Then just run it from the directory you cloned into, for me:
sudo ~/code/openconnect/openconnect --juniper <server> -u <username>
I have been trying to make this work for months but I am now being given an IP address by our pulse app.
Comment: This issue was fixed in their 7.08 release, so instead of pulling down the bleeding edge source code from Github, you could download the stable 7.08 release and compile. http://www.infradead.org/openconnect/changelog.html
Comment: Dror I noticed that I have the same problem and got around it by manually editing my /etc/dnsmasq.conf and adding server=/TLD/dns-server-1-ip statements.  not the most elegant solution, but it worked for me and my usecase
Comment: I've followed your instructions but dns is not set correctly. Any suggestions?
Comment: It may be possible that the pulse server is not sending the dns information to you or that openconnect does not understand the information it is given.   (taken from my openconnect dialogue) WARNING: Juniper Network Connect support is experimental.
It will probably be superseded by Junos Pulse support.  It may also be possible that Network Manager or dnsmasqe are interfering with the published dns settings.  It is a common issue with openvpn that the linux device does not pick up and use the dns servers without an update to resolvconf
Comment: I'd add `git checkout v7.08` to freeze the above instructions for OpenConnect 7.08 (or grab the official 7.08 tarball).
Answer: As Andrew pointed out, this is because the version of openconnect is out of date. Rather than have a self-built version of open connect, I actually added the package source for Zesty, updated just openconnect and turned off the package source. Given that I'll move to Zesty next month, this felt fairly low risk to me.

Openconnect and Pulse Stopped Working


Function creating in Lua

Question: When I create the function by assigning ,"if" condition doesn't work but when I do create the function like in second example below, it works. Can you tell me why?
Not working:
local start=os.time()

local countDown = function(event)
   if((os.time()-start)==3) then
      Runtime: removeEventListener("enterFrame", countDown)
   end
   print(os.time()-start)
end

Runtime:addEventListener("enterFrame", countDown)

Working:
local start=os.time()

local function countDown(event)
   if((os.time()-start)==3) then
      Runtime: removeEventListener("enterFrame", countDown)
   end
   print(os.time()-start)
end

Runtime:addEventListener("enterFrame", countDown)

Answer: That's because when you do local countDown = ..., the countDown variable doesn't exist until after the ... part has been executed. So your function will access a global variable, not the local one that doesn't exist yet.
Note that Lua converts local function countDown ... into the following:
local countDown
countDown = function ...

Function creating in Lua


Como chamar um ajax dentro de outro?

Question: preciso chamar outra requisição ajax dentro de uma condição. Mas o ajax de fora nao espera o de dentro termianr para finalizar. Exemplo:
Uso isso
 $.ajax({
                        type: "GET",
                        url: "MINHA_URL",
                        success: function (e) {
                        if(e == 'erro'){
                           $.ajax({
                               type: "GET",
                               url: "MINHA_SEGUNDA_URL",
                               success: function (f) {
                                  IMPRIMIE ALGUMA COISA
                               }
                       .....

O problema é que nao executacorretamente. Como proceder?
Comment: Nao sei qual versão do jQuery que está usando mas o comum é usar o `done` para executar algo quando a requisição for realmente concluída.
Answer: Mas o ajax de fora não espera o de dentro terminar para finalizar.

Não espera pois são requisições assíncronas.
Defina na chamada do ajax a option async: false
Comment: O problema é que {async: false} ja está obsoleto nas versoes mais novas do jquery!
Answer:     $.ajax({
    url: 'MINHA_URL',
    type: 'post',
    data: {
        html: 'Teste 1'
    },
    success: function(returnhtml) {
        $("#result").append($('
').html(returnhtml));
        $.ajax({
            url: 'MINHA_URL',
            type: 'post',
            data: {
                html: 'Teste 2'
            },
            success: function(returnhtml) {
                $("#result").append($('
').html(returnhtml));
            }
        });

    }
});

Resultado :

Teste 1

Teste 2

Exemplo prático: http://jsfiddle.net/qz02oukw/

Como chamar um ajax dentro de outro?


Characteristics of wave equation on compactified coordinates

Question: I am following Zenginoglu's paper here on page 6-7. I am confused why my attempts to apply hyperboloidal compactification on the characteristics do not agree with the illustration Zenginoglu provided. I think I may have made a mistake when applying the transformation.
To provide some background: the characteristics of the standard wave equation
$$
\partial_t^2u - \partial_x^2u = 0
$$
are $x\pm t=c$ for some constant $c$. By applying the hyperboloidal compactification
$$
\begin{split}
\rho &= \dfrac{x}{1+x}\\
\tau &= t - h(x)
\end{split}
$$
where $h(x) = \sqrt{S^2 + x^2}$ is the height function (for consistency and computational purposes, set $S=10$), we transform the characteristics in the compactified $\rho/\tau$ coordinates as follows.

I want to verify this claim computationally. Rewriting the characteristics $x\pm t = c$ with the parametrized function
$$
r_\pm(t) = (c\mp t, t)
$$
and defining the compactified parametrization of the characteristic as
$$
\bar{r}_\pm(t) = (\rho, \tau) = \bigg(\dfrac{x_\pm}{1 + x_\pm}, t - h(x_\pm)\bigg)
$$
we get
$$
\bar{r}_\pm(t) = \bigg(\dfrac{c\mp t}{1 + c\mp t}, t - \sqrt{S^2 + (c\mp t)^2}\bigg).
$$
However when I plot one line for $t\in(-100, 100)$ out I get a big mess, and it's not even in the right quadrant. Did I make a mistake with my transformation?
Answer: I don't think your $\rho$ is correct. In the article $x = \rho / \Omega$ (see equation (12)) where $\Omega = \Omega(\rho)$ where the zero set corresponds to spatial infinity. What you set above will have $\Omega = (1-\rho)$ which vanishes at $\rho = 1$, so necessarily you have a different picture from what he has. The correct $\Omega$ to use is given in equation (19) of the paper which takes the form
$$ \Omega = \frac12 \left( 1 - \frac{\rho^2}{S^2} \right) $$
where $S$ is a parameter showing how wide the compactified domain should be. In the shown picture, it was chosen with $S = 10$.


jquery - how to slice elements in two different unordered lists?

Question: I have two sets of unordered lists with the same class name and I want to subset it with jquery slice.
var currentCount= 0;
var maxCount= 3;
$('.ulClassName>li').slice(currentCount,maxCount).show();

This works perfectly for the first UL (it shows only the first three lists) but does not slice the second UL with the same class name. Below is the markup:

Blah blah1

Blah blah2

Blah blah3

Blah blah4

Blah blah5

Blah blah6

Blah blah1

Blah blah2

Blah blah3

Blah blah4

I understand that jquery indexes all list elements in the page, I dont want to write separate code for the two lists, can somebody help me?
Answer: You might want to call:
$('.ulClassName').each(function() {
   $(this).find('li').slice(currentCount, maxCount).show();
});

Answer: An alternative is to use the nth-child selector combined with nextAll to avoid using slice, which operates on the entire set all at once:
$('.ulClassName > li:nth-child(4)').prevAll().show();

Alternatively,
$('.ulClassName > li:nth-child(3) ~ li').hide();

(This hides everything under the third li element, which is different from the first, but should be more efficient since ~ li can be evaluated by document.querySelectorAll() for modern browsers)
Answer: $('ul.sideFilter').each(function(){

$(this).find('li').slice(5).wrap("

");

});

Comment: You should really add some non-code comments describing your answer.
Comment: Additionally, since your answer is quite similar to one that has already been accepted, you should describe why your solution may be perfered.


Drupal 7: use Form API to make a button that doesn't submit the whole page

Question: I want a button that runs a callback function using the AJAX method included in Form API.
The button I have still submits the whole node edit form. I don't want it to do that - just pass a couple variables to the callback function and display the results. How can I do that?
This is my FAPI code for that button:
<code>    $form['rid_import']['rid_get'] = array(
                '#type' => 'button',
                '#value' => t('Import'),
                '#attributes' => array(
                    'id' => array('fetch_rid'),
                    'class' => array('col-sm-3', 'col-xs-4')
                ),
                '#parents' => array('rid_import'),
                '#limit_validation_errors' => array(),
                '#executes_submit_callback' => false,
                "#submit" => array('sql_no_submit'),
                '#ajax' => array(
                    "callback" => 'sql_fetch_restid',
                    "wrapper" => 'rid_sql_query',
                    "event" => 'click'
                )
          );
</code>
EDIT
You're right, I was being unclear. Basically what I wanted is something that works like your "Add More" or "Remove" buttons when you have multiple-value fields, but just to run my function without reloading the page – grab some data from the DB and show it there on the node edit form. I have a multivalue field collection that should be populated with those values and then saved together with the rest of the node. That's why I don't want it to go ahead and save the node. However, if it isn't possible I guess I will have to find another way to do what I need.
And tried to add a submit function, still reloads the whole page.
Comment: I voted it unclear because. as you can see under schlicki's answer, two of us have read it, and understood it differently. Sure proof (for me, at least) it could use more clarity about OP's intents and needs.
Answer: Just try to use "submit" as the type and specify a custom "#submit". From the ajax_example module:
<code>$form['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('ajax_example_add_more_add_one'),
  '#ajax' => array(
    'callback' => 'ajax_example_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);
</code>
This does not submit the form with the default submit handler but with your own. In this case it is "ajax_example_add_more_add_one".
Hope it helps, j
Comment: It will still submit all values, whole `$form_state`
Comment: Is it because node edit forms define the actions additionally? I used that in custom forms and it works fine.
Comment: It works fine. It's just not quite what OP asked. Sending everything works all right - and that's the point of my answer.
Comment: OK maybe I misunderstood that. I thought the problem is that OP wants the node not being saved.. But in this case my answer won't help ;) Sry..
Comment: Or maybe I misunderstood. Let's see what others (especially OP) will say about whose interpretation is right.
Answer: Well, I happened to find this entry: Ajax Callback Function in Submit Button Doesnt Work
The answer was to remove the ID of the submit button. Which I did. Now at least I'm not getting a page reload.
I will mark this as solved. Thanks to Mołot and schlicki for their time.


Passing a node field as a contextual filter to a view pane

Question: I am trying to pass an contextual filter to a views content pane from a field in my node and have followed the procedure described in this question without success. I see that the OP of that question eventually resorted to a PHP contextual filter as well.
The only difference is that I am using Panelizer rather than Panels. My field is called field_organization_contact_recor. My view works if I test it with legal values for that field in the views UI and gives the correct results in the preview.
I have chosen "from context" and checked that I am passing the correct field in the "Argument input" settings for the views pane. I checked by using firebug to check the field name of the selected option was correct. I get "no results" for my view.
I have also tried setting it up as "Input on pane config". If I do that and pass in a hard-coded value in the pane settings I also get the correct view results in my panels page. On that settings popup there is a prompt "You may use keywords for substitutions." What is the required format of these keywords to pass a field value? I have tried the format shown on the list of built-in contexts on the contexts tab "%node:field_organization_contact_recor". This format doesn't work in my case.
Additional info: This field is CiviCRM contact reference field. Perhaps there is a particular hook that this field type doesn't implement?
Comment: These "keywords for substitution" are CTools context keywords, processed by [ctools_context_keyword_substitute( )](http://www.drupalcontrib.org/api/drupal/contributions!ctools!includes!context.inc/function/ctools_context_keyword_substitute/7).
  There is a big list of them after creating a Panel variant: in the panel's content section, unfold "Substitutions".
Answer: I found a straightforward solution for this in a comment in the issue queues:

Basically there is a Display Mode on each content type for Tokens that can be used to control exactly what is rendered by tokens that are used.
To enable it per content type, do the following:

In the actual Content Type itself, got to the "Manage Display" tab.
Scroll down to the end of the field listing and click the "Custom Display Settings" link.
Enable (Check) and Save the Token option to enable the Token Display mode.
Go to that display mode (Grey display mode tabs near the top) and any field settings you do here effect what the tokens render (which is the same ones Panels uses).
Comment: Thanks. Your answer is partially the same as mine. Your steps provide a better explanation of step 1 in my solution. I also needed a custom field formatter to get the raw value of my field available in the token display mode.
Answer: I have found that the format shown on the contexts tab (in Panelizer) which displays as "%node:field_organization_contact_recor" is indeed correct. The reason that it didn't work in my case is that the default value that gets passed by this token is the fully formatted value passed through the field's default formatter. My view needed the un-themed/un-formatted raw value of the field.
For now I have implemented a workaround using this method of:

Setting up a custom Token display mode
Writing a field formatter that outputs the raw value and using it in this display mode.

This is a good solution until we DO want to use the fully themed/formatted value as a token somewhere else on the site. I could not find a better solution despite all the interesting reading in these two relevant threads: Field Tokens and Entity tokens duplicates field tokens created by token module
Comment: For fields with simple contents (for example EntityReference, containing integers), writing a custom field formatter is not necessary to get the raw value. Just select "Format: Entity id" for the field in the Token display mode page and it will work.
Comment: Also, some "keywords for substitution" do not require setting up the Token display mode at all: `%node:nid` for the node ID works without it.
Answer: For the "Input on pane config" field, here is a solution without the Token display mode. In your case, set the parameter to:
%node:field-organization-contact-recor:cid

Explanation: CTools context keywords can be chained like Drupal [tokens]. At least the versions with dashes for underscores, but apparently not the versions with underscores. In your case %node:field-organization-contact-recor refers to a CiviCRM Contact Record, which apparently has its raw ID stored in a cid field. So we use that for chaining.
I could chain entity reference fields referring to nodes with %node:field-name:nid successfully and assume the above will be the equivalent for your case, but I did not test it in CiviCRM.


Views: Get total results

Question: I am trying to get a total count of the results using Views.  Looking at this link, Count results in Views using aggregation, I use aggregation, but Views counts each row as 1.  For example, this is what I get:
TITLE         Results
"A title"     1
"A title2"    1
"A title3"    1
etc...

I want it to be
Title
"A title"
"A title2"
"A title3"

Results: 3

Any way to do this in Views?  If not, is there a way I can weak the current Views SQL or its output instead of having to write my own module and SQL query from scratch?
Answer: Add a Global: Result summary field to the footer. There is no need to turn on aggregation.
Comment: I think you mean *Global: Result summary* not *"Global: results"* in list of things offered in Footer. So, in the View edit screen, select 'Add Footer' (middle column of the settings) then choose *Global: Result summary* And then choose from the various @ prefixed variables regarding what you'd like to display.

Views: Get total results


Is random sampling considered a random experiment?

Question: A random experiment is defined as "An experiment, trial, or observation that can be repeated numerous times under the same conditions." I was wondering if randomly sampling a part of your dataset is considered a random experiment? Say you have 3000 rows of data and you randomly sample 300 rows to make
inferences on the data. Is this considered a random experiment? Or how data is collected is considered random experiment? Say you say you record heights of kids of age 9 and their parent's heights.
Comment: The original 3000 are not at all random? Only the selection of the 300?
Comment: How would this differ from randomly drawing balls from the urn during lottery? Also, why does it matter to you? Why do you ask?
Comment: @innisfree consider original 3000 as all the responses recorded but it is random if we consider they can't record every individual for the subject the original 3000 is random as well.
Comment: @Tim I am confused on the definition of random experiment or rather how to interpret it. If I rephrase the question would random experiment be to draw random samples from my dataset or would it be considered as how the dataset is created by asking many kids and their parent's heights many times for different families?
Answer: A random experiment is an experiment or a process for which the outcome cannot be predicted with certainty (e.g. http://aix1.uottawa.ca/~glamothe/mat2377/ProbabilityI.pdf).
In statistical inference a random sample is a random variable    $X_1,\dots,X_n$ if $X_1,\dots,X_n$ are independent and identically    distributed random variables (e.g. Casella and Berger, Statistical    Inference, Duxbury, 2002).
In the statistical theory of design of experiments, randomized    experiments (NB: randomized, not random) involve randomly allocating the experimental units across    the treatment groups (e.g. https://en.wikipedia.org/wiki/Randomized_experiment); then the measures of response can be assumed to be the observed values of independent and identically distributed random variables (e.g. Cox and Reid, The Theory of the Design of Experiments, Chapman & Hall/CRC, 2000).
According to the repeated sampling principle, statistical procedured are to be assessed by their behavior in hypothetical repetition under the same conditions (e.g. Geisser, Modes of Parametric Statistical Inference, Wiley Interscience, 2006). If you can randomly extract 3000 experimental units, then other 3000 units under the same conditions, and so on, this is repeated sampling.
Repeated extraction (resampling) of 300 units from the same random sample is a statistical method named bootstrapping (e.g. https://en.wikipedia.org/wiki/Bootstrapping_(statistics).
Comment: The *randomized* experiment is exctracting 3000 people randomly from a population. Resampling 300 units could be the first step in a statistical method named bootstrapping, it is not a *randomized* experiment.
Comment: Rather than the general definitions I am asking a specific question. How would the definitions fit to my example? Where would be the random experiment in my case? You mentioned resampling 300 units randomly is bootstrapping but does that mean it is not random experiment? What about the creation of the dataset by asking many people for the specified information is that a random experiment?
Comment: That seems like a terrible definition. Whether or not something can be predicted depends on the knowledge/expertise of the experimenter.


Ordenar lista encadeada com método O(n*log(n))

Question: Eu preciso ordenar uma lista encadeada (implementação própria, sem utilizar API do Java) com um método de ordenação que possua complexidade O(n*log(n)). Pesquisando métodos que satisfaçam a condição encontrei o quicksort, entretanto, ele pressupõe acesso randômico aos elementos que serão ordenados, o que é inviável no caso da lista.
Assim, tive a ideia de copiar todos os elementos da minha lista para um vetor, realizar a ordenação com quicksort e copiá-los novamente para a lista depois de ordenados. Essa solução é viável? Ela é capaz de manter a complexidade desejada?
Além disso, existem outros métodos com essa mesma complexidade que se adequem mais à lista encadeada?
Answer: A pergunta é de algo que pode garantir a complexidade, não fala em nada relacionado com a velocidade, são conceitos diferentes.
Lista encadeada com essa complexidade é difícil encontrar, só quicksort não consegue esta complexidade. Copiando antes só piora a situação.
Copiar para outra estrutura pode dar mais velocidade, mas não dar esta complexidade.
Parece que alguém conseguiu fazer com mergesort, mas sem copiar nada antes :) A resposta aceita em pergunta no SO fala justamente desta solução.
O mergesort, assim como o heapsort, conseguem dar a complexidade exigida na pergunta. Estes são dois algoritmos bem conhecidos, claro que depende um pouco da implementação. O problema destes dois algoritmos é que ele consome muito espaço - O(N). A pergunta não fala nada em espaço, mas especificamente por ser uma lista ligada, estes algoritmos conseguem O(1).
Dá uma olhada no Radix, ele costuma operar milagres, mas é difícil implementar.
Essa tabela pode ajudar ainda que não seja específico para linked list, o algoritmo implementado adequadamente pode garantir a complexidade exigida.
Coloquei no GitHub para referência futura.
Answer: Baseado na tabela linkada pelo @Maniero, há pelo menos 4 algoritmos de ordenação que, na média, são de complexidade O(n*log(n)), a saber:

Quicksort
Mergesort
Timsort
Heapsort

Copiar os dados para um array pode ser uma opção
A página do Heapsort na Wikipédia diz:

Merge sort can be adapted to operate on singly linked lists with O(1) extra space. Heapsort can be adapted to operate on doubly linked lists with only O(1) extra space overhead.

Traduzindo:

Mergesort pode ser adaptado para funcionar em listas singularmente encadeadas com espaço extra O(1). Heapsort pode ser adaptado para funcionar em listas duplamente encadeadas com aumento do espaço extra de apenas O(1).

Infelizmente não tem exemplo nem referência. Como fazer isso? Basicamente você pode trocar o acesso aleatório de vetor por referências aos elementos da lista encadeada.
No caso do Heap sort, o algoritmo da Wikipédia tem um trecho assim:
end ← count - 1
while end > 0 do
    (a[0] is the root and largest value. The swap moves it in front of the sorted elements.)
    swap(a[end], a[0])
    (the heap size is reduced by one)
    end ← end - 1
    (the swap ruined the heap property, so restore it)
    siftDown(a, 0, end)

Então, por exemplo, aonde há incremento ou decremento, basta substituir isso por um avanço ou retrocesso na lista. Onde há referência ao primeiro elemento, usa-se uma referência ao primeiro, o mesmo se faz com o último.
Exemplo:
procedure heapsort(first, last, count) is
    input: first and last elements of a doubly linked list with length of count

    heapify(first, last, count)
    end ← last
    while end.previous != null do
        swap(end, first)
        end ← end.previous
        count ← count - 1
        siftDown(first, end, count)

procedure heapify(first, last, count) is
    start ← iParent(first, count)
    while start != null do
        siftDown(start, last, count - 1)
        start ← start.previous
        count ← count - 1

procedure siftDown(start, end, count) is
    root ← start
    while iLeftChild(start, root, count) ≤ end do
        child ← iLeftChild(start, root, count)
        swap ← root
        if swap.value < child.value
            swap ← child
        if child.next.value ≤ end.value and swap.value < child.next.value
            swap ← child.next
        if swap.value = root.value
            return
        else
            swap(root, swap)

Note que no meu exemplo acima, cada elemento (first, last, start, end, root, swap) agora é na verdade uma referência que contém 3 atributos: value, previous e next.
Ainda resta implementar as rotinas iParent(start, count) e iLeftChild(start, end, count).

iParent basicamente precisa encontrar o elemento central. Isso não é trivial em listas encadeadas, mas pode ser facilmente implementado já que temos a referência ao primeiro elemento e a quantidade. Tudo o que precisa ser feito é avançar floor((count-1) / 2) vezes a partir do primeiro elemento.
iLeftChild basicamente avança 2*i + 1, sendo i a posição do elemento root em relação à start. Então pode ser facilmente implementado avançando uma referência count + 1 vezes a partir de root.

Isso funciona? Deveria, mas não testei. Implemente por sua conta e risco, considerando que as rotinas de busca descritas acima vão deixar o algoritmo um pouquinho mais lento, embora eu acredite que outras formas de otimização podem ser encontradas.
Answer: Copiar pode não ser uma má ideia.
O(n*log n + n) para um n suficientemente grande pode ser considerado o mesmo que O(n*log(n)).
Note, entretanto, que a notação Big-O é um direcionamento muito importante, mas não definitivo no momento de fazer análises práticas de algoritmos. Existem vários detalhes de otimização de hardware que não são levados em conta em uma análise puramente Big-O.
Comment: O Downvoter poderia sinalizar, por favor, o problema que viu na resposta?


Drupal 7 template_preprocess_block

Question: I am trying to alter content of the system main block but only on the front page. I have added template_preprocess_block() in the template.php file, but is_front is FALSE even though I am on the front page of the site?
I use the Context module to control blocks, but the main block is the only one I have added using /admin/structure/block not Context.
Update
I have also tested hook_block_view_MODULE_DELTA_alter() but is_front is not passed to this function.
Update
Even though I disable the Main page content block front the Content region, I still see a node on the front page, publishing options set to published, promoted to front.
Doing this on a fresh install locally.
Enabling the Main page content block and setting "All pages except those listed" to  doesn't change anything - still looking at my node.
Answer: Use function drupal_is_front_page().
Answer: simplest and most straightforward solution:
Create two versions of that block and from this textarea select where the block should be

then do the appropriate configuration.
Comment: yeah, that could be an option
Comment: weird but remoning the main block from the content region has no effect. I still see content on the front page.
Answer: you could try something like this, even if the conditions aren't exactly the same:
<?php
    // works with paths like 'home' too, as well as 'node/2'
    $is_front_page = ($_GET['q'] == variable_get('site_frontpage', 'node') || drupal_get_path_alias(current_path()) == variable_get('site_frontpage', 'node'));
?>

borrowed from here

Drupal 7 template_preprocess_block


Explanation of Two Propositions on Random Variables from Rice 3rd Edition

Question: There are two propositions I'm struggling with interpreting what they really mean. Perhaps I'm expecting more even though they appear simplistic:

$X$ is defined as a random variable, with density $f$ and cdf $F$. With the appropriate conditions to make them "nice".
First is my understanding of Proposition C. Z is usually reserved for a standard normal random variable and I took it as such. So in my mind what proposition C is saying is "Let our standard normal random variable be a function of an arbitrary CDF. Then our standard normal random variable has a uniform distribution on $[0,1]$." But here is where it get's cloudy for me.....we have this standard normal random variable, this standard normal random variable is going to have a distribution, since it has been declared as a "standard normal random variable" I would assume that its distribution would be "normally distributed". The values for this standard normal random variable, $Z$, happen to come from the CDF of some other random variable, $X$. I see the proof and the steps of the proof are very simple and sound, but the concept is not clicking with me.
With regards to Proposition D I understand what that is saying. In practice we would start with a CDF, $F(x)$ and rearrange things in a way to apply a uniform random generator.
Help with interpreting Proposition C?
Comment: You've correctly identified the dissonance. While you are used to seeing $Z$ as a standard normal variable, it doesn't necessarily always mean such. Here it does not: $Z$ is defined as the random variable $F(X)$. If it helps, just replace every occurrence of $Z$ with $Y$ in the proposition.
Comment: In Proposition C, $Z$ is not assumed to be a standarnd normal random variable.  It is just defined by $Z := F(X)$.
Comment: @dc3rd No, it is crucial that $F$ is CDF of $X$ to be able to say anything about $F(X)$. Moreover, it does not hold for any $X$, but it is important that $F$ is continuous (it not necessarily needs to have inverse, tho (but the proof goes a little bit different, with generalised inverse function))
Comment: It should be specified that $F$ is CDF of $X$. Writing $F(X)$ to mean that $F$ is CDF of $X$ is incorrect, because $F(X)$ is meant to be a random variable, such that $F(X)(\omega) = F(X(\omega))$. You can always write $F_X$ to denote the CDF of $X$ which is as far as I know, one of possible ways to specify so.
Comment: And answering to your second question, yes, if $F_X$ is continuous, then you can conclude that $Z:= F_X(X)$ is a uniform random variable on $[0,1]$
Comment: `Z has a uniform distribution ...` Got it?
Comment: @GregMartin, so if I'm understanding this proposition right this is a somewhat major implication....that any random variable that happens to be a function of the CDF of another random variable is always uniformly distributed on $[0,1]$?
Comment: doesn't $F(X)$ mean that $F$ is $CDF$ of $X$?......That's how I interpreted it. So if $F$ is the $CDF$ of $X$ and is continuous, then I could conclude that $Z$ would be uniform? @DominikKutek
Comment: I see what you mean and I do agree. The idea does get clouded in what I wrote. Thanks for the clarification.
Comment: Do you want to put the explanation in an answer so I can give you the sacred green check mark?
Answer: In proposition C and D, what is missing are the assumptions.
Proposition C should be stated: If $X$ is a random variable with continuous CDF $F_X$ then random variable $Z:= F_X(X)$ is uniformly distributed on $(0,1)$ (it's the same as uniformy distributed on $[0,1]$)
The proof that is in the book, assumes that $F$ has inverse $F^{-1}$ (just to have simplier proof, but it isn't necessary for proposition C to hold). Moreover, in the proof, it should be said that those equations are true for $z \in [0,1]$, otherwise we have for $z<0$: $\mathbb P(Z \le z) = \mathbb P(F_X(X) \le z) = 0$ (since $F_X$ is a function with values in $[0,1]$) and for $z>1$ we have $\mathbb P(Z \le z) = \mathbb P(F_X(X) \le z)=1$, since as we said before, function $F_X$ always takes values less or equal to $1$.
Proposition $D$ is okay, but we need to know that $F$ is right continuous function, non-decreasing with values in $[0,1]$. Proposition assumes that $F^{-1}$ exists, which again isn't neccesary, but then you need the notion of generalised inverse to write the proposition $D$.
Comment: Hi I was just going over the contents of this solution again and wanted to make sure I have the proper comprehension with regards to Proposition C.  So in my words Proposition C is saying: "$Z$ is the random variable defined as the set of values that the cdf of $X$ takes on at all points defined for random variable $X$. This random variable $Z$ is uniformly distributed over $(0,1)$"


Chamar um método de uma classe interna desde fora

Question: Tenho uma classe B e nessa classe necessito chamar um método, getSomething(type, option), que se encontra definido numa classe A que é uma classe que extends AsyncTask e que se encontra dentro da classe C.
A minha classe C está definida da seguinte forma:
public class C extends BaseActivity{
(...)
 public class A extends AsyncTask<String, Void, String> {
 (...)
  public String doInBackground(String... params) {
  (...)
  }
  public String getSomething(String type, String option){
  (...)
  }
  protected void onPreExecute() {
  (...)
  }
  protected void onPostExecute(String result){
  (...)
  }
(...)
}

O que estou a tentar fazer é dentro da classe B, dentro de um método colocar esta chamada ao método getSomething():
String sentence = new C().new A().getSomething(type,option);

também já tentei:
new C().new A().execute();

Não consigo chamar o método porque me dá excepção
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference

sempre que é executada a chamada ao método getSomething(...).
Alguém pode ajudar, para saber como posso chamar o procedimento desde outra classe?
Answer: Para instanciar uma classe interna fora da classe onde foi declarada, é necessário primeiro criar uma instância da classe externa e usar a sintaxe objectoExterno.new ClasseInterna() para criar o objecto interno.
ClasseExterna objectoExterno = new ClasseExterna();
ClasseExterna.ClasseInterna objectoInterno = objectoExterno.new ClasseInterna();

No seu caso, como a classe C é uma Activity, isso não pode ser feito porque uma Activity não deve ser instanciada através do operador new.
A solução passa por transformar a classe interna numa classe normal e instanciá-la da forma habitual em cada uma das classes.
Comment: Obrigada. Fiquei esclarecida.
Answer: Na classe 'A', crie a instância:
public static A a;

Agora na sua classe 'B', chame:
A.a.getSomething();

Não testei se funciona, mas deve funcionar!


Nested if (rising_edge(clk)) statements in VHDL

Question: so I've come across some old code that I have to replicate, but it won't compile with the new Xilinx compiler, so I need to figure out exactly what it does. I have something like this:
if rising_edge(clk) then
   —do some things
   if rising_edge(clk) then
      —do some other things
   end if
end if

Does it take 2 clock cycles to get to the inner if statement, or is the second if statement simply redundant?
Also, Xilinx gives the error: "Logic for signal  is controlled by a clock but does not appear to be a valid sequential description"
Thanks, and any help is appreciated.
Answer: Given that rising_edge(clk) is true for the first if, surely it's still true at the second nested if.  This assumes no time has passed within the -- do some stuff section, which is presumably the case.
Therefore, that second if could be replaced by if true then... or indeed left out!
Answer: That just plain won't synthesize in any tool I have seen. Don't do it, even for simulation.
The second statement rising_edge isn't a sequential statement, e.g. an assignment. It is a statement that involves time so that's how you can be sure.
Comment: I can't get it to synthesize either, and honestly it's not anything I would ever think of writing. I'm just trying to determine the intent of the original author so I can re-wirte the code. Apparently with an old synthesizer this used to work, or so I'm told.
Comment: The second if does not involve time passing, it's the same test as the first one (if clk = '1' and clk'event)
Answer: If it synthesized before it was a synthesizer failure/bug. How sure are you that the code matches what was tested and determined to be working?  (It sounds like you only have someone's word for this being the correct code that was synthesized before.)
Is the existing system available for comparison and testing?  What are the tool versions involved?  Can you use the old tools and verify it synthesizes and what warnings it provides?  Depending on what version you are using you might be able to use the synthesis report, fpgaeditor (or similar) to look at what actually synthesized.
Or you can analyze the code to see what the designer intended and duplicate that with valid HDL.
Failing that all you have left is trial and error.
Try assuming:

The statements inside the nested rising edge are always active.  (Remove the nested rising edge if statement leaving the code block it surrounded).
The statements inside the nested rising edge are never active.  Remove the entire nested rising edge block.
You could try it but I really can't imagine how a synthesizer would create a 2 cycle delay out of this. You might be reduced to trying this or other even more unlikely situations.  It gets really hard to predict what this failure mode would be.
Comment: I'm not so sure that it would be a bug if a synthesizer would accept this. The second if-statement would always pass in a simulation (the same condition is tested). While it makes sense for a synthesis tool to refuse two nested edge conditions, it would also make sense to just ignore the second condition. That said, the code should really be changed so that it would only have a single edge detection.
Comment: Thanks for such a great reply! I'm pretty sure that I'm able to determine what the original authors intent was from the rest of the code (no comments, mind you) and I'm going to try and implement that and see what happens. Thanks for the help!
Answer: actually what you want to infer is nested clocked processes.
This shouldn't synthesize since it doesn't represent meaningful hardware.
You should rewrite your code, accordingly to xst.pdf (e.g. if you use Xilinx ISE).
Kind regards,
Nikolaos Kavvadias


C# Listbox: Display custom items in listbox

Question: I have an object I created in C#, lets call it "listBoxCustom".
I want to store listBoxCustom in my listbox object, and i have a number of listBoxCustom objects.
I want to display a given name that I set for each object in the listbox, but as of right now it is displaying "myProject.listBoxCustom" in the nodes of the listbox, for as many items as I have added.
What do I need to do such that it will display the correct name that I want? I am assuming I need to create a certain property of my object and the listbox will by default try and access this, I am just not sure what it is.
Please let me know if you need additional detail, and thank you in advance.
Comment: http://www.java2s.com/Code/CSharp/GUI-Windows-Form/AddObjecttoListBox.htm This shows the solution. Basically when being displayed the system is casting your object ToString(). You just need to override what this behavior is doing, and it will give you whatever you want.
Answer: Simply override ToString method in your listBoxCustom class.


CUBA : injecting a datasource in a frame dynamically

Question: Relates to question CUBA : entity inheritance
I have:
- Customer entity (name, email)
- Company extends Customer (industry)
- Person extends Customer (firstName, lastName)
I would like to design following screens:
- CustomerEditFrame, no datasource defined
- CompanyEditScreen embedding CustomerEditFrame
- PersonEditScreen embedding CustomerEditFrame
Then I need to define the datasource of the frame:
- In CompanyEditScreen, a companyDs needs to be defined for the frame
- In PersonEditScreen, a personDs needs to be
Options I see:
1) In all screens embedding the frame, use the same datasource name (e.g customerDs) so that it can be injected in the frame : confusing, if I have a Company Datasource I would like to call it companyDs and not customerDs
2) From the frame, call getDsContext().get(ds_id) : nok, because name of ds changes
3) From the frame, iterate on getDsContext().getAll() and look for a datasource over a Customer class or a subclass and ensure there is only one : not safe, not sure to get the right one
4) From the screen, e.g CompanyEditScreen, assign the companyDs to the frame in the init() method : no method to do so per se
Have looked through all the samples (including sampler code). The case that is closer is the OrderEdit screen of the Sales sample which dynamically open a frame depending on the Operation type. It does not cover inheritance but the solution used is based on datasource name (1st option, which I find confusing when dealing with children classes).
How should I do ?
Comment: When you write about the case of using dynamic opening of frames, you probably mean the Akkount sample and its OperationEdit screen.
Answer: I would suggest passing an entity instance to the frame instead of passing or referencing the whole datasource, as explained here.
When the screen with two datasources containing the same instance (one in the screen and one in the nested frame) will be committed, there will be no any duplication because screen collects data from all dirty datasources into a single Set.


Opening My Documents prompts for credentials in redirected environment

Question: We have a class infrastructure with classes consisting of "user" pc's and a single "teacher" pc. The fileserver has a folder for the teacher's "my documents", in which there are folders for each of the student users. Both types of accounts have their "my documents" redirected to these folders.
We use this nested structure so that the teacher has access to their documents in an easy way, allowing him for instance to put new shortcuts on their desktop or collect files.
The problem is that (only recently, apparently) whenever a user tries to insert files from My Documents into a powerpoint for instance it will prompt for credentials to the server. You can press cancel and re-enter the folder and it will work fine. Restart powerpoint (or whatever Office application) and you get prompted again. Apparently it's the same for their desktop, which is also redirected. Browsing to My Documents in explorer should work fine.
It's a bit vague, but the teachers aren't the best in supplying feedback. I tried to explain as best I could.
EDIT: removed link to the other issue as it was unrelated and now solved
Thanks a bunch
Comment: How is the redirect set up?  UNC path, HTTP?
Comment: UNC indeed. \\server\folder (windows fileserver)
Comment: I should add: actually logging in and choosing to remember the credentials does not change anything!
Comment: Other problem is now clearly unrelated, it was something by design that I didn't know about. So just this one remains...
Comment: I'm surprised there weren't issues with permissions when it came to redirecting something that belongs in a user profile. Especially as MS has been tightening how profiles and security works. You're saying that the teacher user's My Docs is being accessed by all the students as well? Why not map a share to something like G: and give permissions for everyone from that? Minimal training to have them go to g:\folder\file.doc, might save on permission hassles too. That's just me though.
Comment: the teacher's docs are not being accessed by the users, its just the teacher that has access to the user's my docs. everything else works with regular shares
we get no real permissions errors other than the credentials prompt
Answer: Even though this post is old, I came across the same thing today with Windows 7 clients accessing redirected folders on a Windows Server 2012R2 with Excel 2013. So the problem is still there.
Problem Reproduction
Since the original description was a bit vague here is the exact way to reproduce the problem:

"my documents" (or probably any other library) is redirected to a server share
"my documents" contains an MS Excel (probably any MS Office) document.
create a link to that document in another redirected library, for example on the "desktop".
trying to open the document by double-clicking the link will prompt for the user's credentials, while a double-click directly on the file in "my documents" works fine.

It is interesting to note that this only happens when creating the link from within a redirected library like "my documents". If you access the same shared folder directly by its UNC path and create the link from there, everything works fine as well.
The Solution that worked for me
It is a permission problem on the redirected folders share, even though it looks fine at first and is perfectly accessible for other programs than MS Office.
The shares that host redirected folders need exactly these permissions, as documented by Microsoft (as early as Windows Server 2003):
on the share:
EVERYONE:F (or at least F for the users that access the share)

in the file system:
CREATOR OWNER - Full Control (Apply onto: Subfolders and Files Only)
System - Full Control (Apply onto: This Folder, Subfolders and Files)
Domain Admins - Full Control (Apply onto: This Folder, Subfolders and Files)
Everyone - List Folder/Read Data (Apply onto: This Folder Only)
Everyone - Read Attributes (Apply onto: This Folder Only)
Everyone - Traverse Folder/Execute File (Apply onto: This Folder Only)
Everyone - Create Folder/Append Data (Apply onto: This Folder Only)

I was missing the last 2 permission entries, thinking I could get away with just read access. Adding those 2 entries, which seem totally unrelated, solved the problem.
Answer: To clarify:
C:\users\Teacher\Documents is shared, and contains
user1\
user2\
.
.
usern\

Recall that Windows authentication is based on "most restrictive" so if you've a Deny in the mix it will trump any Allow for the same resource to the same entity.  User folders also typically have very restrictive access by default.
I would recommend that you redirect to a network share outside of the \users\ folder (or \Documents and Settings\ for pre-Vista/Server 2008 environments).  Instead, create a new folder off the root or on a file server if you've one available, share that, and give the teacher Read access.  Each user folder under that can then inherit that Read, and be assigned Full Control to the person it's assigned to.  That SHOULD allow a single sign-in when Windows starts and re-establishes the persistent mapped share, rather than when each app is started and hooks the My Documents redirect.


PHP Problem accessing the global variable

Question: I'm having problem with global variable in PHP. I have mysqli config file which contains only following data:
$mysqli = new mysqli("localhost", "user", "pass", "db");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

I have the following class on another file:
class user{

function username_exists($username){
    global $mysqli;
    if ($stmt = $mysqli->prepare("SELECT username FROM users WHERE username=?")) {
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->store_result();
        $count=$stmt->num_rows;
        $stmt->close();
    }
    return ($count > 0 ? true : false);
    }

    ...
    some more functions
    ...

    }

Now this works fine, but in my previous question on SO, i was told that it is a bad practice to access global variable like I'm doing in above class. So, I'm trying to pass the global variable in the constructor, in following way:
private $mysqli;
      function __construct()
      {
        global $mysqli;
        $this->mysqli = $mysqli;
      }

    function username_exists($username){
    //global $mysqli;
    if ($stmt = $this->mysqli->prepare("SELECT username FROM users WHERE username=?")) {

And I get the following error:
Fatal error: Call to a member function prepare() on a non-object in...(line number)

Can you please tell me whats problem with it and how this can be fixed? Thanks.
Edit: Sorry for the spelling mistake of __construct. It was only mistake typing here, and the error isnt because of that.
Comment: why u write `private $mysqli;` on last code block
Answer: Well... having global in your constructor kindof beats the point. Consider passing it in as a parameter __construct($mysqli).
  public function __construct($mysqli)
  {
    $this->mysqli = $mysqli;
  }

What you're trying to do here is called dependency injection.
Answer: I think the problem is you misstyped __construct try changing your __cuntruct to the right name for the constructor.
The global in username_exists is also useless.
You should also write a constructor which takes the variable as argument and avoid using global completly :
class User {
     var $mysqli;

     function __construct($mysqli) {
         $this->mysqli = $mysqli;
     }

     [ ... some functions ... ]
}

You must create your object like this :
$myuser = new User($mysqli);
$myUser->prepare();

Comment: Thanks for your reply. I'm sorry I mistyped the construct, but that was not the problem. I tried using the method you described and i get 2 errors, first Warning: `Missing argument 1 for user::__construct(), called in ...` and the second error is same which i mentioned in my original post. Can you please have a look the code of my config file which I have put in original file. Thanks again.
Comment: You must pass your $mysqli variable when you create your object. I think you should read the PHP documentation about objects : http://php.net/manual/en/language.oop5.basic.php It seems to me that you don't really understand what you're doing. BTW, I updated my post with a little example on how you should create the object
Answer: Your constructor is not getting called because it is not the constructor at all
__cuntruct

should be
__construct

Comment: I am facing this problem on SO that someone downvote and did not respond why he did? Downvote, it is okay but care to leave comment
Comment: Probably someone trying to cancel my upvote so their answer ranks higher... Your answer is correct and was the quickest at being so.
Answer: The code as written was not really what the others on SO were attempting to encourage you to do.
function __construct($mysql_handler){
  $this->mysql = $mysql_handler;
}

This is passing in the parameter into the object scope at construction.  When you create an instance of your object, you would pass in the MySQL handle.
$mysqli = new mysqli("localhost", "user", "pass", "db");
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$u = new User($mysqlli);

Then you should be able to call mysqli member functions on the property itself.
Your constructor is also misspelled.  It will only work properly with the magic method name __construct().
Answer: Couple of things.  I think it would work OK if you changed __cuntruct to __construct.
You're still using the global declaration inside the username_exists function.  Why not just pass the $mysqli variable in the constructor?
function _construct($mysqli) {
    $this->mysqli = $mysqli;
}

then you have no globals in the class.
Comment: Thanks for the reply, however the spelling mistake was only typing here, sorry for that. I've fixed that, and also tried passing the variable in the constructor, it still gives same error. If you see my config file code above, Do i need to change anything in that? Thanks.
Answer: Remove global $mysqli; in the function username_exists(), it does not makes sense.
The global $mysqli; is not required/does not makes sense since you want this variable to store the reference the connection IN THE CONTEXT of your object.
Answer: change  __cuntruct() to __construct()


How to Compare Cell Positions in Excel VBA?

Question: Okay, so basically I want to determine if the row position found for a certain string is below that for another string.  If it is, I need to set the value to zero.  I've tried many variations of this but it doesn't appear as though I can compare ranges in this way.  Is there another way to get the cell position so I can do this comparison?
<code>    If i < 56 Then
        If Rng4(j) < Rng5(i + 1) Then
            Rng4(j).Activate
            X(i, j, 1) = ActiveCell.Offset(0, 1)
            X(i, j, 2) = ActiveCell.Offset(0, 2)
        Else
            X(i, j, 1) = 0
            X(i, j, 2) = 0
        End If
    End If
</code>
Answer: You need to compare the Row property of your ranges
<code>If i < 56 Then
    If Rng4(j).Row < Rng5(i + 1).Row Then
        Rng4(j).Activate
        X(i, j, 1) = ActiveCell.Offset(0, 1)
        X(i, j, 2) = ActiveCell.Offset(0, 2)
    Else
        X(i, j, 1) = 0
        X(i, j, 2) = 0
    End If
End If
</code>
Comment: Thank you so much for the quick answer :)  As you can probably tell I'm still fairly new to all this!


How to interpret crash reports that are not fully symbolicated in firebase?

Question: We use firebase crash analytics in our app, it helped us solve bugs quick by specifying function name and even line numbers too, but sometimes it only gives

appDelegate.swift [start + 17644]

how can I intrpret this report? and why it appears like that ?
this is the full trace with threads, the app name is replaced by appName
Exception name: EXC_SOFTWARE / UNCAUGHT_NS_EXCEPTION
1 CoreFoundation __exceptionPreprocess + 1241536
2 libobjc.A.dylib objc_exception_throw + 34136
3 CoreFoundation -[__NSPlaceholderDictionary initWithObjects:forKeys:count:] + 80952
4 CoreFoundation +[NSDictionary dictionaryWithObjects:forKeys:count:] + 80552
5 FBSDKCoreKit 4304632780 + 244684
6 FBSDKCoreKit 4304632048 + 243952
7 FBSDKCoreKit 4304437716 + 49620
8 CoreFoundation __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 823848
9 CoreFoundation _CFXRegistrationPost + 821548
10 CoreFoundation ___CFXNotificationPost_block_invoke + 820904
11 CoreFoundation -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1276824
12 CoreFoundation _CFXNotificationPost + 44016
13 Foundation -[NSNotificationCenter postNotificationName:object:userInfo:] + 26152
14 UIKit -[UIApplication _deactivateForReason:notify:] + 491392
15 CoreFoundation __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 823848
16 CoreFoundation ___CFXRegistrationPost_block_invoke + 823692
17 CoreFoundation __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 905564
18 CoreFoundation __CFRunLoopDoBlocks + 903512
19 CoreFoundation __CFRunLoopRun + 896080
20 CoreFoundation CFRunLoopRunSpecific + 36932
21 GraphicsServices GSEventRunModal + 49556
22 UIKit -[UIApplication _run] + 504568
23 UIKit UIApplicationMain + 483376
24 appName main (AppDelegate.swift:18)
25 libdyld.dylib start + 17844

Thread 2
1 libsystem_kernel.dylib mach_msg_trap + 4460
2 libsystem_kernel.dylib mach_msg + 4056
3 CoreFoundation __CFRunLoopServiceMachPort + 904424
4 CoreFoundation __CFRunLoopRun + 895236
5 CoreFoundation CFRunLoopRunSpecific + 36932
6 Foundation -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 51848
7 Foundation -[NSRunLoop(NSRunLoop) runUntilDate:] + 185720
8 UIKit -[UIEventFetcher threadMain] + 10422824
9 Foundation __NSThread__start__ + 1090680
10 libsystem_pthread.dylib _pthread_body + 14412
11 libsystem_pthread.dylib _pthread_start + 14172
12 libsystem_pthread.dylib thread_start + 3496

Thread 3
1 libsystem_kernel.dylib mach_msg_trap + 4460
2 libsystem_kernel.dylib mach_msg + 4056
3 CoreFoundation __CFRunLoopServiceMachPort + 904424
4 CoreFoundation __CFRunLoopRun + 895236
5 CoreFoundation CFRunLoopRunSpecific + 36932
6 CFNetwork +[NSURLConnection(Loader) _resourceLoadLoop:] + 847820
7 Foundation __NSThread__start__ + 1090680
8 libsystem_pthread.dylib _pthread_body + 14412
9 libsystem_pthread.dylib _pthread_start + 14172
10 libsystem_pthread.dylib thread_start + 3496

Thread 4
1 libsystem_kernel.dylib mach_msg_trap + 4460
2 libsystem_kernel.dylib mach_msg + 4056
3 CoreFoundation __CFRunLoopServiceMachPort + 904424
4 CoreFoundation __CFRunLoopRun + 895236
5 CoreFoundation CFRunLoopRunSpecific + 36932
6 Foundation -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 51848
7 Foundation -[NSRunLoop(NSRunLoop) run] + 397836
8 appName +[GAI threadMain:] + 1782640
9 Foundation __NSThread__start__ + 1090680
10 libsystem_pthread.dylib _pthread_body + 14412
11 libsystem_pthread.dylib _pthread_start + 14172
12 libsystem_pthread.dylib thread_start + 3496

Thread 5
1 libsystem_kernel.dylib mach_msg_trap + 4460
2 libsystem_kernel.dylib mach_msg + 4056
3 appName google_breakpad::ExceptionHandler::WaitForMessage(void*) + 2388144
4 libsystem_pthread.dylib _pthread_body + 14412
5 libsystem_pthread.dylib _pthread_start + 14172
6 libsystem_pthread.dylib thread_start + 3496

Thread 6
1 libsystem_kernel.dylib mach_msg_trap + 4460
2 libsystem_kernel.dylib mach_msg + 4056
3 CoreFoundation __CFRunLoopServiceMachPort + 904424
4 CoreFoundation __CFRunLoopRun + 895236
5 CoreFoundation CFRunLoopRunSpecific + 36932
6 GeoServices _runNetworkThread + 4308864
7 libsystem_pthread.dylib _pthread_body + 14412
8 libsystem_pthread.dylib _pthread_start + 14172
9 libsystem_pthread.dylib thread_start + 3496

Thread 7
1 libsystem_kernel.dylib __workq_kernreturn + 129672
2 libsystem_pthread.dylib _pthread_wqthread + 4952
3 libsystem_pthread.dylib start_wqthread + 3488 arrow_drop_down

Thread 8
1 libsystem_kernel.dylib __workq_kernreturn + 129672
2 libsystem_pthread.dylib _pthread_wqthread + 4468
3 libsystem_pthread.dylib start_wqthread + 3488 arrow_drop_down

Thread 9
1 libsystem_kernel.dylib __workq_kernreturn + 129672
2 libsystem_pthread.dylib _pthread_wqthread + 4952
3 libsystem_pthread.dylib start_wqthread + 3488

Thread 10
1 CoreFoundation> -[__NSDictionaryM countByEnumeratingWithState:objects:count:] + 86492
2 appName +[FIRAEvent normalizedParametersForParameters:isPublicEvent:] + 1999144 3 appName +[FIRAEvent normalizedParametersForParameters:isPublicEvent:] + 1999144 4 appName -[FIRAEvent initWithOrigin:isPublic:name:timestamp:previousTimestamp:parameters:] + 2002028
5 appName +[FIRAnalytics logEventOnSerialQueueWithOrigin:isPublicEvent:name:parameters:timestamp:ignoreEnabled:ignoreInterceptor:addedScreenParameters:] + 2195924
6 appName __65+[FIRAnalytics logEventWithOrigin:isPublicEvent:name:parameters:]_block_invoke_3 + 2195040
7 libdispatch.dylib _dispatch_call_block_and_release + 4604
8 libdispatch.dylib _dispatch_client_callout + 4540
9 libdispatch.dylib _dispatch_queue_serial_drain + 62528
10 libdispatch.dylib _dispatch_queue_invoke + 18852
11 libdispatch.dylib _dispatch_root_queue_drain + 70536
12 libdispatch.dylib _dispatch_worker_thread3 + 69864
13 libsystem_pthread.dylib _pthread_wqthread + 4788
14 libsystem_pthread.dylib start_wqthread + 3488

Comment: Please provide a full crash report including the exception or signal information, at least a full stack trace.
Comment: @Kerni : the traces are added.
Answer: Your app crashed because of an exception. As your data doesn't show the exception string, it is unknown what kind of exception triggered the crash.
The exception was raised due to a problem in the FBSDKCoreKit framework, which is likely the Facebook 3rd party SDK. As you most likely didn't upload the debug symbols of that framework to Firebase, they couldn't symbolicate them and provide the classes and methods being called in those frames.
The exception is triggered by a problem with handling of an NSDictionary object, could be trying to insert a nil value for a key, but that is just a guess.
As the only non system frames in the resulting stack trace are from your apps call, Firebase grouped the crashes by that call instead of the calls in FBSDKCoreKit.
To learn more about those crashes you need to upload the symbols of the FBSDKCoreKit framework. With the given information it is impossible to know what the crash is about and how to fix it.
Comment: I uploaded new symbolication files, it will only affect the next exception firebase says.
Comment: Did you make sure to upload the symbol files of the facebook framework?
Comment: in this very same error stack, firebase now says
"Future stack traces for UUID xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx will be symbolicated using the uploaded symbol file".


Obter dados via JSON por URL em C#

Question: Estou precisando obter dados via JSON, através de uma URL, este link: https://cryptohub.online/api/market/ticker/egx/
Estou tentando com o código abaixo, mas já recebo erro assim que ele faz o download da string.
O erro recebido é:

A cadeira de caracteres não está no formato JSON.

Porém, pelo (pouco) que entendo, me parece que o retorno está OK no formato.
Alguma idéia do que pode estar acontecendo?
Este é meu código:
using (var webClient = new System.Net.WebClient())
        {
            var json = webClient.DownloadString("https://cryptohub.online/api/market/ticker/EGX/");

            dynamic obj = JsonConvert.DeserializeObject(json);

            var btc = 0.0;

                foreach (var result in obj.BTC_EGX)

                btc = result.last;

Answer: Olá! houve uma atualização no protocolo TLS para o 1.2 com isso chamadas https deixaram de funcionar por estarem setadas ao antigo TLS 1.0. Seta o Secutiry Protocol do System.Net conforme adicionei no seu exemplo abaixo. abs
using (WebClient webClient = new System.Net.WebClient())
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            var json = webClient.DownloadString("https://cryptohub.online/api/market/ticker/EGX/");

            dynamic obj = JsonConvert.DeserializeObject(json);

            var btc = 0.0;

            foreach (var result in obj.BTC_EGX)

                btc = result.last;

        }

Comment: você só precisa adicionar a referencia, o `using`, para o `ServicePoint Manager`. Se não me engano é: `using System.Net;`.
Comment: Isso mesmo; precisa adicionar a referencia "using System.Net" pois o objeto que você irá setar o tls está dentro dela.
Comment: Oi Paulrocost, deu erro ao compilar:
Erro  O nome 'ServicePointManager' não existe no contexto atual
Comment: amanhã retomo pra tentar resolver isso aqui, de qualquer maneira, obrigado pela força!
Comment: Perfeito Resolveu o problema! Muito obrigado @paulocost e vhoyer

Obter dados via JSON por URL em C#


how to use corresondence theorem

Question: Suppose $A$ is a normal subgroup of $B$ and $B/A$ is an cyclic group with infinite order. I want to show $B$ has a normal subgroup of index $k$ for every $k$ positive using correspondence theorem, I am not sure how to start this one.
Answer: The correspondence theorem works with quotients. The quotient you have is $B/A$. The theorem tells you to lift a subgroup of $B/A$ to an intermediate subgroup between $B$ and $A$. You're looking for a subgroup of $B$ of index $k$. You might as well put it between $B$ and $A$, if you're going to use the given information and the tool at hand like you're supposed to. If you do, $B\ge M\ge A$, if we want to know about the index we would use the formula $[B:M]=[B/A:M/A]$. So you're looking for a subgroup of $M/A\le B/A\cong\Bbb Z$ of index $k$. Which is obviously possible.

how to use corresondence theorem


Monitoring/debugging memory usage C

Question: I have an issue with my program using much more memory than I think it should
I've used valgrind and it has been a godsend for discovering memory problems such as buffer overruns and memory leaks
Problem I have here is that it doesn't look like its a leak, just usage that is inconsistent with what I think it should be
Is there another tool that you can use to monitor memory usage in the same way you might monitor variable values using a debugger such as gdb?
massif has told me that the lion share of the heap memory is being allocated via this statement:
->98.80% (1,338,700,288B) 0x40341D5: caa (caa.c:196)

the statement being a call to push an element on to a UT_array, e.g.
utarray_push_back(utarr_ctr_pdws, &pdw);

pdw is a pointer to a struct and is a stack variable
So it would seem the memory that UT_array is mallocing isn't getting freed, but I have another statement a few lines down explicitly doing this:
utarray_free(utarr_ctr_pdws);

The UT_array is just an array of pointers therefore doesn't need any additional dtor function defined in the UT_ICD helper struct.
If anyone has any experience of using UT_arrays maybe you can shed some light on why its using up so much memory?
Comment: You could try massif, a valgrind tool to show heap allocations. Even if you don't strictly have a leak (you still keep a pointer to allocated memory) it will show you where you are allocating large amounts of memory.
Comment: looks good - just experimenting with it now...
Comment: In my experience, if valgrind shows an error, there is a problem. My you could post the problematic code?
Comment: @eyalm - i've analysed the valgrind memcheck output and theres nothing by way of leaks that looks anywhere near serious enough to explain what I'm seeing on system monitor (memory usage) so currently having a look at valgrind massif - 1st imressions are that its exactly waht i need in this instance. its more a case of finding the problem as opposed to fixing the problem at this stage!
Comment: @BoBTFish - happy to accept your comment as an answer as it looks like a very good solution to my problem.
Comment: What platform is this running on? Linux? What are you using to measure memory usage? 'top'?
Comment: yes linux, i'd forgotten about top - i was using system monitor - top would be better - but system monitor did highlight my laptop was running out of memory pretty quickly. Massif has enabled me to see that the problem is in allocating heap mmory for UT_arrays (I'm using this data structure - http://uthash.sourceforge.net/utarray.html) . They don;t seem to be getting freed...
Comment: just figured out how to run top from within emacs - use M-x term top, not M-x shell top
Comment: have fixed the problem - utarray was being freed within an if statement whereas it was being created outside of the if statement therefore a bunch of arrays were being created but not freed, sounds like a classic memory leak but valgrind memcheck didn't pick it up - not sure why, possibly because utarray is implemented in macros?
Answer: valgrind massif is the answer here, its a heap memory analysis tool (see http://valgrind.org/docs/manual/ms-manual.html)
Answer: I suspect there's something in your pdw struct that you've allocated space for. utarray_free won't know about the members of the struct, so it'll only free the pointer to the struct itself. If you've malloc'd space for any member of the struct, utarray_free won't know how to clear them unless you set a dtor function in your UT_icd to free alloc'd struct members.

Monitoring/debugging memory usage C


Limiting barline length on one-line staff?

Question: In the below example, is there any way to prevent the barline from sticking out over the 1 line staff?
\version "2.24.2"

\new PianoStaff { <<
        \new Staff \with {
                \remove Time_signature_engraver
                \hide Clef
        } {
              \override Staff.StaffSymbol.line-positions = #'(5)
              \stopStaff \override Staff.StaffSymbol.line-count = #1 \startStaff
              s1
        }
        \new Staff {
                c'1
        }
>> }

\layout {
        \context {
              \PianoStaff
              \alterBroken transparent #'(#t) SystemStartBrace
        }
}

Answer: To reduce the height of the barline to zero use:
\override Staff.BarLine.bar-extent = #'(0 . 0)
But, if you just apply this to your example you'll see a gap between the inter-staff barline and the staff line.  This is because that upper staff line is not in the middle of the upper staff (it's at position 5) as you have used:
\override Staff.StaffSymbol.line-positions = #'(5)
I assume this is because you want the upper staff to be further away from lower.  Instead, to achieve this you should remove the above line of code, and use an override that sets the staff-staff spacing, such as:
\override Staff.VerticalAxisGroup.staff-staff-spacing.basic-distance = #12
Comment: The gap you encounter comes from a wrong extent (which is measured relative to the 0 position of the VAG), you should rather set it to `#'(5 . 5)` to sit at the correct position.
Comment: @Lazy Sure, that'd be the way to go if the single staff line is really supposed to be in position 5.
Comment: I simply intended to explain to you why your solution produces that gap, not to claim that setting the barline to position 5 was the best thing to do :-). Also see my answer to understand why things happen the way they do and how to actually prevent that from happening (rather than just forcing a fixed extent for the bar lines).
Answer: This is intended behaviour. Lilypond will by default enforce a minimum extent for the bar lines, which matters for e.g. regular one line staves (where you want the bar lines to protrude from the line). This is internally handled by the widened-extent property of the StaffSymbol, which gives the minimum values the extent must have. This is calculated by staff-symbol::calc-widened-extent, which will widen the extent by one staff space in both directions if the bar line is shorter than two staff spaces.
To get the behaviour you want set these limits to infinitely high/low:
\override Staff.StaffSymbol.widened-extent = #'(+inf.0 . -inf.0)


Conditional probability question involving Bayes' theorem

Question: A jar has 300 buttons in it. 299 buttons have one side red, the other side blue. One of the buttons has both sides blue. I randomly take a button from the jar and toss it 5 times getting 5 blues in a row. What is the probability I chose the special blue button?
I did:
$$
\begin{align}
P(\text{chose blue button}|\text{5 blue tosses}) &= \frac{P(\text{choose blue button and 5 blue tosses})}{P(\text{5 blue tosses})}\\
&= \frac{\frac{1}{300}\cdot 1^5}{\frac{299}{300} \left(\frac{1}{2}\right)^5 + \frac{1}{300}1^5}
\end{align}
$$
Is this correct?
Answer: Straightforward application of Bayes' Theorem. I agree with @msm that you have the right method and answer. Notice that your answer (approx 0.1) is substantially greater
than just the probability (approx .003) of choosing the 'pure blue' button
without conditional info from 'testing out' the button with 5 tosses.
Just for verification, I simulated the experiment 10 million times
in R statistical software. Results are in reasonable agreement with your answer.
(Because choosing a 'pure blue' button is so rare, such a simulated result may be
accurate to only about 2, maybe 3, decimal places.)
<code> m = 10^7;  p = x = numeric(m)
 b = c(1, rep(.5, 299))     # buttons in jar
 for (i in 1:m) {
   p[i] = sample(b, 1)         # choose a button
   x[i] = rbinom(1, 5, p[i]) } # toss 5 times and count 'blue's
 mean(p == 1)                  # proportion of 'pure blue' buttons chosen
 ## 0.0033274
 1/300                    # compare
 ## 0.003333333
 mean(p[x==5] == 1)       # when get 5 'blues' what proportion 'pure blue' bottons
 ## 0.09672815
 1/(299/32 + 1)           # compare (your answer)
 ## 0.09667674
</code>
Comment: Great answer that also proves how much easier probability questions are to simulate than to answer with formulae.
Comment: Interesting analysis +1
Answer: It is correct. Maybe it is more clear when it is written as
$$\begin{align}P(\text{chose blue }|\text{5 blue tosses}) &= \frac{P(\text{5 blue tosses|blue})P(\text{blue})}{P(\text{5 blue tosses|blue })P(\text{blue })+P(\text{5 blue tosses|other})P(\text{other})} \\[10pt]
&= \frac{(1^5)\frac{1}{300}}{(1^5)\frac{1}{300}+(\frac{1}{2})^5\frac{299}{300}}\end{align}$$


Pegar o endereço do usuario logado Laravel

Question: Tenho um projeto no Laravel 6 e consigo pegar o nome do usuário logado:
{{ Auth::user()->nome }}

Acontece que o endereço desse usuário está em outra tabela OneToOne onde 1 usuário tem 1 endereço.
Como faço para pegar esse dado de endereço do usuário logado?
 {{ Auth::user()->??? }}

Seguem os Models:
User:
 <?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;
    public function getAuthPassword()
    {
        return $this->senha;
    }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'nome', 'email', 'senha',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'senha','remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function endereco ()
    {
        return $this -> hasOne(Endereco::class,'user_id','id');
    }
}

Endereço:
 <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Endereco extends Model
{
    protected $table = 'enderecos';
protected $fillable = [
    'id', 'user_id', 'logradouro', 'bairro','numero','cidade','uf','cep',
];
    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }
}

Comment: Coloque os dois models na pergunta
Comment: Acabei de adicionar
Answer: Ao criar essa função
public function endereco ()
{
    return $this -> hasOne(Endereco::class,'user_id','id');
}

sua model User passa a ter uma referência à model Endereco.
Para acessar esse endereço, basta fazer assim {{Auth::user()->endereco}} e a partir desse endereço buscar o campo que necessita.
{{Auth::user()->endereco->logradouro}}
{{Auth::user()->endereco->bairro}}
{{Auth::user()->endereco->numero}}
{{Auth::user()->endereco->cidade}}
{{Auth::user()->endereco->uf}}
{{Auth::user()->endereco->cep}}

Comment: Funcionou perfeitamente! Grata
Answer: Dessa forma você consegue acessar as informações vinculado ao usuário logado.
$user = Auth::user();

$result = Endereco::where('user_id', '=', $user-id)->get();

$result vai retornar as colunas que você precisa.
Comment: Excelente dica! Vou estudar !
Comment: Sim, ok e como eu pego o endereço? São duas tabelas, User e Endereco. O loga no sistema e consigo pegar o nome, mas queria pegar o endereço também?
Comment: Editei, veja se é isso que você precisa.
Answer: Nessa pergunta Salvar relacionamento 1:1 no Laravel 5.3 já tem um exemplo básico de como acessar a relação e trazer os dados, talvez não seja a melhor forma como você fez {{ Auth::user()->??? }} porque se limita a ter que sempre fazer isso para os outros campos, então no seu controller ou em uma View::composer ou em uma View::share, faça:
// informações de user logado pelo sistema do laravel
$user = Auth::user();
// todas as informações do endereço do usuário logado
$endereco = $user->endereco()->first();

e passe para a sua View esses variáveis.
Leitura:

Salvar relacionamento 1:1 no Laravel 5.3
Como usar o relacionamento hasmany no laravel 5.2?
Problemas com relacionamento um para muitos laravel


Hostname in certificate didn't match on wildcard cert

Question: This may be an apache/server configuration, or it might require a Java solution.   On my server I have a few subdomains.  I force https on all subdomains and I have a wildcard ssl certificate that is used for all subdomains.
When I go to https://myapp1.myvendor.com and view the certificate in the browser I see the following common name:
CN = *.myvendor.com
I also have a Java program that posts to https://myapp1.myvendor.com/post.php however when I post from Java using:
org.apache.http.client.methods.HttpPost httpPost = new HttpPost("https://myapp1.myvendor.com/post.php");
HttpResponse response = httpClient.execute(httpPost);

I get the following error:
javax.net.ssl.SSLException: hostname in certificate didn't match:
<myapp1.myvendor.com> != <myvendor.com> OR <myvendor.com> OR <www.myvendor.com>

What strikes me as odd is that it is trying to match myvendor.com or www.myvendor.com not *.myvendor.com.  I do have a certificate installed for myvendor.com, but I stopped using it in favor of the wildcard cert.
Any suggestions?  Do you need more information?
Apache Config:
<VirtualHost *:443>
 SSLEngine On
 SSLCertificateFile /etc/pki/tls/certs/27c7d7842bf94d.crt
 SSLCertificateKeyFile /etc/pki/tls/private/mydomain.key
 SSLCACertificateFile /etc/pki/tls/certs/my_cert.crt

 ServerName myapp1.myvendor.com
 DocumentRoot /var/www/myvendor/myapp1/src/
 ErrorLog /var/www/logs/myapp1/error.log
 CustomLog /var/www/logs/myapp1/access.log combined
 <Directory /var/www/myvendor/myapp1/src/>
         AllowOverride All
 </Directory>
</VirtualHost>

I also found this in a different config file that IS loaded:
<VirtualHost _default_:443>
 SSLCertificateFile /etc/pki/tls/certs/local.crt
 SSLCertificateKeyFile /etc/pki/tls/private/local.key
 SSLCACertificateFile /etc/pki/tls/certs/my_local_cert.crt
</VirtualHost>

I think it is getting this cert because this cert has:
subject Alternative name:
 DNS Name=myvendor.com
 DNS Name=www.myvendor.com

which matches the error from Java.  If this is the case my question is why is Java getting this cert as opposed to the one that the browser gets?
Comment: 95% your myapp1.myvendor.com points to server you don't expect. I.e. your proxy settings/hosts file make domain to point somewhere else... Or myapp1.myvendor.com is configured to use different cert than you expect.
Comment: Or your server does SNI and Java isn't giving it the info it needs to choose the right cert.
Comment: @AlexeiLevenkov See my edit.  Does my edit make sense?
Answer: It looks like you are using SNI, e.g. multiple https servers on the same IP with different certificates. In this case have a look at Server Name Indication (SNI) on Java how to use SNI in Java.


Why do I get duplicate HSTS headers? AWS ELB, nginx, Ruby on Rails

Question: I'm running a set of Rails servers on AWS with elastic load-balancing and nginx.  When I run a security test at SSL labs (http://ssllabs.com/ssltest), it reports back:
    Invalid: Server provided more than one HSTS header

Where's that coming from, and how do I configure it to only report one HSTS header?
Answer: Rails adds a HSTS header when you set config.force_ssl = true.
Since the error is that it's being duplicated, you're probably setting nginx to set the same header. Choose for either rails or nginx to do it, not both.


is there a way to know witch module is responsible to programmatically alter a view's query?

Question: I have a view that diplays some orders with a filter by current user if he is owner of the order or not ..
If the current user is admin, i can see my orders with no problems.
If im logged in with another role the view is always empty althought im ordering products with that user.
I doubt about the view access, or some modules permission (for example if this role has the permission to view his own orders or if he has permission to view his own product ...) I checked these permissions carefully, but the view result still empty.
when I debug the query I get inside where clause an additional condition that's applyed only for non admin users :

(AND 1 = 0)

as you know this condition returns always false, so that's why the result of the query is empty.
Is there a way to know from where is coming this condition when im logged in with a non admin role ?
Thanks in advance.
Answer: Interesting question / challenge, not obvious to debug ...
Here is what I would do, in the order specified:

Scan the entire modules directory for a string containing '1 = 0'.

Scan the Drupal database (all tables) for a string containing '1 = 0'.

If none of both scans lead to any results, I'd consider using the X-ray module, to check if that would help me any further. Some details about this module (from its project page):

X-ray module gives a look at the skeletal structure of a site to help developers and site builders see how things work.
X-ray Features:

A technical summary is added to the help above the main administrative sections. For example, blocks, content types, and menus are summarized on Structure; themes on Appearance; etc.
A table of permission titles matched to their permission machine names.
A table of most* hooks which Drupal invokes (and when they are invoked) and that are available to be implemented.
The function and arguments producing each page you visit, displayed on that page.
The form ID of every form you see, displayed on the form.
Answer: Please check, that all line items in order related to this order (order_id field in line item entity).
Also, please check the following issue: https://www.drupal.org/node/1541206


Creating marginal plots when using mgcv (GAM) package in R

Question: Before training the GAM model I log-transformed several variables. The default plotting method plot.gam in mgcv can provide nice visualization of the marginal effect of a variable but seems not be able to transform the variable back to the original scale. Is there any easy way to do this?
If not, how can we make the marginal plots by hand? I seem to have figured out how to do this with one predictor. However, in the multiple predictor case, if we scan the variable of interest, what fixed values should we use for the rest of variables? Shall we take the mean for all other variables? What if the rest of variables have some categorical variables where the mean is not clear?
Answer: First, make sure that transforming your predictor (or response) variables is actually a reasonable thing to do (see, e.g., here).
Second, you'll have to do it manually if you mean back-transforming a predictor variable to an original scale.  If you're talking about the response variable, read this again, and if you still decided to transform the response variable see the trans and possibly shift arguments in ?plot.gam.
But let's assume you're referring to back-transforming a predictor variable.  For a marginal plot, setting the other continuous variables at their mean is a popular choice, but that need not be the case.  If a predictor variable was highly skewed, for example, you could easily use the median as an option.  Or a specific value relevant to the context.  You'll have to think carefully about what makes the most sense in your application.  Note also that using the mean of a log-transformed variable in your marginal plots puts it at the geometric mean on the original scale.
The same thought process applies to categorical variables --- you could produce the marginal plot for the reference class (as I illustrate below), another class that may be more relevant, or even all classes.
Below we use mgcv's simulation capabilities to generate a data set with 3 continuous predictors (x1, x2, and x3) and a categorical predictor (x0).  For simplicity, imagine that x1 and x2 have already been log-transformed, so we're interested in returning them to their original scale in our marginal plots.  Since we (pretended to) log-transform x1 and x2, it's a simple matter of exponentiating the values prior to plotting.
library(mgcv)
set.seed(123)

# Assume normal response
# Assume x1 and x2 have been log-transformed
xformed_data <- gamSim(5)
mod <- gam(y ~ x0 + s(x1) + s(x2) + s(x3), data = xformed_data)
plot(mod, pages = 1)

# Marginal plots (transformed and original scale) for x1
# Generate new data set with categorical variable at reference class (i.e., x0 = "1")
# This marginal plot will illustrate the marginal relationship between x1 and y with
# x0 at the refence level, x2 at its geometric mean, and x3 at its mean

x1dat <- data.frame(x0 = factor("1"),
                    x1 = seq(min(xformed_data$x1), max(xformed_data$x1), length.out = 100),
                    x2 = mean(xformed_data$x2),
                    x3 = mean(xformed_data$x3))

x1fit <- predict(mod, newdata = x1dat, type = "response", se = TRUE)

# Marginal plot for x1 on transformed scale; will match output from plot(mod)
# although confidence intervals will not match because uncertainty from other
# smooths and intercept now included
plot(y ~ x1, xformed_data)
lines(x1dat$x1, x1fit$fit)
lines(x1dat$x1, x1fit$fit +2 * x1fit$se.fit, lty=2, col = "red")
lines(x1dat$x1, x1fit$fit -2 * x1fit$se.fit, lty=2, col = "red")

# Marginal plot for x1 on original scale; will match output from plot(mod)
plot(y ~ exp(x1), xformed_data)
lines(exp(x1dat$x1), x1fit$fit)
lines(exp(x1dat$x1), x1fit$fit +2 * x1fit$se.fit, lty=2, col = "red")
lines(exp(x1dat$x1), x1fit$fit -2 * x1fit$se.fit, lty=2, col = "red")

# Marginal plots (transformed and original scale) for x2
# Generate new data set with categorical variable at reference class (i.e., x0 = "1")
# This marginal plot will illustrate the marginal relationship between x2 and y with
# x0 at the refence level, x1 at its geometric mean, and x3 at its mean

x2dat <- data.frame(x0 = factor("1"),
                    x1 = mean(xformed_data$x1),
                    x2 = seq(min(xformed_data$x2), max(xformed_data$x2), length.out = 100),
                    x3 = mean(xformed_data$x3))

x2fit <- predict(mod, newdata = x2dat, type = "response", se = TRUE)

# Marginal plot for x2 on transformed scale; will match output from plot(mod)
# although confidence intervals will not match because uncertainty from other
# smooths and intercept now included
plot(y ~ x2, xformed_data)
lines(x2dat$x2, x2fit$fit)
lines(x2dat$x2, x2fit$fit +2 * x2fit$se.fit, lty=2, col = "red")
lines(x2dat$x2, x2fit$fit -2 * x2fit$se.fit, lty=2, col = "red")

# Marginal plot for x2 on original scale; will match output from plot(mod)
plot(y ~ exp(x2), xformed_data)
lines(exp(x2dat$x2), x2fit$fit)
lines(exp(x2dat$x2), x2fit$fit +2 * x2fit$se.fit, lty=2, col = "red")
lines(exp(x2dat$x2), x2fit$fit -2 * x2fit$se.fit, lty=2, col = "red")


taiwlind JavaScript can't get executed in blazor .net8 with @rendermode InteractiveWebAssembly

Question: I recently configured a Blazor project with Auto rendering mode, incorporating Tailwind CSS. However, I encountered challenges when using components that require flowbite.min.js in Razor pages with the @rendermode InteractiveWebAssembly attribute. Disabling this attribute enables Tailwind to function correctly for these components but disrupts the execution of @onclick events. This dilemma forces a trade-off between optimal Tailwind performance and the proper functioning of Blazor events, depending on the presence or absence of @rendermode InteractiveWebAssembly.
This code utilizes flowbite.min.js:
<button data-drawer-target="drawer-example" data-drawer-show="drawer-example" aria-controls="drawer-example" type="button">
    New Appointment
</button>

<button id="blazor" @onclick="SomeFun" />

When @rendermode InteractiveWebAssembly is not added, the code effectively displays the canvas off (drawer), but the button's (blazor) click event will not be triggered. Conversely, when @rendermode InteractiveWebAssembly is present, the flowbite.min.js-dependent code fails to work, but the blazor button successfully handles the @onclick event.
Here is my App.razor:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <base href="/" />
    <link rel="stylesheet" href="app.css" />
    <link rel="icon" type="image/png" href="favicon.png" />
    <HeadOutlet />

    <Routes />

I also have to mention that in Microsoft documentation, they always show samples without setting the @rendermode.
Comment: Without any error messages or a minimum example, we cannot help much. I suspect it's not the js but how you're communicating with it and dealing with the switch from server to wasm. Also, the auto render modes include SSR first this can be disabled.
Comment: I have revised the entire post to provide a clearer explanation of my issue.
Comment: What errors do you see on the browser console?
Comment: Appreciation to @RBee for investigating this matter. I've recently shared a solution to my question for the benefit of others facing a similar issue.
Answer: For individuals encountering a similar issue, I have successfully identified the resolution through the following link: https://github.com/themesberg/flowbite/pull/739/files.
If you adhere to the Flowbite documentation, it may not yield the expected results. Please refer to https://flowbite.com/docs/getting-started/blazor/#install-flowbite for more information.


JNA Error at Program Exit

Question: So I have the following in c++
__declspec(dllexport) extern "C"
char** get_prop_types( int* count ) {
  const vector<string>& r = prop_manager::get_prop_types();
  char **p = (char**)malloc( r.size() );
  char **ptr = p;
  for( vector<string>::const_iterator it = r.begin(); it!=r.end() ; ++it ) {
    *p = (char*)malloc( it->size() );
    strcpy(*p++,it->c_str());
  }
  *count = r.size();
  return ptr;
}

and in java
public interface Arch extends Library {
    public Pointer get_prop_types( IntByReference size );
}
static Arch theLib; //initialization not shown

public static String[] getPropTypes() {
    IntByReference size = new IntByReference();
    Pointer strs = theLib.get_prop_types(size);
    //free is apparently handled for us?
    return strs.getStringArray(0, size.getValue());
}

public static void main( String[] args ) {
    System.out.println( Arrays.toString(getPropTypes()) );
}

The above will print out a list of Strings. So far so good. But after main returns (during finalization?) I get an error along the lines of
The instruction at "%08X" referenced memory at "%08x". The memory could not be "read".

I get the same error when trying to manually free() the char** or each individual char*
Can someone tell me what I've done wrong? Or at least point we to some more resources?
Answer: This:
 *p = (char*)malloc( it->size() );

should be:
 *p = (char*)malloc( it->size() + 1);

And I just noticed that:
 char **p = (char**)malloc( r.size() );

should be:
 char **p = (char**)malloc( r.size() * sizeof(char *) );

which shows how often I use malloc these days!
Comment: i dun derped. I apparently need `char **p = (char**)malloc(r.size()+1)` also. thanks
Comment: @Kitsune I don't see why that should be necessary, as there is no terminating null character to worry about in that case.
Comment: I tried w/o and it crashed again. Putting the extra +1 works. /shrug

JNA Error at Program Exit


What is the Grant Permissions button for Azure AD web app

Question: This more of an admin question as far as where you might find this issue. I am working with an Azure AD web app and I am wondering what the Grant Permissions button does?
I made a test dummy MVC project to see what it did and when I grant permissions for my account for the current directory it makes the manifest unusable.
This is the view of my app in Azure AD app registrations. I've highlighted the Grant Permissions button that I am talking about.

This is the drop down I get when clicking on the Grant Permissions button. This is the part I really don't understand and need clarification on what it's doing when I say yes.

Basically, what can I do to undo the actions if I say yes to the Grant Permissions button for my app? But also, what exactly does the Grant Permissions do for my app? I am just a normal user in my Active Directory that has the ability to create apps in ad and edit the manifest.
Any help would be much appreciated and thanks in advance!
Answer: The Grant Permissions button in the Azure Portal will perform Admin Consent on the app you have selected.
Admin Consent can accomplish a multitude of things. There are two primary use cases.

If you're building a single tenant web app that calls admin and user scopes/permissions, it will consent for all users in that tenant.  This will let the app call any admin scopes, and also suppress consent for all the users inside the tenant.
The other use case is to consent for app only permissions, which always requires admin consent.

The Azure AD How to build a multi tenant app doc has a great section on the meaning of admin consent.
I am not aware of any way to revoke admin consent. An individual user can revoke consent they've granted through My App.
Comment: One trick to remove admin consent would be to delete the application's service principal in the tenant. That would also remove any individual consent that was granted to the application and any tenant specific settings set on the service principal, but that may still be a fine option for you.
Comment: Thank you very much! Can you give any insight as to why the manifest would be un-editable after granting permission?
Comment: @Alex I haven't heard of that happening before. I'll forward this comment to that team and see if they can help.
Comment: @DanielDobalian That would be awesome! I think it might be because I am a normal ad user and not an admin but then again I am still a novice at this. If you find nothing, that is okay, I just wanted to get this issue out to others that might encounter the same problem. Thanks!
Comment: @Alex out of curiosity, how were you able to "Grant Permissions" as a normal user, did an admin do it on your behalf? If you registered the application as a non-admin you should be able to edit the manifest. If you didn't register the app, that may explain this.
Comment: @DanielDobalian I think what you're saying is correct. My admin created an app for me for testing and I think that is why I did not have access. He granted permission on behalf of everyone so yes I don't know how I did not see that before. Thanks for following up on this!