Minimum sum of integers not multiples of one another.

Question: Question: Let A be a set of 7 positive integers that are not multiples of one another. Find the smallest possible sum of all elements in A.
I tried brute forcing the question: deriving the sum the 7 smallest primes to be 58(i.e. the sum of 2,3,5,7,11,13,17). However, i found a smaller sum of 55 with numbers the 4,5,6,7,9,11,13. However, I cannot seem to show in a neat way that this sum is indeed the smallest possible. Is 55 indeed the answer? Is there a way to show that it is?
Comment: I do not see any better way than brute force. I checked the sets with maximum element at most $30$, and found no better solution. Since a set with an element greater than $30$ would give sum at least $58$ (because $1$ is not allowed, hence the sum would be at least $2+3+4+5+6+7+31$) , This shows that you found the optimum.
Comment: Your solution is also the only one with sum $55$
Answer: $55$ is indeed the answer. I checked it using an almost brute force approach, with some modifications:

Selecting the smallest number $i_1$, it can only be one of $2,3,4$, since $5+6+7+8+9+10+11$ is already more than $55$.
Selecting the second number $i_2$, we know that the total sum will be at least $i_1 + i_2 + i_2+1 + i_2+2 + i_2+3 + i_2+4 + i_2+5 = i_1 + 6i_2+15$ which means that we know $i_1\leq i_2\leq\frac{55-15-i_1}{6} = \frac{40-i_1}{6}$. Also, we can skip $2i_1,3i_1,4i_1,\dots$ when checking for possible values of $i_2$.
For $i_3$, we know that the total sum will be at least $i_1+i_2+i_3+i_3+1+i_3+2+i_3+3+i_3+4 = i_1+i_2+5i_3+10$ which means $i_2\leq i_3\leq\frac{45-i_1-i_2}{5}$. Also, we can skip $2i_1,3i_1,\dots$ as well as $2i_2,3i_2,\dots$ when looking for possible values of $i_3$.

Doing the same with $i_4,i_4,\dots i_7$ limits the search space somewhat, allowing us to see that $4,5,6,7,9,11,13$ is the only solution.
Comment: Can the downvoter please explain why they consider my answer wrong?


how to publish the visual studio asp.net solution?

Question: I have converted my website into the solution, by creating new blank solution and adding existing website in it. Now i want to publish that solution, but it doesn't show me any option of publishing solution.
How can i publish the solution?
Thanks in advance.
Comment: Can you find the Publish option when you right click web app ?
Answer: The publish command should be on the web site or web application project rather than on the solution itself.
Comment: @Rohan I don't really understand. Why would you want to publish the solution?? Normally your Web project should contain all the necessary resources to run properly. I.e. a web application contains all the compiled projects of your solution that are referenced from your Web Application project, in the `bin` folder, ready to be deployed. You always publish the "front-end" project which will then contain the references to potential subprojects.
Comment: @Rohan I still don't understand :) A Visual Studio Solution is just a construct for organizing different projects. In the end what counts is your "front-end" project, whether it is a Console Application, WinForms or WPF App or a Web Application. That's what you are going to release and therefore that's where the Publish option resides.
Comment: This is one option. Normally it proposes to delete existing or to overwrite newer ones.
Comment: If you only want to replace specific files, you could always publish using the File System option, to another folder, and then only replace the specific files you want to in the live site.
Comment: @RohanBüchner- thanks for reply. i want to know can we publish the solution rather than publishing website?
Answer: Right click on your project file and select publish website. keep in mind that if it asks to delete existing files then it is asking about already published files not the source files. So  it is safe to delete prior published files and publish new website, as well as you can change the folder for new published site
Answer: You can get some help from the following article: How to deploy ASP.Net Web Application
But just a friendly recommendation that you do a bit of researching yourself before asking questions.


What's the difference between "standard error of estimate" versus the "variance of residuals"

Question: For OLS linear regression, Hayes (2022, p. 56) provides a definition of "mean squared residual" and one for "standard error of estimate", for a model with $k$ predictor variables:
$$\large \text{mean squared residual}=\frac{\sum^n_{i=1} (y_i-\hat y_i)^2}{n-(k+1)}=\frac{\sum^n_{i=1} \varepsilon_i^2}{n-(k+1)}$$
$$\large \text{standard error of estimate}=\sqrt\frac{\sum^n_{i=1} \varepsilon_i^2}{n-(k+1)}$$
However, the formula for $R^2$ implies there is another type of "mean squared residual" with only $(n-1)$ in the denominator:
$$\large R^2=\frac{\hat\sigma^2_{\hat{Y}}}{\hat\sigma^2_Y}=\frac{\hat\sigma^2_Y-\hat\sigma^2_\varepsilon}{\hat\sigma^2_Y}=\frac{\frac{\sum^n_{i=1} (y_i-\bar Y)^2}{(n-1)} -\frac{\sum^n_{i=1} \varepsilon^2}{(n-1)}}{\frac{\sum^n_{i=1} (y_i-\bar Y)^2}{(n-1)}}$$
Thus, what would be the name for $\large\frac{\sum^n_{i=1} \varepsilon^2}{(n-1)}$ to distinguish it from $\large\frac{\sum^n_{i=1} \varepsilon_i^2}{n-(k+1)}$ ?
References

Hayes, A. F. (2022). Introduction to Mediation, Moderation, and Conditional Process Analysis: A Regression-Based Approach (Third edition). The Guilford Press. https://www.guilford.com/books/Introduction-to-Mediation-Moderation-and-Conditional-Process-Analysis/Andrew-Hayes/9781462549030
Comment: Side remark: using the $k-1$ version to calculate R-squared gives another good friend: the R-squared adjusted.
Comment: @whuber I know they cancel out. For R^2, would it be legitimate to make all the denominators (n-k-1)? If so, I would think those terms would have different names than their (n-1) counterparts, and that's my question: what is the name of the squared error with df (n-1), versus its name with df (n-k-1). I assume they must have different names.
Comment: There isn't a question here, because there is no "$n-1$" in the denominator since all those factors cancel: you could replace them with any nonzero number you please.
Answer: Okay, I think I may have an answer, but I'm not 100% sure of its correctness. Perhaps:
$$\large\displaystyle\frac{\sum^n_{i=1}(y_i-\hat y_i)^2}{n-1}=\small\text{unbiased estimate of the {population mean squared residuals}}$$
$$\large\displaystyle \sqrt\frac{\sum^n_{i=1}(y_i-\hat y_i)^2}{n-(k+1)}=\small\text{unbiased estimate of the {population standard error of residuals}}$$
The above is based on analogical reasoning from the following:
$\large\displaystyle\frac{\sum^n_{i=1}(y_i-\bar Y)^2}{n-1}$ is the unbiased estimate of the population variance of $Y$ , and $\large\displaystyle \sqrt \frac{\sum^n_{i=1}(y_i-\bar Y)^2}{n-1}$ is a biased estimate of the population standard deviation of $Y$, hence my proposed answer above. If someone could help confirm or challenge the correctness of this, I would feel better.
Comment: I suspect my answer is incorrect: I think the top formula in my answer is merely {the unbiased estimate of the variance of the residuals}, whereas the second formula in my answer is the {root mean squared error (RMSE)} (which is merely the square root of the {mean squared error (MSE)}).

As far as I understand, they each have a purpose: the unbiased estimate of the variance of the residuals is focused on accurately estimating the variance of the residuals, whereas the MSE and RMSE are focused on evaluating the predictive performance of the model while considering its degrees of freedom.


Fujitsu Siemens ServerView and SNMP Monitoring

Question: I want to monitor the temperature of a couple of our servers, and since they're Fujitsu Siemens servers with ServerView installed I decided to check if SNMP was an option, and apparently it was.
However, I can't seem to figure out which OID to get, or even in which MIB to look for this information. As usual, the documentation seems to be pretty scarce or at least vague.
Concrete information on this case would be welcome, more than anything, but if you would have tips on how to look for the right OIDs in general that would probably help me on my way as well as I don't have a clue how to properly go about it right now.
Thanks
Answer: HI THERE!
Global state OID 22.214.171.124.22.214.171.124.10.2.11.2.1.0
It could return
1=OK, 2=Degrade,3=Error, 4= Fail, 5=unknown.
good luck!
Comment: could you tell me where you found this, and what else there is to be checked? "global state" doesnt mean a whole lot to me right now
Comment: http://forums.pandorafms.com/index.php?topic=2712.0 is one possible source
Answer: What monitoring software are you using (Cacti, Munin, Nagios, Zabbix, other)? It may have built-in or community-contributed templates for your particular server.
Have a look on the manufacturer's website for MIBs relating to the hardware sensors (disk, CPU etc. are normally reported by the OS) - otherwise, snmpwalk a server and see if you can find anything that might correspond to temperature, keeping in mind the units may not be what you expect.
Comment: I'm using Icinga (the Nagios fork) but that obviously has nothing built in. I tried looking for the MIBs and I think I may have found them, but there's about 25 included in the package and so far I had no luck locating what I need. How do you start snmpwalking ? Don't you need an OID to start with?
Answer: You could try monitoring with IPMI. This should be available even on rather old servers from around 2010 or 2011 like Fujitsu Primergy with iRMC S2 or S3 that don't support SNMP (they can just send traps). Beware, IPMI can e.g. configure the server or power it on and off...


Time signatures and music

Question: My daughter has created a piece of music for her B-Tec music production class in which the time signature changes, but the tutor is trying to argue that this is not correct. Can someone please clarify for me, whether it is acceptable for a piece of music to change time signatures? I'm getting the impression it is okay - but why is this musically acceptable?
Comment: It's acceptable, but your daughter's tutor could nonetheless be right.
Comment: Without knowing the criteria for the course, it's an impossible question to answer with regard to that. Obviously it's acceptable, as it happens a fair bit, reason being, the music, in the writer's (and player's) view, needs that to happen.
Comment: Voting to close, needing more details. One option that I haven't noticed being discussed yet is that the meter change was acceptable but incorrectly executed; e.g. maybe the new time signature didn't match the actual number of beats in each bar. Please tell more about the teacher's objection and if possible post the music.
Comment: There are no *absolute* standards of "correct" or "acceptable". Without clarification on what the tutor *meant*, this is unanswerable.
Comment: Is the tutor saying "categorically wrong", "wrong in this assignment", "not accurately reflecting the composition", or something else?  Also: Please edit the question to clarify "B-tec".  (Which is apparently [BTEC](https://qualifications.pearson.com/en/qualifications/btec-technicals/music-production.html) and a region-specific program, but not [this Btec](https://www.urbandictionary.com/define.php?term=Btec) or [this btec](https://www.btecsolutions.com/).)
Answer: Well, like so many other aspects of music, the answer is it depends. In this case, the most important considerations are (1) what are the specific requirements for the music production class and (2) what genre of music is she creating.
Requirements
If the syllabus explicitly dictates that the time signature must not change, then that is that.  There may be a reason for this.  The instructor may be working with musical novices who need practice fitting rhythms within a time signature properly.  Allowing students to simply change the time signature when their music doesn't fit would subvert this.  Or maybe the software in use doesn't work well with changing time signatures and so this is a requirement for the student to be able to produce their music freely.  Adding a little context about this would help.
Genre
Some genres of music do change time signature from time to time, some almost never change, and some change very frequently.  If she is writing music in a mainstream dance genre, for example, changing time signatures frequently would not probably work well.  We expect dance music of a specific kind to follow a time signature convention and stick with it.  If she is composing a piece for a group of young musicians or amateurs to play, they may be confused by the time signatures.  But if she is creating it for electronic playback, or a professional-level ensemble, changing time signatures as often as the composer desires is perfectly reasonable.  A little context in this realm would help, too.
Comment: I guess we need a little more info from the OP then.  I read it as wondering whether a time signature change at all/in general is acceptable.   Of course there are specific instances like you mention where the choice of time signature is simply wrong.
Comment: "often in Happy Birthday, bar 6 changes time signature drastically"  Only if you choose to interpret a fermata that way!  And I'd rate doing so as an error.
Comment: You've missed the point. A time signature change can be incorrect. For example notate 'Happy Birthday' but change to 5/4 in the second measure. You'd almost certainly agree that's wrong. It makes no musical sense.
Comment: @PiedPiper if you are writing down existing music without a time signature change then writing one is obviously incorrect. The question is whether it's not allowed to write *new* music with a time signature change.
Comment: @PiedPiper - often in Happy Birthday, bar 6 changes time signature drastically!
Comment: @user253751 My example was badly formulated. I should have written "if you are composing a simple melody like 'Happy Birthday'..."
Comment: @Tim That's a place where there probably **should** be a time signature change (4/4 or even 5/4). Seems I picked the wrong example.
Comment: @user253751 Happy Birthday is just an example, chosen because it is a well known melody.  It's also possible to compose a new piece that is entirely in one time signature only and write it down with an incorrect time signature change (or, conversely, to compose a new piece that has a time signature change but write it down incorrectly all in one time signature).  It's just too difficult in the space of a stack exchange comment to compose a novel example to illustrate this.
Comment: @Laurence I disagree that it's a fermata at all. Have you ever seen a group of birthday singers hold that note until cued to continue? No, every single person knows to add exactly one extra beat.
Comment: Check this version out, and weep! https://www.youtube.com/watch?v=_z-1fTlSDF0
Comment: Oh dear, @Laurence, that is dreadful!  I don't even know where to start...
Answer: The question is worded a bit strangely, it really depends on what exactly the question is asking. I think the better way to ask the question is "When is the usage of a time signature change inappropriate", since it's easier to explain when a time signature change is non-standard, rather than "are time-signature changes appropriate?"
As some users in the comments mentioned, it would be inappropriate to use a time signature change on an existing piece of music in which the time signature is already well-known or commonplace, say, "Twinkle Twinkle Little Star". The piece is in 4/4 throughout, and to change the time signature would be arguably wrong (or at least very confusing to read). After all, time signatures are supposed to provide clarity in beat and/or divisions of beat(s), and if it's providing more confusion than clarity, it's (probably) wrong.
However, there are also instances in which time signature changes maybe inappropriate to use even in a compositional setting. First, such changes may be unsuitable or inapplicable to the style. For example, most American marches are written in some divisions of two (2/4, 2/2, or 6/8), since its music was constructed for, well, marching. A change in the time signature (even into 4/4!) would be confusing for those performing the piece.
Of course, it could be feasible for a composer seeking some spice in their writing to perhaps switch from cut-time into 6/8 (or vice versa), but this sort of practice is generally uncommon within American marches, which (at least ones composed by Sousa and his contemporaries) generally also followed a fairly strict form (if you're curious, you can read about that here!)

A time signature changes can also be wrong or unnecessary from a pure notation point of view. For example, if I wrote something like this:

This is wrong (sort of). Isolated, this is just a 9/8 figure, and unless there's some good contextual reason for this being here, most people would also argue that this should just be written as 9/8. However, things get a little bit more interesting if I were to write it as such:

Now there's actually a reason for the time signature change. A 9/8 pattern suggests a triple compound pattern (1-2-3, 1-2-3, 1-2-3), but what I've written below suggests a (1-2-3, 1-2/ 1-2, 1-2) pattern, though it could also easily be written like this:

or even just this:

Many of these changes would largely depend on the context of the piece, and different ones would make more sense. For example, if my piece was generally in 9/8 and I wanted to just mess with the meter a bit, I would probably write it like this:

It wouldn't make sense for me to change the time signature (unless there was some very good reasoning otherwise) since it just clutters the page. However, if I were to compose something more metrically complex like...

... the 5/8+2/4 pattern makes more sense here.Link here if you're curious on how it sounds.
(Sorry if the melody sounds rushed, it's because I wrote it in like 15 minutes just for this example).
So yeah, TL;DR, context matters. Opt for clarity - if changing the time signature makes your piece make more sense, then it should be used. Otherwise, just stick with the time signature you have, and be aware of the style you're writing for, to be wary if it is appropriate or inappropriate to incorporate it.
Comment: If anyone's curious on how the 9/8 melody sounds, I can upload that too, though that one's fairly simple and short enough that you could just play it on piano.
Answer: Time signature changes are allowed, and commonplace, particularly in modern styles.
The time signature changes your daughter has written  may be inappropriate, an inefficient way of notating her musical intention.
If you show us a page of her score, we can usefully discuss whether this is the case!

Time signatures and music


Change views exposed filter value only on page reload

Question: Is there a clean way to alter a View exposed filter field, but only on page reload and not each time you submit the exposed filters form ?

Example
I have a View with exposed filters. When a user is loading this View, I want to change the value of an exposed filter field, depending on a cookie value.
I've managed to make it work with the hook_form_views_exposed_form_alter function.
function HOOK_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form['#id'] == 'views-exposed-form-MY-VIEW') {
        $cookies = \Drupal::request()->cookies->all();
        if (isset($cookies['MY_COOKIE'])) {
            $form['MY_FIELD']['#value'] = $cookies['MY_COOKIE'];
        }
    }
}

Problem is : if the user manually change the exposed filter and submit the form, the value is getting back to the first one because the hook_form_alter is getting called again.
Here is a video : https://i.stack.imgur.com/ZSRLQ.jpg

Poor solution
I've found a solution, but it doesn't looks like a good one. I've found out that when the hook_form_alter is getting called by a submit, there is a new entry ('a' => '') in the UserInput array that you can find by calling $form_state->getUserInput().
First load :
[
    'MY_FIELD' => 'All',
    '...' => '...'
]

After submit :
[
    'MY_FIELD' => 'New value',
    'a' => '',
    '...' => '...'
]

So now I can use the following to change the field value only on the page load :
if (isset($cookies['MY_COOKIE']) && !array_key_exists('a', $form_state->getUserInput())) {
    $form['MY_FIELD']['#value'] = $cookies['MY_COOKIE'];
}

But I'm not even sure it is fully functional, is there a better way to do it ?

Clean solution
Thank's to @NoSssweat, here's a cleaner solution :
function MODULE_views_pre_build(ViewExecutable $view) {
    $request = \Drupal::request();
    $is_ajax = $request->isXmlHttpRequest();
    if (!$is_ajax) {
        $cookies = \Drupal::request()->cookies->all();
        if (isset($cookies['MY_COOKIE'])) {
            $view->setExposedInput(['MY_FIELD' => [$cookies['MY_COOKIE'] => $cookies['MY_COOKIE']]]);
        }
    }
}

Comment: @NoSssweat The `hook_views_pre_build` is working but I've the same problem : each time I submit the exposed filter form, the field value is getting back to the previous value.
Comment: @NoSssweat Just added a video link to show you : https://imgur.com/EmVha6e
Answer:
Just added a video link to show you : imgur.com/EmVha6e

You just need to add a conditional to check if it's not ajax
   $request = \Drupal::request();
   $is_ajax = $request->isXmlHttpRequest();
   if (!$is_ajax) {
     // code that sets the filter initial value
   }

Credit: How can I detect AJAX request inside Drupal?
Comment: That's it ! I've finally used the `hook_views_pre_build` function. With the request check, it seems the best solution, a lot cleaner than the one I was using. Thank you !


Retornar as posições do maior número numa matriz

Question: Preciso de um código que retorne a posição do maior elemento da matriz, e se esse elemento se repetir, que o código retorne todas as posições que esse maior elemento aparece.
Abaixo, em meu código, consigo retornar o maior valor, mas não a sua posição:

maior: é o maior valor
posição: posição na linha que o maior valor se encontra
vez: é um contador de quantas vezes já rodei as linhas (por exemplo: estou na linha 2)

from random import randint
maior = 0
posição = 0
matriz = []
vez = 0
for i in range (4):
    linha = []
    vez = vez + 1
    for j in range (4):
        linha.append(randint(1,10))
        if linha[j] > maior:
            maior = linha[j]
            posição  = j
            linha = vez

    matriz.append(linha)

print (matriz)
print ("maior: ", maior)
print ("posição do maior número: ", posição)
print ("linha: ", linha)

Answer: Oi, seu codigo esta quase certo. A posicao depende de i,j. Entao voce tem que guardar o valor de i,j:
from random import randint
matriz = [-1]*4
j = 0
maior = 0
posição = ()
for i in range (4):
    for j in range (4):
        matriz[j] = randint(1,10)
        if matriz[j] > maior:
            maior = matriz[j]
            posição = (i,j)
        j = j + 1
    print (matriz)
    print ("posição do maior número: ", posição)
print ("maior número da matriz: ", maior)

Para conseguir todas as posicoes que o maior numero ocorre, voce vai tem que criar uma lista de pares, e se o numero maior mudar voce vai ter que reinicializar a lista de pares e comecar a adicionar valores nela de novo.
Answer: Se o maior elemento pode se repetir, então você precisa ter uma lista com todas as posições.
Se o número for igual ao maior, você adiciona a posição nesta lista. Mas se algum outro número maior ainda for encontrado, a lista de posições anteriores deve ser descartada e uma nova deve ser iniciada:
from random import randint
maior = 0
matriz = []
tamanho = 4
posicoes = []
for i in range(tamanho):
    linha = []
    for j in range(tamanho):
        n = randint(1, 10)
        if n > maior: # achei um maior, começa uma nova lista de posições
            posicoes = [(i, j)]
            maior = n
        elif n == maior: # igual ao maior, adicione a posição na lista
            posicoes.append((i, j))
        linha.append(n)

    matriz.append(linha)

print (matriz)
print ("maior: ", maior)
print ("posições do maior número: ", posicoes)

Estou guardando as posições em tuplas, contendo os valores de i e j (já que você precisa de ambos os valores para ter a posição correta).
Também eliminei a variável vez, que me pareceu desnecessária.
Comment: ~Interessante esse código
Answer: Pude notar que você está tentando fazer aglutinar todas as tarefas numa coisa só.
Seria melhor dividir o seu problema em etapas menores e mais simples onde em cada uma dessas etapas você fizesse apenas o essencial para resolver um problema menor.
Focando a sua pergunta:

Preciso de um código que retorne a posição do maior elemento da
  matriz, e se esse elemento se repetir, que o código retorne todas as
  posições que esse maior elemento aparece.

Eu vejo as seguintes etapas:

Criar uma matriz
Descobrir qual o maior elemento da Matriz
Descobrir quais as posições de ocorrência do maior elemento na Matriz.

Para criar uma matriz não tem mistério, é lista composta por listas isomórficas onde a quantidade de linhas da lista exterior é a mesma quantidade de elementos contidos em uma das listas interiores. Para simplificar é um lista onde o número de linhas é o mesmo número de colunas, traduzindo isso em list comprehension:
lambda d: [[randint(1,10) for _ in range(d)] for _ in range(d)]

Uma lista de números aleatórios, entre 1 e 10, onde o número de linhas é o mesmo que o número de colunas.
Para encontrar o maior elemento da matriz crie uma lista com os maiores elementos de cada linha e a partir dessa lista apenas encontre o maior elemento e esse será o maior elemento da matriz:
lambda m: max(list(map(max, m)))

O mais trabalhoso é encontrar as posições de ocorrência do maior elemento e mesmo assim não é nada demais. É precorrer as linhas da matriz coletar o índices dessas ocorrências e criar uma tupla (linha,coluna) de onde foram encontrados ocorrência do maior elemento:
def posição(elemento, matriz):
  ocorrencias = []
  for linha in range(len(matriz)):
    o = [i for i,v in enumerate(matriz[linha]) if v==elemento]
    for i in o:
      ocorrencias.append((linha,i))
  return ocorrencias

Juntando tudo:
import pprint #Usado para melhorar a impressão da matriz
from random import randint

matriz = lambda d: [[randint(1,10) for _ in range(d)] for _ in range(d)]

maior = lambda m: max(list(map(max, m)))

def posição(elemento, matriz):
  ocorrencias = []
  for linha in range(len(matriz)):
    o = [i for i,v in enumerate(matriz[linha]) if v==elemento]
    for i in o:
      ocorrencias.append((linha,i))
  return ocorrencias

mat = matriz(4)
mat_max = maior(mat)
mat_max_occor = posição(mat_max, mat)

pprint.pprint(mat,width=20) #Usado para melhorar a impressão da matriz
print(f'\nvalor máximo:{mat_max}')
print(f'Posições de ocorrencia do valor máximo:{mat_max_occor}')

Código funcionando no Repl.it: https://repl.it/repls/UltimateCulturedPresses
Funções utilizadas:
max(): https://docs.python.org/3/library/functions.html#max
map(): https://docs.python.org/3/library/functions.html#map
list(): https://docs.python.org/3/library/functions.html#func-list
enumerate(): https://docs.python.org/3/library/functions.html#enumerate


How can I embed a webform in an Ionic React app?

Question: Webform has a Share submodule that can be used in decoupled situations.
There is a video tutorial here.
However, I'm having trouble getting my webform embedded in my Ionic React app.
What I have done

Went to /admin/structure/webform/config and selected Enable form sharing under Form share settings.
Went to /admin/structure/webform, clicked the more info triangle, selected Share.

I now have the option to choose from JavaScript, Resizing iframe, and Fixed iframe, but all of these use document.write, which won't work with Ionic because the document has already been written.
Comment: Yeh that document.write is an old-school hack and maybe it needs to be reworked.  Thanks for posting what looks like a great solution.
Answer: Here is specifically how to do this in Ionic + React.
First, Webform share uses the iframe-resizer library, which has an official react component.
So install the library into your app:
npm install iframe-resizer-react
Then add a component such as WebformContact.tsx (this example uses TypeScript):
import * as React from 'react';
import {
  IonContent, IonPage,
} from '@ionic/react';
import IframeResizer from 'iframe-resizer-react';

const styleWebformIframeEmbed: React.CSSProperties = {
  width: '1px',
  minWidth: '100%',
};

const WebformContact = () => (
  <IonPage>
    <IonContent>
      <IframeResizer
        src="https://example.com/webform/MY-WEBFORM-MACHINENAME/share/iframe-resizer/4.2.10"
        title="MY WEBFORM TITLE"
        frameBorder="0"
        allowFullScreen
        style={styleWebformIframeEmbed}
      />
    </IonContent>
  </IonPage>
);
export default WebformContact;

Note that you need to install the same version of iframe-resizer in both webform (drupal) + your ionic app.
Also note that if your site is https, you should be sure to specify that in the src tag; when React is hosted by Ionic, it will be run from http://localhost (Android) or http://capacitor (iOS), so if you do not specify https for the server, you will get a difficult to understand error:

iframeResizer.js:822 Failed to execute 'postMessage' on 'DOMWindow':
The target origin provided

But really what this means is that you are trying to access an https server in an iframe with http.  So specify https!


ORACLE calculate hours between two timestamps

Question:
Possible Duplicate:
Calculate difference between 2 date / times in Oracle SQL

so i am creating a database for an airline as part of my university coursework. first time using oracle.
I am trying to calculate the hours between two timestamps.
so something like
<code>v_interval = new.departure_time - v_arrival_time;
v_days = extract (day . v_interval);
v_hours = extract (hours, v_interval) + (v_days * 24);
</code>
how do you guys think i should do it?
Answer: Similar question:

Calculate difference between 2 date / times in Oracle SQL

More examples:

Date / Time Arithmetic with Oracle 9/10


Multi-Master K8S cluster fails when half of the masters are down

Question: i have a 4 masters HA K8S cluster , (accross 2 datacenters , 2 in each site) , but the kubectl command stops working after shuting down 2 masters , is this the expected behaviour?
I want the cluster to survive a Datacenter crash.
PS : I am using 2 HA proxy + Keepalived
Answer: I assume your master would host etcd containers, are they? Then this is expected, yes.
Check etcd FAQ. A 4 nodes cluster would indeed have a failure tolerance of 1 member. You would need 5 members, to allow for 2 failures. Though the recommended sizing running Kubernetes is usually 3.
Multi-datacenter deployments can be complicated: latency in between etcd members would be an issue. If this is fine with you, to survive a DC crashing, then you need 3 DC. Otherwise, you'ld better look into setting up individual clusters, and implementing failovers/replication on top of those.


Coding categorical variables in logistic regression (and similar tool)

Question: Let us consider first case. I have logistic regression with one categorical variables with 3 distinct values. I can code as
Value A -> (0,0)
Value B -> (1,0)
Value C -> (0,1)

And with intercept my variables would look like
Value A -> (1,0,0)
Value B -> (1,1,0)
Value C -> (1,0,1)

Now once I have regression done, it is easy to interpret coefficients of regression. Value A will serve as base case. Let $x_B$ denote vector of value where B outcome of our categorical variable is present (and so on for other outcomes) and $\beta_B$ is the coefficient of B value
$odds(x):=p(x)/(1-p(x))$
$\frac{e^{x_B}}{e^{x_A}} = e^{\beta_B} = \frac{odds(x_B)}{odds(x_A)}$
So interpretation of $\beta_B$ is log of ratio of odds of B to A.
Now let us consider another case. I have two categorical variables. First variable is $Z$ with values $A,B,C$ and another categorical variable is $W$ with values $E,F,G$.
Now let us try to code it similar to the first case (with intercept)
value A -> 1,0,0,0,0,0
value B -> 1,1,0,0,0,0
value C -> 1,0,1,0,0,0
value E -> 1,0,0,1,0,0
value F -> 1,0,0,0,1,0
value G -> 1,0,0,0,0,1

With this coding I no longer get the same simplification as in the first case and interpret $\beta_E$ as before. Simplification works, but I get to compare value A and value E from different variables, while I rather compare outcomes within one variable.
Is there workaround, am I missing something?
UPDATE
Here is example using R to clarify my question
x <- sample(c('green', 'blue', 'red'), size=20, replace= TRUE)
y <- sample(c('east', 'west', 'north'), size=20, replace= TRUE)
outcome <- sample(c(1,0), size=20, replace= TRUE)
my_df <- data.frame(x, y, outcome)

model <- glm(outcome~., family=binomial(link = 'logit'), data=my_df)
summary(model)

Print out of results
Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -0.3449     1.2934  -0.267   0.7897
xgreen       -2.9008     1.6541  -1.754   0.0795 .
xred         -1.5273     1.4097  -1.083   0.2786
ynorth        1.7580     1.5611   1.126   0.2601
ywest         3.3712     1.8804   1.793   0.0730 .

What are interpretations of coefficienst and how interpretations are derived?
Comment: Are you using any program to perform your analyses?  Most of the modern statistical programs take care of all of this coding for your automatically.

Also, it's not 100% clear to me what you are asking.  Do you want to calculate the odds ratio of B to A with this new, expanded model, but you are confused as to how to do so because of the added complexity of having to average over other independent variables?
Comment: There is an important and illustrative mismatch between your presentation of the model matrix construction (following the text "Now let us try to code it similar to the first case (with intercept)"), in which your matrix has *six* columns, and the `R` output, *which gives only five parameter estimates.* Your coding actually corresponds to a *single* categorical variable with possible values A,B,C,E,F,G, rather than *two* categorical variables. If the distinction is still unclear, please execute `model.matrix(outcome~., my_df)` and inspect the output closely.
Comment: @whuber Thank you, what a great command `model.matrix(outcome~., my_df)`! I wish I knew it before I asked the question.
Comment: @StatsStudent: Let me add example using R to clarify my question.
Answer: I see a few conceptual mistakes here.
First of all, if $Z$ and $W$ are two variables in logistic regression, there should be no constraint on their input value. Logistic regression is a discriminative model, so no assumption is made about the distribution of the input variables. Therefore the values of $Z$ and $W$ should not be mutually exclusive. You are allowed to have an entry for both, which you neglected to allow when listing your values. Thus you have nine possible entries, not six.
Secondly, as you noted with one variable, each categorical variable need only one less binary variable than the number of classes. So with two categorical variables, each with three classes, you have 5 inputs. One bias (which is always one), and four binary variables representing the two 3-class categorical variables.
We can look at the model as having five parameters. $\beta_B,$ $\beta_C,$ $\beta_F,$ $\beta_G,$ and $\beta_0,$ where each subscript represents the categorical value it represents, and $\beta_0$ is the bias term which represents the "reference" values $Z=A$ and $W=E.$ (This is an arbitrary choice.) In general, the bias term absorbs the reference value of every categorical variable in the model.
Now, let's denote $l = \beta' X$ as the log-odds of an observation given $X$ (where $X$ is a five-vector of binary variables representing an observation and $\beta$ is the vector of five parameters). (Note that by "odds of an observation", what I mean is that it's the odds ratio of a "one" observation of your target variable given $X$ with respect to a "zero" observation given $X$.) Suppose we have $X_1 = (1,0,0,0,0)'$ and $X_2 = (1,0,0,1,0)'.$ This corresponds to $(Z,W) = (A,E)$ and $(Z,W) = (A,F)$ respectively. As well, $l_1 = \beta' X_1$ and $l_2 = \beta' X_2.$ Then,
$$
\frac{\text{odds}(X_2)}{\text{odds}(X_1)} = e^{l_2 - l_1} = e^{\beta_F}.
$$
So $\beta_F$ is the log of the odds ratios between observations $(Z,W) = (A,F)$ and $(Z,W) = (A,E).$ However, it's easy to see that this relationship would hold independent of what the value of $Z$ is. That is, if $Z=Z_0,$ then using the same analysis, we would find that $\beta_F$ is the log of the odds ration between observations $(Z_0,F)$ and $(Z_0,E),$ no matter what the value of $Z_0.$  Thus, $\beta_F$ is the log of the odds ratio between $W=F$ and $W=E.$ This is simply because of the choice of $E$ as the base line value.
You can easily extend this argument to any value of a categorical variable, with respect to the choice of reference value. In general, if $Z$ is a categorical input variable in logistic regression with $k$ levels, then it contains $k-1$ parameters, each of which represents the log-odds of an observation given a particular value of $Z$ with respect to an observation given the reference value of $Z.$ This is true regardless how however many other categorical variables are in the model.


Word disappears in Console.Write();

Question: My program shows the letter and then asks with what letter should you replace it:
static void Main(string[] args)
{
    string textToEncode = File.ReadAllText(@"C:\Users\ASUS\Desktop\szyfrowanie2\TextSample.txt");
    textToEncode = textToEncode.ToLower();
    string distinctLetters = new string(textToEncode.Distinct().ToArray());
    var count = textToEncode.Distinct().Count();
    Console.WriteLine("Letters used in text: \n\n");
    int iteration = 0;
    for (int i = 0; i < count; i++)
    {
        if (Equals(distinctLetters[i], ' ')) { Console.Write(" <space> "); }
        else if (Equals(distinctLetters[i], '\r')) { continue; }
        else if (Equals(distinctLetters[i], '\n')) { continue; }
        else { Console.Write(distinctLetters[i] + " "); }
    }
    Console.WriteLine("\n\nEncoding: \nPlease do not use single non-letter characters for coding (such as ',' or '?'");

    List<string> charsUsedToEncode = new List<string>();
    List<string> charsEncoded = new List<string>();
    while (iteration < count)
    {
        if (Equals(distinctLetters[iteration], ' ')) { Console.Write("Swap <space> with "); }
        else { Console.Write("Swap " + distinctLetters[iteration] + " with "); }
        string string1 = Console.ReadLine();
        if (string.IsNullOrEmpty(string1) == true)
        {
            Console.WriteLine("You have to type a character. ");
        }
        else if (string1.Length > 1)
        {
            Console.WriteLine("You entered more than one character. ");
        }
        else
        {
            char SwappingMark = char.Parse(string1);
            if (charsUsedToEncode.Contains(SwappingMark.ToString()))
            {
                Console.WriteLine("\nThis character has already been used.");
            }
            else if (Equals(distinctLetters[iteration], '\r')) { continue; }
            else if (Equals(distinctLetters[iteration], '\n')) { continue; }
            else
            {
                charsEncoded.Add(distinctLetters[iteration].ToString());
                charsUsedToEncode.Add(SwappingMark.ToString());
                SwappingMark = char.ToUpper(SwappingMark);
                textToEncode = textToEncode.Replace(distinctLetters[iteration], SwappingMark);
                iteration++;
            }
        }
    }
    textToEncode = textToEncode.ToLower();
    Console.ReadLine();
}

The problem is, after a '.' char The word "Swap" disappears. It looks like this:

Swap w with a
...
Swap . with x
y with l

The word "Swap" disappears. In my TextSample after a '.' text starts in new line and I don't know why, since there is a  else if (Equals(distinctLetters[iteration], '\n')) { continue; } condition.
Comment: Instead of checking for `\n` and `\r` just use `Environment.NewLine`
Comment: how should I do it?
Comment: can you please share sample input text
Comment: `if (Equals(distinctLetters[iteration], '\n')) { continue; }` is only used _after_ you print the "swap" statement. So, you display the statement anyway and then ignore it later. You must not display it in the first place.
Comment: @germi Not really. Using `\r` and `\n` is actually better in this case because the text file might contain either of them. If `Environment.NewLine` happens to be `\r\n`, it won't work.
Comment: [link](https://pastebin.com/00ABZXFF) here is a text sample, I should've shared it earlier, sorry.
Answer: As I mentioned in the comments, the problem is that you skip the new-line characters before printing them but they're still in the string. So, you skip them again but after actually printing the "swap" statement to the user (causing those characters to be displayed before they're ignored).
What you should do instead is not include them in the array from the beginning. Also, there's no need to create a new string; you can just use a char array like this:
char[] distinctLetters = textToEncode.Distinct()
                                     .Where(c=> !"\r\n".Contains(c))
                                     .ToArray();

That way, you never have to check for \r or \n again since they don't exist.
Full example:
static void Main(string[] args)
{
    string textToEncode = File.ReadAllText(@"C:\Users\ASUS\Desktop\szyfrowanie2\TextSample.txt");
    textToEncode = textToEncode.ToLower();
    char[] distinctLetters = textToEncode.Distinct()
                                         .Where(c=> !"\r\n".Contains(c))
                                         .ToArray();
    var count = distinctLetters.Count();
    Console.WriteLine("Letters used in text: \n\n");
    int iteration = 0;
    for (int i = 0; i < count; i++)
    {
        if (distinctLetters[i] == ' ') { Console.Write(" <space> "); }
        else { Console.Write(distinctLetters[i] + " "); }
    }
    Console.WriteLine("\n\nEncoding: \nPlease do not use single non-letter characters for coding (such as ',' or '?'");

    List<string> charsUsedToEncode = new List<string>();
    List<string> charsEncoded = new List<string>();
    while (iteration < count)
    {
        if (distinctLetters[iteration] == ' ') { Console.Write("Swap <space> with "); }
        else { Console.Write("Swap " + distinctLetters[iteration] + " with "); }
        string string1 = Console.ReadLine();
        if (string.IsNullOrEmpty(string1))
        {
            Console.WriteLine("You have to type a character. ");
        }
        else if (string1.Length > 1)
        {
            Console.WriteLine("You entered more than one character. ");
        }
        else
        {
            char SwappingMark = char.Parse(string1);
            if (charsUsedToEncode.Contains(SwappingMark.ToString()))
            {
                Console.WriteLine("\nThis character has already been used.");
            }
            else
            {
                charsEncoded.Add(distinctLetters[iteration].ToString());
                charsUsedToEncode.Add(SwappingMark.ToString());
                SwappingMark = char.ToUpper(SwappingMark);
                textToEncode = textToEncode.Replace(distinctLetters[iteration], SwappingMark);
                iteration++;
            }
        }
    }
    textToEncode = textToEncode.ToLower();
    Console.ReadLine();
}

Word disappears in Console.Write();


How Can I Change The Language & Navigate To Another Page Simultaneously?

Question: Having developed a redux responsible for selecting the application's language, I am facing some difficulties in changing the language and navigating to another page within one click. Two clicks are needed: First Click: Language Update - Second Click: Navigation Process. Getting a quick hand would be highly valued. Here is the source code:
languageActionTypes.tsx
export const SET_ENGLISH = 'SET_ENGLISH';
export const SET_ARABIC = 'SET_ARABIC';
export const SET_ESPANOL = 'SET_ESPANOL';

languageActionCreator.tsx
import * as languageActionTypes from '../ActionTypes/languageActionTypes';

export const setEnglish = () => {
  const action = {
    type: languageActionTypes.SET_ENGLISH,
  };
  return action;
};

export const setArabic = () => {
  const action = {
    type: languageActionTypes.SET_ARABIC,
  };
  return action;
};

export const setEspanol = () => {
  const action = {
    type: languageActionTypes.SET_ESPANOL,
  };
  return action;
};

languageReducer.tsx
import {SET_ENGLISH, SET_ARABIC, SET_ESPANOL} from '../ActionTypes/languageActionTypes';

const initialState = {language: 'en'};

const LanguageReducer = (state = initialState, action: any) => {

  switch (action.type) {
    case SET_ENGLISH:
      return {language: 'en'};
    case SET_ARABIC:
      return {language: 'ar'};
    case SET_ESPANOL:
      return {language: 'sp'};
    default:
      return state;
  }

};

export default LanguageReducer;

LanguageSelector.tsx
import React from 'react';
import {SafeAreaView, ImageBackground, Image, Text, View, TouchableOpacity} from 'react-native';
import * as Animatable from 'react-native-animatable';
import {images} from '../../constants';
import styles from './LanguageSelectorStyle';
import {connect} from 'react-redux';
import {setEnglish, setArabic, setEspanol} from '../../store/Actions/languageActionCreator.tsx';
import '../../assets/i18n/i18n';
import {useTranslation} from 'react-i18next';

const LanguageSelector = ({navigation, language, makeEnglish, makeArabic, makeEspanol}: any) => {

  const {i18n} = useTranslation();

  const transEnglish = () => {
    i18n
      .changeLanguage(language)
      .then(() => {
        makeEnglish();
        language === 'en' && navigation.navigate('RegistrationLogin');
      })
      .catch(err => console.log(err));
  };

  const transArabic = () => {
    i18n
      .changeLanguage(language)
      .then(() => {
        makeArabic();
        language === 'ar' && navigation.navigate('RegistrationLogin');
      })
      .catch(err => console.log(err));
  };

  const transEspanol = () => {
    i18n
      .changeLanguage(language)
      .then(() => {
        makeEspanol();
        language === 'sp' && navigation.navigate('RegistrationLogin');
      })
      .catch(err => console.log(err));
  };

  return (
    <SafeAreaView>
      <ImageBackground style={styles.backgroundImage} source={images.backgroundImage} resizeMode="cover">
        <View style={styles.content}>
          <Image style={styles.appLogo} source={images.fullDTTLogo} resizeMode="contain" />
          <View style={styles.actionView}>
            <Animatable.View
              animation="bounceInUp"
              iterationCount={1}
              iterationDelay={500}
              direction="alternate">
              <TouchableOpacity
                style={styles.actionBtn}
                onPress={() => {transEnglish()}}>
                <Text style={styles.actionTxtBtn}>English</Text>
              </TouchableOpacity>
            </Animatable.View>
            <Animatable.View
              animation="bounceInUp"
              iterationCount={1}
              iterationDelay={1000}
              direction="alternate">
              <TouchableOpacity
                style={styles.actionBtn}
                onPress={() => {transArabic()}}>
                <Text style={styles.actionTxtBtn}>Arabic</Text>
              </TouchableOpacity>
            </Animatable.View>
            <Animatable.View
              animation="bounceInUp"
              iterationCount={1}
              iterationDelay={1500}
              direction="alternate">
              <TouchableOpacity
                style={styles.actionBtn}
                onPress={() => {transEspanol()}}>
                <Text style={styles.actionTxtBtn}>Espanol</Text>
              </TouchableOpacity>
            </Animatable.View>
          </View>
        </View>
      </ImageBackground>
      {console.log('Language:', language)}
    </SafeAreaView>
  );

};

const mapStateToProps = (state: any) => {
  return {
    language: state.LanguageReducer.language,
  };
};

const mapDispatchToProps = (dispatch: any) => ({
  makeEnglish: () => dispatch(setEnglish()),
  makeArabic: () => dispatch(setArabic()),
  makeEspanol: () => dispatch(setEspanol()),
});

export default connect(mapStateToProps, mapDispatchToProps)(LanguageSelector);

Answer: If I understand your requirement correctly, can you expand the translation functions to include a navigate call?
Instead of
onPress={() => {transArabic()}}>

You could try
onPress={() => {
  transArabic();
  navigation.navigate('someScreen');
}}>


The probability that a student will receive a point if he correctly selects both specific elements from a set of 20 elements.

Question: At chemistry classes, the student receives a set of 20 names of chemical compounds. Among them there are two lipids that should be underlined. If both correct lipids are marked correctly, the student gets a point. Rightfully? Is such success trustworthy? How likely is it to get a point in this way of checking knowledge in the complete ignorance of the student? How likely is it to hit one lipid?
My answers to the last two questions:

Both lipids: $\frac{\binom{2}{2}}{\binom{20}{2}} = \frac{1}{190} = 0.00526... ≈ 0.53$%
Exactly one lipid: $\frac{\binom{2}{1}*\binom{18}{1}}{\binom{20}{2}} = \frac{18}{95} = 0.18947... ≈ 18.95$%

But what should be the answers to the first two questions? Thanks for help.
Answer: Your calculations are correct.  The probability of missing both answers is $$\frac{\binom{18}{2}}{\binom{20}{2}} = \frac{153}{190},$$ and since the number of correct guesses can only be $0$, $1$, or $2$, we see that these probabilities must add to $1$:
$$\frac{1}{190} + \frac{18}{95} + \frac{153}{190} = \frac{1 + 36 + 153}{190} = 1.$$
As to the question of whether such a success is "trustworthy," that depends on the tolerance for error.  If the instructor wants no more than $1\%$ of students who guess randomly to get both choices correct (and therefore receive a point), then this method is sufficiently trustworthy, because the probability is $0.526316\% < 1\%$.  But if the instructor wants no more than $0.1\%$ of such students to receive a point by guessing, then it is insufficient.  The question could be redesigned; e.g., identify $3$ out of $3$ correct choices among $20$ possibilities, which has a probability of $$\frac{1}{\binom{20}{3}} = \frac{1}{1140} \approx 0.0877193\% < 0.1\%.$$
Comment: Well, there is no specification from the instructor, but okay, thanks for the answer. But what about the question, if it is rightfully?


Can any one tell what's wrong with the following script in disabling the list of dates

Question: I used Keith-Wood calendar for that i added some script as follows

I am also having this too to disable weekends

But i am unable to disable the dates as per in the list can any one tell what's wrong i am doing
My design is as follows
<asp:TextBox ID="txtDateofBirth" runat="server" Style="left: 398px; position: absolute;
top: 131px" />

Answer: holidays[i] is a string, you cant use a getTime() on it.
So rather do
if (date.toString('MM-dd-yyyy')==holidays[i])

Comment: Yes you need to change your dates to 2 digits ie like 12-2-2010 to 12-02-2010, and i dont see the change i told you in your code
Comment: So as per you saying there is no need to write like this `'12-2-2010'`
Comment: But still i am not getting my result if you have done this can you post the script as per my requirement
Comment: Can you add this code, alert(date.toString('MM-dd-yyyy')); outside the for loop and tell me what it is alerting
Comment: I didn't get any alert if i write that


Given an odd integer, $a$ does $\gcd(a,p-1)=1$ has infinitely many prime $p$ solutions?

Question: Given an odd integer, $a$ does   $\gcd(a,p-1)=1$ has infinitely many prime $p$ solutions?
One can argue that there are infinitely many numbers $x$ satisfies $\gcd(a,$x$)=1$. How to argue that there are infinitely many prime $p=x+1$.
Any hint?
Comment: If $a$ is even, no...  But if $a$ is odd, my hint would be to apply the Dirichlet arithmetic progression theorem.
Comment: When $a=2$ this asks: are there infinitely many even primes?
Comment: let me correct to odd.
Answer: By Dirichlet's theorem, there are infinitely many primes in the arithmetic series $2+na$, ($n\in \mathbb{N}$).
If $p=2+na$ is such a prime, then $\gcd(a, p-1) = \gcd(a, 1+na) = 1$.


Why does PyYAML 5.1 raise YAMLLoadWarning when the default loader has been made safer already?

Question: Here is my code:
import yaml
yaml.load('foo')

This code leads to the following warning with PyYAML (5.1).
$ pip install pyyaml
$ python3 foo.py
foo.py:2: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.
  yaml.load('foo')

So I visited https://msg.pyyaml.org/load to see what this is about but I do not understand the need for this warning.
First, the documentation says,

UnsafeLoader (also called Loader for backwards compatability)
The original Loader code that could be easily exploitable by untrusted data input.

Okay, that makes sense. In an earlier version, the original loader was unsafe. Further, it says,

FullLoader
Loads the full YAML language. Avoids arbitrary code execution. This is currently (PyYAML 5.1) the default loader called by yaml.load(input) (after issuing the warning).

So the current version uses FullLoader which is not unsafe. This is confirmed again in the document.

The load function was also made much safer by disallowing the execution of arbitrary functions by the default loader (FullLoader).

If the current version that uses FullLoader is not unsafe, then why do we need the YAMLLoadWarning at all?
Comment: I think you should read "**much** safer"  as: *not as unsafe as the original, but still not completely safe*. You are reading it as that it is *safe* (i..e "not unsafe")
Answer: I think this warning is more like a notification & guidance to let the user know what is the PyYAML best practice in the future. Recall that: Explicit is better than implicit.

Before version 5.1 (e.g. 4.1), the yaml.load api use Loader=Loader as default:
def load(stream, Loader=Loader):
    """
    Parse the first YAML document in a stream
    and produce the corresponding Python object.
    """
    loader = Loader(stream)
    try:
        return loader.get_single_data()
    finally:
        loader.dispose()

def safe_load(stream):
    """
    Parse the first YAML document in a stream
    and produce the corresponding Python object.
    Resolve only basic YAML tags.
    """
    return load(stream, SafeLoader)

At that time, there were only three available choice for Loader class: limited BaseLoader, SafeLoader and the unsafe Loader. Although the default one is unsafe, just like we read from the doc:

PyYAML's load function has been unsafe since the first release in May
  2006. It has always been documented that way in bold type: PyYAMLDocumentation.
  PyYAML has always provided a safe_load function that can load a subset of
  YAML without exploit.

But there are still a lot of resources and tutorials prefer using yaml.load(f) directly, so the users (and especially the new user) are choosing a default Loader class implicitly.

And since PyYAML version 5.1, the yaml.load api is changed to be more explicit:
def load(stream, Loader=None):
    """
    Parse the first YAML document in a stream
    and produce the corresponding Python object.
    """
    if Loader is None:
        load_warning('load')
        Loader = FullLoader

    loader = Loader(stream)
    try:
        return loader.get_single_data()
    finally:
        loader.dispose()

def safe_load(stream):
    """
    Parse the first YAML document in a stream
    and produce the corresponding Python object.
    Resolve only basic YAML tags. This is known
    to be safe for untrusted input.
    """
    return load(stream, SafeLoader)

And a new FullLoader is added into Loader classes. As users, we should also be aware of the changes and use yaml.load more explicitly:

yaml.load(stream, yaml.SafeLoader)
Recommended for untrusted input. Limitation: Loads a subset of the YAML language.
yaml.load(stream, yaml.FullLoader)
For more trusted input. Still a bit of Limitation: Avoids arbitrary code execution.
yaml.load(stream, yaml.Loader) (UnsafeLoader is the same as Loader)
Unsafe. But has the full power.


SYSLOG-NG - Having trouble with a destination

Question: I'm trying to set up a seperate log file for all windows messages. I've set up a match for MSWinEventLog, but it's completely ignoring my configuration
Here's my config, which is straight after the src object
filter f_windows    { match("MSWinEventLog"); };
destination winFIFO { file("/var/log/splunk/syslog-ng/winFIFO"); };
log { source(src); filter(f_windows); destination(winFIFO); flags(final); };

It all ends up in this one instead:
filter f_messages   { not facility(news, mail) and not filter(f_iptables); };
destination messages { file("/var/log/messages"); };
log { source(src); filter(f_messages); destination(messages); };

Can anyone see what i'm doing wrong?
Answer: hmm... here's mine lifted from gentoo's security handbook w/ some iptables modifications. honestly I don't remember how I wrote it but maybe the term 'value' has some meaning?

@version: 3.0
#
# /etc/syslog-ng.conf
#

options {
  stats_freq (0);
  flush_lines (0);
  time_reopen (10);
  log_fifo_size (1000);
  long_hostnames(off);
  use_dns (no);
  use_fqdn (no);
  create_dirs (no);
  keep_hostname (yes);
  perm(0640);
  group("log");
};

source src {
  unix-stream("/dev/log");
  internal();
  file("/proc/kmsg");
};

destination d_authlog { file("/var/log/auth.log"); };
destination d_syslog { file("/var/log/syslog.log"); };
destination d_cron { file("/var/log/crond.log"); };
destination d_daemon { file("/var/log/daemon.log"); };
destination d_kernel { file("/var/log/kernel.log"); };
destination d_lpr { file("/var/log/lpr.log"); };
destination d_user { file("/var/log/user.log"); };
destination d_uucp { file("/var/log/uucp.log"); };
destination d_mail { file("/var/log/mail.log"); };
destination d_news { file("/var/log/news.log"); };
destination d_ppp { file("/var/log/ppp.log"); };
destination d_debug { file("/var/log/debug.log"); };
destination d_messages { file("/var/log/messages.log"); };
destination d_errors { file("/var/log/errors.log"); };
destination d_everything { file("/var/log/everything.log"); };
destination d_iptables { file("/var/log/iptables.log"); };
destination d_acpid { file("/var/log/acpid.log"); };
destination d_console { usertty("root"); };

# Log everything to tty12
destination console_all { file("/dev/tty12"); };

filter f_auth { facility(auth); };
filter f_authpriv { facility(auth, authpriv); };
filter f_syslog { program(syslog-ng); };
filter f_cron { facility(cron); };
filter f_daemon { facility(daemon); };
filter f_kernel { facility(kern) and not filter(f_iptables); };
filter f_lpr { facility(lpr); };
filter f_mail { facility(mail); };
filter f_news { facility(news); };
filter f_user { facility(user); };
filter f_uucp { facility(cron); };
filter f_news { facility(news); };
filter f_ppp { facility(local2); };
filter f_debug { not facility(auth, authpriv, news, mail); };
filter f_messages { level(info..warn) and not facility(auth, authpriv, mail, news, cron) and not program(syslog-ng) and not filter(f_iptables); };
filter f_everything { level(debug..emerg) and not facility(auth, authpriv); };
filter f_emergency { level(emerg); };
filter f_info { level(info); };
filter f_notice { level(notice); };
filter f_warn { level(warn); };
filter f_crit { level(crit); };
filter f_err { level(err); };
filter f_iptables { match("IN=" value("MESSAGE")) and match("OUT=" value("MESSAGE")); };
filter f_acpid { program("acpid"); };

log { source(src); filter(f_acpid); destination(d_acpid); };
log { source(src); filter(f_authpriv); destination(d_authlog); };
log { source(src); filter(f_syslog); destination(d_syslog); };
log { source(src); filter(f_cron); destination(d_cron); };
log { source(src); filter(f_daemon); destination(d_daemon); };
log { source(src); filter(f_kernel); destination(d_kernel); };
log { source(src); filter(f_lpr); destination(d_lpr); };
log { source(src); filter(f_mail); destination(d_mail); };
log { source(src); filter(f_news); destination(d_news); };
log { source(src); filter(f_ppp); destination(d_ppp); };
log { source(src); filter(f_user); destination(d_user); };
log { source(src); filter(f_uucp); destination(d_uucp); };
#log { source(src); filter(f_debug); destination(d_debug); };
log { source(src); filter(f_messages); destination(d_messages); };
log { source(src); filter(f_err); destination(d_errors); };
log { source(src); filter(f_emergency); destination(d_console); };
log { source(src); filter(f_everything); destination(d_everything); };
log { source(src); filter(f_iptables); destination(d_iptables); };

# Log everything to tty12
#log { source(src); destination(console_all); };

Answer: Syslog had got itself in a bit of a knot. When I stopped the service, it would still be visible when I did a 'ps -ef |grep syslog' - I killed it, and restarted the service anew and it works fine now.


Como capturar o evento de fechamento em um Stage?

Question: Estou procurando um evento tipo o "windows close" do Swing.
Answer: Você pode chamar o método setOnCloseRequest do seu Stage, dessa forma você pode executar uma ação assim que o usuário cliciar no botão para fechar a janela.
Ex.:
<code>public class Teste extends Application {
    @Override
    public void start(Stage stage) {
        stage.setOnCloseRequest(event -> System.out.println("Fechando o programa"));

        Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>


Delete user account after checkout completion

Question: Im trying to create a rule that deletes an user account after checkout completion for New users, but it is not working. Can anyone please help me to figure out what is wrong? after checkout completion, check if user is not admin or any other role, then delete the account. After anonymous checkout, an user account is created (blocked, registered).
<code>{ "rules_delete_user_account_after_checkout" : {
  "LABEL" : "Delete User Account after Checkout",
  "PLUGIN" : "reaction rule",
  "WEIGHT" : "3",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules", "php", "uc_cart" ],
  "ON" : { "uc_checkout_complete" : [] },
  "IF" : [
    {
      "NOT data_is" : {
        "data" : [ "order:customer:roles" ],
        "value" : { "value" : { "3" : "3" } }
      }
    }
  ],
  "DO" : [
    { "php_eval" : { "code" : "\/\/ Delete the user.\r\nuser_delete(NULL, [order-uid]);" } }
  ]
}}
</code>
Answer: Deleting a user after checkout is a bad idea. I assume you know this, but the client is asking/forcing you to do this.
check this link - automatically delete all Ubercart-created users,  this has a solution.
Comment: Welcome to Drupal Answers! Link-only answers are not considered answers, on Stack Exchange. May you edit your answer to make it independent from the external site?
Answer: thanks for the link. I did followed the recommendation from the post.

After saving a new user account, Customer completes checkout: assign
new user an "ubercart" role.
Customer completes checkout, User has the ubercart role and user is not admin or any of the other roles, execute php code:
// Delete the user.
user_delete($order->uid);


how to align multiple jpanels under each other

Question: in the below code i am trying to create tabs.
1-according to the code below, the jlabel the contains the word "Demo", at run time, it does not show up! why that is happening and how to force that jlabel to appear?
2-as you see in the code, the function createTab1() should create jTextField and JPasswordField. at run time they are appearing but they are alligined horizontally, what i want is, to display the JTextField and its jlabel beside each other horizontally and the second jlabel and the JpassworfField beside each other but under the jTextField and its jLabel, as shown below:
 Labe     jtextField
 label    jPasswordField

but the code below result the GUI shown in
Code:
private void setUpGUI() {
    // TODO Auto-generated method stub
    jFrame_Main = new JFrame("Main Window");
    jPanel_ContainerPanel = new JPanel(new BorderLayout());
    jPanel_ContainerPanel.setBorder(BorderFactory.createLoweredBevelBorder());
    jLabel_ContainerLabel = new JLabel("Demo");
    jLabel_ContainerLabel.setHorizontalAlignment(SwingConstants.CENTER);

    jPanel_ContainerPanel.add(jLabel_ContainerLabel, BorderLayout.NORTH);

    createTab1();
    //createTab2();

    jTabbedPane = new JTabbedPane();
    jTabbedPane.add("tab1", jPanel1);

    jFrame_Main.getContentPane().add(jPanel_ContainerPanel);
    jFrame_Main.getContentPane().add(jTabbedPane);
    jFrame_Main.pack();
    jFrame_Main.setVisible(true);
}

private void createTab1() {
    // TODO Auto-generated method stub
    jPanel1 = new JPanel();
    jPanel1.setBounds(10, 15, 150, 20);
    jLabel1 = new JLabel("userName");
    jPanel1.add(jLabel1);

    JTextField field = new JTextField();
    field.setBounds( 10, 35, 150, 50 );
    jPanel1.add( field );

    JLabel label2 = new JLabel( "Password:" );
    label2.setBounds( 10, 60, 150, 20 );
    jPanel1.add( label2 );

    JPasswordField fieldPass = new JPasswordField();
    fieldPass.setBounds( 10, 80, 150, 20 );
    jPanel1.add( fieldPass );
}

public static void main(String[] args) {
    GUITabs guiTabs = new GUITabs();
}

}
Comment: why don't you use netbeans ? you can easily design those type of GUI s.
Comment: yes darg and drop is enabled in netbeans. You can drag panels buttons labels and etc. to the jframe and make GUI s easily.
Comment: [Link](https://netbeans.org/downloads/)  you can download netbeans IDE from this link
Comment: @MeshBoy actually i ahve not used it before but , does it offer more handy ways to draw the gui , like using drag and drop for an example...because currently i am using eclipse
Comment: @MeshBoy i downloaded netbeans but i really do not know where to go to find swing editor with drag and drop...can u please help
Answer: Problems:

You are using setBounds(...) to add a component to a container (a JPanel) that by default uses a FlowLayout, a layout that does not respect the size/position/bounds properties of its components.
While yes, you could use setBounds(...) on a JPanel that is explicitly defined to use null layouts, I'm going suggest that you not do this as this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain. Instead you will want to study and learn the layout managers and then nest JPanels, each using its own layout manager to create pleasing and complex GUI's that look good on all OS's.
It has been suggested that you use NetBeans drag-and-drop to create your complex GUI's, and while this will work, you will not understand the underlying layouts that NetBeans and Swing are using, and thus will eventually run up into a wall when you need to go beyond the abilities of NetBeans, such as if you want to change layout or add components in the midst of program run. For that reason you're far better off learning about and using the layout managers. You can find the layout manager tutorial here: Layout Manager Tutorial, and you can find links to the Swing tutorials and to other Swing resources here: Swing Info.
You need to give your JTextField and your JPasswordField a column value via setColumn(int column). This will give the field some width.
Myself, I'd use a GridBagLayout to place the JLabel's, JTextFields and JPasswordFields into your JPanel
I'd also not get username and password information from a tab, but rather from a modal dialog such as a JOptionPane. This way the user is prevented from accessing your main GUI until he appropriate handles the modal dialog.

For example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Arrays;
import javax.swing.*;

public class UserNamePassword {
   private static final int COLUMN_COUNT = 10;
   private static final int I_GAP = 3;
   private JTextField userNameField = new JTextField();
   private JPasswordField passwordField = new JPasswordField();
   private JPanel mainPanel = new JPanel(new GridBagLayout());

   public UserNamePassword() {
      userNameField.setColumns(COLUMN_COUNT);
      passwordField.setColumns(COLUMN_COUNT);

      GridBagConstraints gbc = getGbc(0, 0, GridBagConstraints.BOTH);
      mainPanel.add(new JLabel("User Name:"), gbc);
      gbc = getGbc(1, 0, GridBagConstraints.HORIZONTAL);
      mainPanel.add(userNameField, gbc);
      gbc = getGbc(0, 1, GridBagConstraints.BOTH);
      mainPanel.add(new JLabel("Password:"), gbc);
      gbc = getGbc(1, 1, GridBagConstraints.HORIZONTAL);
      mainPanel.add(passwordField, gbc);
   }

   public static GridBagConstraints getGbc(int x, int y, int fill) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.weightx = 1.0;
      gbc.weighty = 1.0;
      gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
      gbc.fill = fill;

      return gbc;
   }

   public String getUserName() {
      return userNameField.getText();
   }

   public char[] getPassword() {
      return passwordField.getPassword();
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }

   private static void createAndShowGui() {
      UserNamePassword project2 = new UserNamePassword();

      int input = JOptionPane.showConfirmDialog(null, project2.getMainPanel(),
            "Login", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
      if (input == JOptionPane.OK_OPTION) {
         if (project2.getUserName().equals("username") &&
               Arrays.equals(project2.getPassword(), "password".toCharArray())) {
            // you're good
         } else {
            JOptionPane.showMessageDialog(project2.getMainPanel(),
                  "error message", "Error Title", JOptionPane.ERROR_MESSAGE);
         }
      }
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}


Programmatically update a field's value

Question: I want to update a node field's value when a node is updated.
Tried using the code mentioned here Programmatically updating a node Drupal 8
use Drupal\node\Entity\Node;

    function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

      $check = \Drupal::routeMatch()->getParameter('node');

      if ($check) {
      $node = Node::load($check->nid->value);
      $node->title->value = 'testing';     //set value for field
      $node->save();
      }
    }

but it did not work. I get a 500 error after saving the node. I also tried taking out the if statement and specifying a node id $node = Node::load(1);
I also tried using Update a node / Entity programmatically in Drupal 8
use Drupal\node\Entity\Node;

function hello_world_node_update(Drupal\node\NodeInterface $node) {

$node = Node::load(1);
$node->set("title", 'New value'); // also tried $node->setTitle('The new Title');
$node->save();

}

but no luck either.
In addition, I tried using different hooks entity_presave, entity_update, node_update, but did not make any difference.
Answer: You can try this code:
function MODULE_NAME_node_presave(Drupal\node\NodeInterface $node) {
  $node->setTitle('new Title');
  $node->set('body', 'this is body');
}

Answer: This is another variation with using the hook you originally tried to use.
I think the problem with your code is that you try to load a new instance of the node, but you should use the node that is provided as paramater $entity:
use Drupal\node\NodeInterface;

function hello_world_entity_presave(Drupal\Core\Entity\EntityInterface $entity)   {
  if ($entity instanceof NodeInterface) {
    $entity->title->value = 'testing';     //set value for field
    // $entity->save(); (not needed)
  }
}

Edit:
Added the use statement to the code.
Comment: just tried your code, but it's breaking the site, getting the classic `The website encountered an unexpected error. Please try again later.`
Comment: This code is only to demonstrate how to use the hook. You need the right use statements. You can find this out, if you look in watchdog (/admin/reports/dblog).
Comment: adding `use Drupal\node\NodeInterface;` code no longer auto breaks the site, but after saving the node, I get the 500 error like I was getting in my question and the logs is not logging anything about it.
Comment: I only wanted to point at the problem: Don't load a new instance of the node, but use the one provided as function parameter. What error is behind 500? Please check your log files or switch on error logging.
Comment: I clear the log, so I don't get confused with all the other previous errors, but after saving and getting the error multiple times [log files are empty](http://i.stack.imgur.com/69QDE.jpg)
Comment: You will have a hard time debugging this without error logging. Did you check your php settings? (http://stackoverflow.com/questions/2687730/how-can-i-make-php-display-the-error-instead-of-giving-me-500-internal-server-er)
Comment: I found the second problem. In the presave hook we don't need to save. We only change the object. I remove this from the code.
Comment: great ✓ works now.
Comment: Notice: Indirect modification of overloaded element of Drupal\Core\Field\FieldItemList has no effect , How to get rid of this notice ??
Comment: Note that when not in the `preSave` context, you do indeed need to run `$entity->save()` after setting the field (such as from a custom module update hook).
Answer: Titles in Drupal 8 are not set like standard fields; they have their own function. Use $node->setTitle('New Title'); for a node or $entity->setLabel('New Title'); for a generic entity. See Node::setTitle for more info.

Programmatically update a field's value


$p\notin A$ a limit point of $A \iff$ for every $\delta > 0$ the intersection $B(p;\delta )\cap A$ is infinite

Question: I need to prove that $p\notin A$ a limit point of $A \iff$ for every $\delta > 0$ the intersection $B(p;\delta )\cap A$ is infinite. With $A\subset \mathbb{R}^n$ and $p\subset \mathbb{R}^n$.
To prove that the first implies the second, I wrote the following down, but I got stuck:
"$p$ is a limit point of $A$, so for every $\delta > 0$ it is true that $B(p;\delta) \cap A \neq \emptyset$. This means that there is at least one point in $B(p,\delta)\cap A$."
I also think $p\notin A$ and $p$ a limit point of $A$ means $A$ is an open set, is this correct?
My common sense tells me that if there is one point in the intersection of $A$ and $B(p,\delta)$, and $p$ a limit point of $A$ (an open set), then $p$ must be on the boundary of the open set $A$, is this correct? Then because "for every $\delta>0$ there is a point in $B(p,\delta)\cap A$", there must also be a point in $B(p,\frac{\delta}{2})\cap A$, so then there are definitely multiple points? Could I continue this argument to end up with infinite points in the intersection?
And for the implication the otherway around, is this line of thinking correct and complete (I'm not too sure):
For every $\delta>0$, the intersection $B(p;\delta )\cap A$ is infinite $\implies$ For every $\delta>0$ it is true that $B(p;\delta) \cap A \neq \emptyset$ $\implies$ $p$ a limit point of $A$.
Comment: How do you define limit point?
Comment: @JoséCarlosSantos Define $A\subset \mathbb{R}^n$ and $p\in \mathbb{R}^n$. $p$ is a limit point of $A$ if for all $\delta>0$ it is true that $B(a;\delta)\cap A \neq \emptyset$
Comment: @TheCodingWombat The definition in your comment only works if $p\notin A$. If $p\in A$ then $B(a,\delta)\cap A$ must contain an element $a\neq p$ for every $\delta>0$.
Comment: You're saying that if $p\in A$, then $B(a;\delta)\cap A$ does not contain an element $a\neq p$ for every $\delta> 0$ ? Does that mean my definition is wrong?
Comment: I am saying that $p$ is a limit point of $A$ iff for every $\delta>0$ the intersection $B(p,\delta)\cap A$ contains an element that differs from $p $. That last clausule was missing in your definition. E.g. the singleton $A=\{p\}$ has no limit points. This in spite of the fact that in that situation $A\cap B(p,\delta)$ contains $p$ hence is not empty for every positive $\delta$.
Answer: If there is only one point $a$ in $B(p,\delta)\cap A$ then for $\delta'\in(0,|p-a|)$ there are no points in $B(p,\delta')\cap A$, contradicting that $p$ is a limit point.
This contradiction also arises if $B(p,\delta)\cap A$ is finite by taking $\delta'\in(0,\min\{|p-a|\mid a\in B(p,\delta)\cap A\})$.
Conversely if for every $\delta>0$ the set $B(p,\delta)\cap A$ is infinite then it will be non-empty and elements in it will not equal $p$. This tells us that $p$ is a limit point of $A$.
Answer: Your idea is alright. You can use contradiction to get a rigorous proof.
If there are finitely many points in the set $B(p, \delta) \cap A$, then you can choose point $q \in B(p, \delta) \cap A$ s.t. the disance between the points from $B(p, \delta) \cap A$ and $p$ is minimum. Then we have that $B(p,\frac{d(p,q)}{2}) \cap A = \emptyset$, which contradicts the fact that $p$ is a limit point of $A$>
Also as $p \not \in A$ we have that $\frac{d(p,q)}{2} > 0$, so everything is well-defined.


Enabling smooth activity transition when changing between Day/Night mode

Question: I use the following code to switch between Day/night mode in my application:
SharedPreferences.Editor editor = sharedPrefs.edit();

AppCompatDelegate.setDefaultNightMode(isChecked
     ? AppCompatDelegate.MODE_NIGHT_YES
     : AppCompatDelegate.MODE_NIGHT_NO);

     if (isChecked) {
        editor.putBoolean("isDarkModeEnabled", true);
        editor.apply();
     } else {
        editor.putBoolean("isDarkModeEnabled", false);
        editor.apply();
}

When I switch modes, the activity blinks and is recreated. How can I have a smoother transition when switching modes (e.g. fade-in/fade-out between switching)? Can I use overridePendingTransition(), or is there another convenient way?
Comment: any solution for this ?
Comment: @ErenTüfekçi nope, I didn't manage. My app blinks when changing between day/night modes.
Comment: same problem here
Comment: @George Any luck with this?
Comment: @V-rundPuro-hit Unfortunately no, it still "blinks" while transitioning between light/dark modes.
Comment: Sad, it works fine in tutorials i watched. lol
Comment: The smooth transition is available in Android L, I think it was removed on newer version.
Answer: Insert below codes in your styles

and add this line your theme.
    @style/WindowAnimationTransition
Then you have smoother transition.
Or visit https://medium.com/@rohitksingh/start-your-activity-with-slide-animation-ae63017e4b7d for specific activity
Comment: Well, the issue with this is that it overrides all activity transitions for my app. I'd like to leave the default android version transition for that, and just get rid of the "blinking" when switching between DayNight modes.
Comment: You can try overridePendingTransition(enterAnim,exitAnim) after startActivity
and you can check this article for more
https://medium.com/@rohitksingh/start-your-activity-with-slide-animation-ae63017e4b7d


For what positive value of $c$ does the equation $\log(x)=cx^4$ have exactly one real root?

Question: For what positive value of $c$ does the equation $\log(x)=cx^4$ have exactly
one real root?
I think I should find a way to apply IMV and Rolle's theorem to $f(x) = \log(x) - cx^4$. I think I should first find a range of values for $c$ such that the given equation has a solution and then try to find one that gives only a unique solution. I have thought over it but nothing comes to my mind. Perhaps I'm over-complicating it.
Any ideas on how to proceed are appreciated.
Answer: If $f(x)=\ln(x)$ and $g(x) = cx^4$ has exactly $1$ solution, then we have a condition of tangency at their common point.
So $$\displaystyle \left[f'(x)\right]_{(x_{1},y_{1})} = \frac{1}{x_{1}}$$ and $$\displaystyle \left[g'(x)\right]_{(x_{1},y_{1})} = 4cx^3_{1}$$
Note at $P(x_{1},y_{1})$ these slopes are equal
So $$\displaystyle \left[f'(x)\right]_{(x_{1},y_{1})} = \left[g'(x)\right]_{(x_{1},y_{1})}\Rightarrow \frac{1}{x_{1}} = 4cx^3_{1}\Rightarrow x^4_{1} = \frac{1}{4c}$$
Now point $P(x_{1},y_{1})$ also lies on $f(x)$ and $g(x)$
So $$\displaystyle \ln(x_{1}) = cx^4_{1} = c\cdot \frac{1}{4c} = \frac{1}{4}$$
So we get $$\displaystyle \ln(x_{1}) = \frac{1}{4}\Rightarrow x_{1} = e^{\frac{1}{4}}$$
So put $\displaystyle x = \frac{1}{4}$ into $\ln(x_{1}) = cx^4_{1}\;,$ and we get $\displaystyle \frac{1}{4} = c\cdot e \displaystyle \Rightarrow c = \frac{1}{4e}$
Note that for all $c\le0\;,$ these two curves intersect each other at exactly one point, but we're only interested in values of $c$ for which $c>0$.
So our final solution is $\displaystyle c = \left\{\frac{1}{4e}\right\}$
Comment: $\ln(x) = 0\Rightarrow x = e^{0} = 1$ and $\displaystyle c= \frac{1}{2e}$
Comment: Put $x=1$ in $\ln(x)$
Comment: Oops, right. Fortunately the problem has excluded non-positive solutions for $c$. XD
Comment: Sorry HZ I have edited by solution, You are Right, Ans $\displaystyle  = \frac{1}{4e}$
Comment: Why must the slopes be equal at the intersection point? I ask since it is not guaranteed that two intersecting curves will have a common tangent line. Intersecting lines is an easy counter example. So why can we assume that the two curves in this problem will share a tangent line?
Comment: Call the functions $f$ and $g$. I think it is because in the case that they only intersect once, we have that $f \geq g$, so $d(f,g) = f - g.$ Then, the minimum of this is at the point of intersection, $x_0$, so $\frac{d}{dx}d(f,g)(x_0) = 0 \iff f'(x_0) = g'(x_0)$
Answer: Hint: Let $x = k$ be the unique place at which both curves intersect. Then we also know that both curves have a common tangent line at this point (try sketching a few example curves to see why), so we can equate derivatives. Thus, we must solve the following system of equations (assuming $\log$ refers to the natural log $\ln$):
\begin{cases}
\ln k = ck^4 \\
\dfrac{1}{k} = 4ck^3
\end{cases}
Answer: There will be precisely one real root if and only if $c\leq 0$ or $c={1\over 4e}$. The details are below.
If $c\leq 0$, then the derivative ${1\over x}-4cx^3$ is strictly positive in $(x,\infty)$, and since the function $\log (x)-cx^4$ tends to $-\infty$ as $x\to 0$ (from the right) and tends to $+\infty$ as $x\to\infty$, you get that there is one real root, by continuity, and it is unique, because the function is strictly increasing.
If $c > 0$, the the derivative ${1\over x}-4cx^3$ has precisely one real root, (check this), and the function tends to $-\infty$ at both extremes, so the only way it will have a unique root is when the $x$ axis is tangent to the graph, i.e. when both the function and it's derivative are zero. Solving the equations gives $c={1\over 4e}$.
Added in proof: I did not notice that you originally asked for only the positive cases of $c$. This leaves you only with $c={1\over 4e}$.
Answer: Solution in terms of
Lambert W function:
\begin{align}
\log(x)&=cx^4,
\\
x^{-4}\log(x^{-4})&=-4c,
\\
\log(x^{-4})&=\mathop{W}(-4c),
\\
x&=\exp\left(-\tfrac14\mathop{W}(-4c)\right).
\end{align}
For $c>0$ there is only one point $t=-\exp(-1)$,
where the two real branches
$\mathop{W_0}(t)$ and $\mathop{W_{-1}(t)}$ met,
so the answer is $c=\tfrac14\exp(-1)$.
Comment: How did you arrive at the 3rd equation?
Comment: @H.Z. Hint: $x^{-4}\log(x^{-4})=\log(x^{-4})\exp(\log(x^{-4}))$.
Answer: One may use a slightly geometric argument for this problem. Notice that $\ln(x)=cx^4$ when $f(x)=cx^4-\ln x=0$. Now, $f$ has a vertex, and the vertex occurs where $f'(x)=4cx^3-\frac{1}{x}=0$. Thus, we have the system of equations
\begin{align}
f(x)&=cx^4-\ln x=0\\
f'(x)&=4cx^3-\frac{1}{x}=0.
\end{align}
Solve the second equation for $x^4$ to get $x^4=\frac{1}{4c}$. Substitute this into the first equation to get $\ln x = \frac{1}{4}$, which implies $x=e^{1/4}$. Finally, substitute this equation for $x$ into $\frac{1}{4}=\ln x=cx^4$ to find that $c=\frac{1}{4e}$.


Android MediaStore query MediaStore.MediaColumns.TITLE column is null for some files

Question: I'm making a query on the Android's MediaStore Files Database -MediaStore.Files.getContentUri("external") - and, for some specific folders, both the MediaStore.MediaColumns.TITLE, and MediaStore.MediaColumns.DISPLAY_NAME are null while for other folders this value exists.
I couldn't find any documentation about MediaStore.MediaColumns.TITLE being possibly null.
This happens for a few internal Android directories, such as these:
_data: /storage/emulated/0/Music, title: null, _display_name: null
_data: /storage/emulated/0/Notifications, title: null, _display_name: null
_data: /storage/emulated/0/Pictures, title: null, _display_name: null

However, for some other folders, the title is there:
 _data: /storage/emulated/0/Android, title: Android, _display_name: null
 _data: /storage/emulated/0/DCIM, title: DCIM, _display_name: null
 _data: /storage/emulated/0/Download, title: Download, _display_name: null

All data comes directly from the MediaStore query.
I am aware I could work directly with the Data but I'm trying to sort the query according to the TITLE, which leads to incorrect results given that some are null.
Is this an expected behaviour? How to deal with it and retrieve all files correctly sorted by title?
Comment: I'm wondering if this should be the way go to: http://stackoverflow.com/questions/8187828/sql-order-by-using-a-substring-within-a-specific-column-possible
Comment: You are getting null title or display name ?
Comment: @HirenPatel when it is null, it is null for both title and display name. Only data field is filled.
Comment: are you working for only audio files or all types of files ?
Comment: @HirenPatel files of all types. `MediaStore.Files.getContentUri("external");`
Answer: Looks like this is an android limitation.
You could always try to do a order by such as this:
select substr(
    substr(substr(MediaStore.MediaColumns.DATA, instr(MediaStore.MediaColumns.DATA, '/') + 1), instr(substr(MediaStore.MediaColumns.DATA, instr(MediaStore.MediaColumns.DATA, '/') + 1), '/') + 1),
    instr(substr(substr(MediaStore.MediaColumns.DATA, instr(MediaStore.MediaColumns.DATA, '/') + 1), instr(substr(MediaStore.MediaColumns.DATA, instr(MediaStore.MediaColumns.DATA, '/') + 1), '/') + 1), '/') + 1
    ) from tablename;

Note that this is not recursive, but only works for up to 3 '/'.
This could be done recursively but it was only introduced later on Android


Como imprimir valores desse tipo de array

Question: Este e o xml usado para gera o array
 <?xml version="1.0" encoding="utf-8"?>
    <integracao>
        <status>2</status>
        <resposta>
            <paginacao>
                <totalItens>2</totalItens>
                <paginaAtual>1</paginaAtual>
                <registrosPorPagina>10</registrosPorPagina>
                <ultimaPagina>1</ultimaPagina>
            </paginacao>
            <historico>
                <registro>
                    <transacao>19569951</transacao>
                    <email></email>
                    <valor>2000</valor>
                    <dataEmissao>2014-09-02T12:09:14</dataEmissao>
                    <status>aguardando</status>
                    <codigoStatus>1</codigoStatus>
                </registro>
                <registro>
                    <transacao>19561474</transacao>
                    <email></email>
                    <valor>2000</valor>
                    <dataEmissao>2014-09-01T01:09:20</dataEmissao>
                    <status>aguardando</status>
                    <codigoStatus>1</codigoStatus>
                </registro>
            </historico>
        </resposta>
    </integracao>

Saída:
SimpleXMLElement Object
(
    [status] => 2
    [resposta] => SimpleXMLElement Object
        (
            [paginacao] => SimpleXMLElement Object
                (
                    [totalItens] => 4
                    [paginaAtual] => 1
                    [registrosPorPagina] => 10
                    [ultimaPagina] => 1
                )

            [historico] => SimpleXMLElement Object
                (
                    [registro] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [transacao] => 19605633
                                    [email] => email@example.com
                                    [valor] => 500
                                    [dataEmissao] => 2014-09-04T01:09:25
                                    [status] => aguardando
                                    [codigoStatus] => 1
                                )

                            [1] => SimpleXMLElement Object
                                (
                                    [transacao] => 19605619
                                    [email] => email_cliente
                                    [valor] => 500
                                    [dataEmissao] => 2014-09-04T01:09:14
                                    [status] => cancelado
                                    [codigoStatus] => 8
                                )

                            [2] => SimpleXMLElement Object
                                (
                                    [transacao] => 19569951
                                    [email] => SimpleXMLElement Object
                                        (
                                        )

                                    [valor] => 2000
                                    [dataEmissao] => 2014-09-02T12:09:14
                                    [status] => aguardando
                                    [codigoStatus] => 1
                                )

                            [3] => SimpleXMLElement Object
                                (
                                    [transacao] => 19561474
                                    [email] => SimpleXMLElement Object
                                        (
                                        )

                                    [valor] => 2000
                                    [dataEmissao] => 2014-09-01T01:09:20
                                    [status] => aguardando
                                    [codigoStatus] => 1
                                )

                        )

                )

        )

)

Answer: Isso não é um array, é um objeto SimpleXMLElement o qual pode ser iterado tal qual um array, mas não através da mesma notação de colchetes que um.
Como não tenho o mesmo XML que você para lhe oferecer uma solução 100% precisa, experimente algo como:
echo $sxml -> status; // Deve retornar 2

Se precisar dos dados da entrada resposta, use como argumento de um foreach:
foreach( $sxml -> resposta as $nodes ) {

    // Use $nodes -> paginacao
}

Se, porventura, você realmente fizer questão de trabalhar com esses dados como um array, você pode converter esse objeto SimpleXMLElement para um array com uma função-zinha bem bacana:
function map( $param ) {

    if( is_object( $param ) ) {
        $param = get_object_vars( $param );
    }

    if( is_array( $param ) ) {
        return array_map( __FUNCTION__, $param );
    }

    return $param;
}

$array = map( $sxml );

Sendo $sxml a variável com o objeto SimpleXMLElement.
Mas isso não é nenhum pouco recomendável porque você passa a não ter mais acesso aos recursos da SimpleXML e nem pode, caso venha a ser necessário, importar o objeto em questão para a DOM que oferece uma gama de recursos muito maior para se trabalhar.
Comment: adicionei o aquivo xml no post
Comment: Eu chutei a sintaxe, mas é bem isso mesmo.
Comment: e como que faz para usar esta segunda função?
Comment: Ooops, faltou isso né? Vou adicionar, mas é como qualquer outra função. ;)


Prove that function has a saddle point

Question: The following was a question on a recent analysis exam I took. We had to make this without a CAS.

Prove that
  $$f(x,y)=\sin(x^2-y^2)-(x^2-y^2)\cos(x^2+y^2)-\dfrac{(x^2-y^2)y^4}{3} $$
  has a saddle point in $(0,0)$.

The Hessian test is indecisive: according to Wolfram Alpha it has a zero on the diagonal.
So I try to find two curves, on one of which $f$ has a local maximum and on one of which $f$ has a local minimum.
It is pretty easy to prove that $g(x):=f(x,0)=\sin(x^2)-x^2\cos(x^2)$ has a local minimum in $x=0$. Indeed, $g'(x)=2x^3 \sin(x^2)$ and for $0<|x|<\sqrt{\pi/2}$, we have $\sin(x^2)>0$, so $g'$ changes sign from $-$ to $+$ in $x=0$. Hence, $f$ has a local minimum in $(0,0)$ along $y=0$.
After some playing in Desmos, I found that
$$h(x):=f(x,2x)=-\sin(3x^2)+3x^2\cos(5x^2)+16x^6$$
has a local maximum in $x=0$. Hence, $f$ apparently has a local maximum in $(0,0)$ along the line $y=2x$.
However, I can't prove this by hand from the expression for the derivative: $h'(x)=-6x\cos(3x^2) +6x\cos(5x^2)-30x^3 \sin(5x^2)+96x^5$. Also, I would have never been able to come up with this on the exam.
Is there any slick way to prove $f$ has a saddle point in $(0,0)$ by hand? Any help is appreciated!
Comment: the idea is to consider higher order taylor expansions of your function, and investigate the resulting polynomial. I'll try to elaborate more when I have time
Comment: What is Hessian at $x=y=0$?
Comment: I have read it, but note that having $0$ on diagonal does not mean that the Hessian matrix is indecisive. Note $f(x,y)=xy$ for example.
Comment: What I mean by indecisive is that we can't conclude anything from it. If all the eigenvalues are positive, we have a local minimum, if all the eigenvalues are negative a local maximum and if one eigenvalue is positive and the other one is negative we have a saddle point. Here, one is zero so we can't say deduce anything from the Hessian matrix.
Answer: Before addressing your actual question, let me briefly outline how the various derivative tests are proven in the single variable case. Suppose $f: \Bbb{R} \to \Bbb{R}$ is $C^{\infty}$; then, we look for the first non-zero derivative of $f$ (assuming that not all derivatives are zero). So, suppose $f^{(k)}(a) \neq 0$ ($k \geq 2$), while $f'(a) = \dots = f^{(k-1)}(a) = 0$. Then, by Taylor's theorem,
\begin{align}
f(\xi) - f(a) &= \dfrac{f^{(k)}(a)}{k!} (\xi - a)^k + \mathcal{O}(|\xi - a|^{k+1}).
\end{align}
In other words, to study the local behaviour of $f$ near the point $a$, since the error term is small (in the big OH sense I wrote above), all we need to do is study the properties of the $k^{th}$ order polynomial $\dfrac{f^{(k)}(a)}{k!}(\xi - a)^k$. Thus, we get a simple sufficient condition for determining the type of critical point:

If $k$ is even and $f^{(k)}(a) > 0$ then $f$ has a local minimum at $a$.
If $k$ is even and $f^{(k)}(a) < 0$ then $f$ has a local maximum at $a$.
If $k$ is odd then $f$ has a saddle point (increases in one direction, decreases in the other) at $a$.

To see this, just sketch the graph of that polynomial; it will be almost obvious. In the multivariable case, there is a similar statement, but because of the higher number of possibilities, the statement is not as exhaustive.

So, for your given function, simply calculate the first few terms in the truncated Taylor polynomial:
\begin{align}
f(x,y) &= \left[(x^2 - y^2) - \dfrac{(x^2 - y^2)^3}{3!} + \mathcal{O}((x^2 - y^2)^5) \right]\\
&- (x^2 - y^2)\left[1 - \dfrac{(x^2 + y^2)^2}{2!} + \mathcal{O}((x^2 + y^2)^4) \right]\\
&- \dfrac{(x^2 - y^2)y^4}{3} \\
&= \dots \\
&= \dfrac{(x^2 - y^2)x^2(x^2 + 4y^2)}{3} + \mathcal{O}\left( \lVert(x,y) \rVert^{10}\right)
\end{align}
So, if we plug in $y=0$, we find that
\begin{align}
f(x,0) &= \dfrac{x^6}{3} + \mathcal{O}(|x|^{10})
\end{align}
which implies $0$ is a local minimum for this single variable function. If we now plug in $y = 2x$, then
\begin{align}
f(x,2x) &= -17 x^6 + \mathcal{O}(|x|^{10}),
\end{align}
which has a local maximum at the origin. Since by restricting the function $f$ to two different paths gave two different types of extrema, it follows that the origin is a saddle point for $f$.
Comment: This is answer is very well written and helpful, thanks!! There is just a small typo, in the Taylor expansion for $f$, the first $+$ on the second line should be a $-$.
Comment: @rae306 Thanks for spotting that. I was also missing the constant term $f(a)$ in the Taylor expansion lol

Prove that function has a saddle point


Apache creates lots of processes in CLOSE_WAIT state and than crashes

Question: I have a web server (centos) with Apache 2.4.3 and in peak times Apache becomes unresponsive until I restart it.
Before it happens there is suddenly spike of httpd proccesses count and it seems that the problem is that there are many httpd processes in CLOSE_WAIT state.
<code>netstat -tanp | grep ':80 ' | grep httpd | awk '{print $6}' | sort | uniq -c | sort -n
      1 LISTEN
    255 ESTABLISHED
    553 CLOSE_WAIT
</code>
Do you have any idea how to solve this issue?
Answer: Your server probably reached its MaxClients limit.
This means that you have more than 255 simultaneous clients connect to your server.
The first obvious thing you can do is disable KeepAlives.
Then if you really need more worker processes you will have to change the mpm from prefork to worker, but this will not work with php.
Comment: Better would be to just increase the MaxClients variable in your config. But be cautious, a too high number might crash your server, because of an out-of-memory error. Read this good tutorial -> https://cloudfaqs.wordpress.com/2013/11/17/how-to-set-maxclients-in-apacheprefork/