How to calculate the critical chi-square value using Python

Question: I know that there's a function called chi2.isf in scipy.stats. So we can calculate the critical chi-square by calling this function with writing degree of freedom and significance level parameters.
Example:
from scipy.stats import chi2

print(chi2.isf(df=15, q=0.05))

Output:
24.99579013972863

However I want to calculate the critical chi-square value that was described in the below website.
Source: https://www.danielsoper.com/statcalc/formulas.aspx?id=12
While I was trying to convert the formulas into Python codes, I wrote codes like below:
from numpy import e, inf
from scipy.integrate import quad

def lower_incomplete_gamma_function(s: float = .0, x: float = .0):
    return quad(lambda t: (t ** (s - 1)) * (e ** (-t)), 0, x)[0]

def gamma_function(z: float = .0):
    return quad(lambda t: (t ** (z - 1)) * (e ** (-t)), 0, inf)[0]

What I wonder is, how can I convert the F(x; k) into Python codes and then can find the critical chi-square value? What is the step I should follow after the last step? Can you help me please?
Thanks in advance.
Answer: The thing is that actually this is not a chi2.isf code. Referencing the documentation of scipy, isf is an inverted version of sf and can be expressed as ppf(1-alpha), which for it's part is an inverted cdf function. cdf can be considered as lower gamma, whereas in scipy the lower gamma already contains the division by gamma, so your output looks rather like cdf up to 14th digit.
Hence, in order to compute the critical chi-squared value you should use the inverted lower incomplete gamma function, like that:
isf = 2 * scipy.special.gammaincinv(k/2, 1-x).


Include initial price in commerce-order-receipt.html.twig

Question: I have drupal 8 and commerce installed. The receipt email that is sent to the customers includes the final price of the product (with the promotion integrated). Is it possible to print the price of the product without the discount? I tried {{order_item.getUnitPrice}} but I still get the price with the discount:
I paste below my template:
    {#
/**
 * @file
 * Template for the order receipt.
 *
 * Available variables:
 * - order_entity: The order entity.
 * - billing_information: The billing information.
 * - shipping_information: The shipping information.
 * - payment_method: The payment method.
 * - totals: An array of order totals values with the following keys:
 *   - subtotal: The order subtotal price.
 *   - adjustments: An array of adjustment totals:
 *     - type: The adjustment type.
 *     - label: The adjustment label.
 *     - total: The adjustment total price.
 *     - weight: The adjustment weight, taken from the adjustment type.
 *   - total: The order total price.
 *
 * @ingroup themeable
 */
#}

{{ 'Order #@number details:'|t({'@number': order_entity.getOrderNumber}) }}

Ευχαριστούμε! Η παραγγελία σας καταχωρήθηκε επιτυχώς.

Στοιχεία παραγγελίας:

                                    Έκδοση
                                    Ποσότητα
                                    Σύνολο

                                {% for order_item in order_entity.getItems %}

                                            {{ order_item.label }}

                                        x {{ order_item.getQuantity|number_format }}

                                            {{ order_item.getTotalPrice|commerce_price_format }} {{order_item.getUnitPrice}}

                                    {% endfor %}

                                    Αξία
                                    {{ totals.total|commerce_price_format }}

                                    {% for adjustment in totals.adjustments %}

                                            {{ adjustment.label }}

                                            {{ adjustment.total|commerce_price_format }}

                                        {% endfor %}

                                     Σύνολο:
                                    {{order_entity.getTotalPrice|commerce_price_format}}

                                    {{ 'Billing Information'|t }}
                                    {{ 'Shipping Information'|t }}

                                {% if billing_information %}
                                 {% block billing_information %}
                                {{ billing_information }}
                                {% endblock %}
                               {% endif %}

                            {% if shipping_information %}
                                {% block shipping_information %}
                                {{ shipping_information }}
                                {% endblock %}
                         {% endif %}

                     {{ 'Selected Payment Method'|t }}

                    {# {{ 'Selected Shipping information'|t }}	 #}

                        {% if payment_method %}

                    {% block payment_method %}
                      {{ payment_method }}
                    {% endblock %}
                    {% endif %}

                  {#
                    {% if shipping_information %}

                                {% block shipping_information_2 %}
                                {{ shipping_information }}
                                {% endblock %}
                         {% endif %}
                  	 #}

ΙΔΡΥΜΑ ΤΗΣ ΒΟΥΛΗΣ ΤΩΝ ΕΛΛΗΝΩΝ

Answer: You could get the promotion value and add it back.
{% set promotions = order_item.getAdjustments(['promotion']) %}

{# assuming there is always one promotion, otherwise you'll want to loop here #}
{% set promotion_amount = promotions.0.getAmount.getNumber %}

{# since promotion is a negative number we have to substract to add back #}
{% set original_price = order_item.getUnitPrice - promotion_amount %}
{{ original_price }}

Comment: Thank you, perfect solution!


Proof for x/log(x)~ Li(x)

Question: Could anyone please show the steps for proving $\frac{x}{log(x)}$~ Li(x) or at least point to a source. Where ~ is the asymptotic equivalence. Any help would be appreciated.
Comment: $$Li(x) = \int_2^x \frac{dt}{\log t} \sim \int_2^x \frac{dt}{\log x} = \frac{x-2}{\log x}$$
Answer: $\lim_{x\to \infty } \, \dfrac{\frac{x}{\log x}}{\text{Li}(x)}=1$
Use L'Hopital rule
$$\lim_{x\to \infty } \, \frac{\frac{1}{\log (x)}-\frac{1}{\log ^2(x)}}{\frac{1}{\log (x)}}=\lim_{x\to \infty } \, \left(1-\frac{1}{\log (x)}\right)=1$$
Hope this helps
Answer: Repeated integration by parts gives an asymptotic expansion:
$$\newcommand{\Li}{\operatorname{Li}}
\begin{align}
\Li(x)
&=\int_2^x\frac{\mathrm{d}t}{\log(t)}\\
&=\frac{x}{\log(x)}\left(1+\frac{1}{\log(x)}+\frac{2}{\log(x)^2}+\dots+\frac{k!}{\log(x)^k}+O\left(\frac{1}{\log(x)^{k+1}}\right)\right)
\end{align}
$$
Note that the constants introduced by the integration by parts are included in the $O\!\left(\frac{x}{\log(x)^{k+2}}\right)$ term, which grows faster than the sum of those constants.
Comment: Would the downvoter care to comment? I see that the one answer not downvoted today mentions the constants arising from the lower limit of integration; however, those constants are included in $O\!\left(\frac{x}{\log(k)^{k+2}}\right)$ which dominates any constant.
Answer: I am not entirely convinced that all conditions for using L'Hôpital's rule are met in the accepted answer from @Raffaele. Therefore I would like to share a proof from Peter Bundschuh's book "Einführung in die Zahlentheorie", page 295. It uses integration by parts:
$$
\newcommand{\Li}{\operatorname{Li}}
\Li x - \Li 2 = \int_2^x 1 \cdot \frac{1}{\log t} \, \mathrm{d}t = \frac{x}{\log x} - \frac{2}{\log 2} + \int_2^x \frac{\mathrm{d}t}{\log^2 t}
$$
$$
\Rightarrow | \Li x - \frac{x}{\log x} | \leq \int_\sqrt{x}^{x} \frac{\mathrm{d}t}{\log^2 t} + \mathcal{O}(\sqrt{x}) = \mathcal{O} \left( \frac{x}{\log^2 x} \right)
$$
Comment: What conditions for L'Hôpital are not met? Both numerator and denominator go to $\infty$. The limit of the ratio of the derivatives exists. You are free to share an answer without anything being wrong with other answers. Your answer matches mine with $k=0$.

Proof for x/log(x)~ Li(x)


Hierarchical Bayesian Model (?)

Question: Please apologize my butchering of statistical lingo :) I have found a couple of questions on here that are related to advertising and click through rates. But none of them helped me very much with my understanding of my hierarchical situation.
There's a related question Are these equivalent representations of the same hierarchical Bayesian model?, but I'm not sure if they actually have a similar problem. Another question Priors for hierarchial Bayesian binomial model goes into detail about hyperpriors, but I'm not able to map their solution to my problem
I have a couple of ads online for a new product. I let the ads run for a couple of days. At that point enough people have clicked on the ads to see which one gets the most clicks. After kicking out all but the one that has the most clicks I let that one run for another couple of days to see how much people actually purchase after clicking on the ad. At that point I know if it was a good idea to run the ads in the first place.
My statistics are very noisy because I don't have a lot of data since I'm only selling a couple of items every day. Therefore it is really hard to estimate how many people buy something after seeing an ad. Only about one in every 150 clicks results in a purchase.
Generally speaking I need to know if I'm losing money on each ad as soon as possible by somehow smoothing the per-ad group statistics with global statistics over all ads.

If I wait until every ad has seen enough purchases I'll go broke because it takes too long: testing 10 ads I need to spend 10 times more money so that the statistics for each ad gets reliable enough. By that time I might have lost money.
If I average purchases over all of the ads I won't be able to kick out ads that just aren't working as well.

Could I use the global purchase rate ($ per click) and use it as a prior for $N$ sub-distributions? That would mean that the more data I have for each ad, the more independent the statistics for that ad get. If nobody has clicked on an ad yet, I assume that the global average is appropriate.
Which distribution would I choose for that?
If I have had 20 clicks on A and 4 clicks on B, how can I model that? So far I have figured out that a binomial or Poisson distribution might make sense here:

purchase_rate ~ poisson (?)
(purchase_rate | group A) ~ poisson (estimate the purchase rate only for the group A?)

But what do I do next to actually calculate the purchase_rate | group A. How do I plug two distributions together to make sense for group A (or any other group).
Do I have to fit a model first? I have data that I could use to "train" a model:

Ad A: 352 clicks, 5 purchases
Ad B: 15 clicks, 0 purchases
Ad C: 3519 clicks, 130 purchases

I'm looking for a way to estimate the probability of any one of the groups. If a group has only a couple of datapoints I essentially want to fall back to the global average. I know a bit about Bayesian statistics and have read a lot of PDFs of people describing how they model using Bayesian inference and conjugate priors and so on. I think there is a way to do this properly but I can't figure out how to model it correctly.
I would be super happy about hints that help me formulate my problem in a Bayesian way. That would help a lot with finding examples online that I could use to actually implement this.
Update:
Thanks so much for responding. I'm beginning to understand more and more little bits about my problem. Thank you! Let me ask a few questions to see if I understand the problem a bit better now:
So I assume the conversions are are distributed as Beta-distributions, and a Beta distribution has two parameters, $a$ and $b$.
The $\frac{1}{2}$ $\frac{1}{2}$ parameters are hyperparameters, so they are parameters to the prior? So in the end I set the number of conversions and number of clicks as the parameter of my Beta distribution?
At some point when I want to compare different ads, so I would compute $P(\mathrm{conversion} | \mathrm{ad}=X) = \frac{P(\mathrm{ad}=X | \mathrm{conversion}) * P(\mathrm{conversion})}{P(\mathrm{ad}=X)}$. How do I compute each part of that formula?

I think $P(\mathrm{ad}=X | \mathrm{conversion})$ is called likelihood, or "mode" of the Beta distribution. So that's $\frac{\alpha - 1}{\alpha + \beta - 2}$, with $\alpha$ and $\beta$ being the parameters of my distribution. But the specific $\alpha$ and $\beta$ here are the parameters for the distribution just for the ad $X$, right? In that case, is it just the number of clicks and conversions this ad has seen? Or is how many clicks/conversions all ads have seen?
Then I multiply with the prior, which is P(conversion), which is in my case just the Jeffreys prior, which is non-informative. Will the prior stay the same as I get more data?
I divide by $P(\mathrm{ad})$, which is the marginal likelihood, so I count how often this ad has been clicked?

In using Jeffreys' prior, I'm assuming that I'm starting at zero and don't know anything about my data. That prior is called "non-informative". As I continue learning about my data, do I update the prior?
As clicks and conversions come in, I have read that I have to "update" my distribution. Does this mean, that the parameters of my distribution changes, or that the prior changes? When I get a click for ad X, do I update more than one distribution? More than one prior?
Answer: As you intuited, a very general way of addressing your question is to construct a hierarchical (multilevel) Bayesian model. The model has three parts, as illustrated below.
Model

At the population level, we model the conversion probability in the population of ads from which your particular set of tested ads is sampled. One could fix the population parameters and use them as a prior for the second level, as was noted before by Neil. Alternatively, we could place a prior on the population parameters themselves, which provides the additional advantage that we can now express our uncertainty about the population parameters in light of the data. Let's follow this route and place a prior $\mathcal{N}(\mu \mid \mu_0, \eta_0)$ on the population mean $\mu$ and $\textrm{Ga}(\lambda \mid a_0, b_0)$ on the population precision (i.e., inverse variance). A diffuse prior can be obtained using $\mu_0 = 0, \eta_0 = 0.1, a_0 = 1, b_0 = 1$, which ensures our posterior inferences will be dominated by the data.

At the level of individual ads, we can model the conversion probability $\pi_j$ of a given ad $j$ as logit-normally distributed. Thus, for each ad $j$, the logit conversion probability $\rho_j := \textrm{logit}(\pi_j)$ is modelled as $\mathcal{N}(\rho_j \mid \mu,\lambda)$.

Finally, at the level of observed data, we model the number of conversions $k_j$ for ad $j$ as $\textrm{Bin}(k_j \mid \sigma(\rho_j), n_j)$, where $\sigma(\rho_j)$ uses the sigmoid transform to translate a logit rate back into a probability, and where $n_j$ is the number of clicks on ad $j$.

Data
As an example, let's take the data you posted in your original question,

Ad A: 352 clicks, 5 purchases
Ad B: 15 clicks, 0 purchases
Ad C: 3519 clicks, 130 purchases

which we translate into: $n_1 = 352, k_1 = 5, n_2 = 15, k_2 = 0, \ldots$
Inference
Inverting this model means to obtain posterior distributions for our model parameters. Here, I used a variational Bayes approach to model inversion, which is computationally more efficient than stochastic sampling schemes such as MCMC. I have plotted the results below.

The figure shows three panels. (a) A simple visualization of the example data you provided. The grey bars represent the number of clicks, the black bars show the number of conversions. (b) The resulting posterior distribution over the population mean conversion rate. As we observe more data, this will become more and more precise. (c) Central 95% posterior probability intervals (or credible intervals) of the ad-specific posterior conversion rates.
The last panel illustrates two key features of a Bayesian approach to hierarchical modelling. First, the precision of the posteriors reflects the number of underlying data points. For example, we have relatively many data points for ad C; thus, its posterior is much more precise than the posteriors of the other ads.
Second, ad-specific inferences are informed by knowledge about the population. In other words, ad-specific posteriors are based on data from the entire group, an effect known as shrinking to the population. For example, the posterior mode (black circle) of ad A is much higher than its empirical conversion rate (blue). This is because all other ads have higher posterior modes, and thus we can obtain a better estimate of ground truth by informing our ad-specific estimates by the group mean. The less data we have about a particular ad, the more will its posterior be influenced by data from the other ads.
All of the ideas you described in your original question are accomplished naturally in the above model, illustrating the practical utility of a fully Bayesian setting.
Comment: Hi @Zhubarb, user511005, here is a link to the paper describing the above model: http://www.sciencedirect.com/science/article/pii/S1053811913002371 I've put together a brief introduction to variational inference here: http://people.inf.ethz.ch/bkay/talks/Brodersen_2013_03_22.pdf
Comment: Kay, thank you for your detailed answer. I understand the answer is slightly dated but would you mind sharing the accompanying code if you have kept it? I am trying to learn Hierarchical Bayesian Modelling but struggling to find intuitive examples in R.
Comment: @Kay , thanks for the interesting answer, could you please add some reference to  hierarchical Bayesian models ? Thanks!
Answer: You need to estimate a probability $p$ of a "conversion" (purchase) given a click for each ad.  (It sounds like you're assuming that the probability of a conversion is the same for each click, which is reasonable.)
The Bayesian way to do this is to estimate a distribution over $p$, which is Beta and has shape parameters $a$ equal to the number of conversions plus $a'$, and $b$ equal to the number of clicks that didn't result in a conversion plus $b'$.
$a'$ and $b'$ represents your prior.  Use $(\frac12, \frac12)$ for a Jeffreys' prior.  In order to "fall back" to the global average, there are a variety of ways of setting $a', b'$ according to all of the data.
To get the estimate of $p$ out of your estimator with parameters $a, b$, you could choose the maximum likelihood value, the mode of the Beta distribution.

In answer to your edits:
The conversions are not Beta-distributed, but Bernoulli-distributed with probability $p$.  Please compare how I am setting $a$ and $b$ in paragraph 2 with what you wrote.  Note that you have a $p$ for each ad, and thus a belief over $p$ for each ad, and each of those beliefs has its own $a$ and $b$.
The Bayesian update is
$$P(p \mid x) \propto P(p)P(x \mid p)$$
where $x$ is the observation (conversion or no conversion) and $p$ is selected for the appropriate ad.
This formula is already worked into the update for $a$ and $b$, which works so that in case of a conversion you add 1 to $a$, otherwise you add 1 to $b$ — this is updating the belief of $p$.
The Jeffreys' prior is not the same thing as the uninformative prior, but I believe that it's better unless you have a good reason to use it.  Feel free to ask another question if you want to start a discussion about that.
Comment: Thanks for responding! I updated my original question because I ran out of characters in this comment box. It would be great if you could give some feedback for some of the details I wrote in the update.

Hierarchical Bayesian Model (?)


Why do lower instruments speak "slower"?

Question: Why do lower instruments, such as double bass and cello in an orchestra or chamber setting, are discerned by the ear slower than higher instruments (violin, flute, etc)? Does it have to do with the acoustic qualities of the instrument, or characteristics of the overtones of lower notes?
I've always been told, as a violist, that my instrument will speaker behind a violin playing the same line if we begin playing physically at the same time. What are the actual physical reasons behind this, if any?
Comment: This doesn't make sense. You ask why lower instruments appear to play later than higher ones, and then give an example of two instruments that are the same, playing the same line. I'm not sure what exactly you're asking here.
Comment: You've been misinformed. Lower instruments do not speak slower.
Comment: Somewhat related - https://music.stackexchange.com/a/31986/18896
Comment: @AricFowler a violist plays a viola which is lower than a violin
Comment: @IanCook oh right! I didn't notice it said violist
Answer: Phase-locking-driven instruments, including strings and winds (but not percussion or plucked strings) can be described as a primary†, linear oscillator (the string, or air column) which is coupled to a nonlinear "energy pump" (the bow or mouthpiece, respectively). It is the oscillator that defines the frequency, so the coupling must not be too strong (else you don't get proper tones but only avant-garde overpressed screeching noises etc.). Weak coupling means, the oscillator does largely what it might also do all by itself, and only changes the waveform much more slowly. Much more slowly, relative to the oscillation period, that is – and the oscillation period is obviously shorter if the pitch is higher. So in that sense, e.g. violin is indeed more naturally agile than double bass – at least bowed double bass. (This is certainly one of the reasons why fast bass work such as in Jazz is usually pizzicato.)
Good players on any instruments are actually able to substantially cheat this: they make the coupling much stronger only very briefly for the initial transient ("grabbing the string with the hair"), but this requires ever more skill as the instrument goes lower.

†In acoustic string instruments, this oscillator is also coupled to a resonator and that coupling likewise introduces some delay, but that can actually be much shorter.
Answer: It takes more energy to get a large instrument resonating than a small one.  I'm dubious about the strings example - we hear the 'bite' of the bow on the string as an immediate transient, even if it does take a little time for the body to fully resonate.  I'm sure there's some truth in what the viola player has been told though, maybe more applicable to legato passages.
But it's certainly true for the larger brass instruments.  The vibration applied at the mouthpiece of a tuba has to kick a 5m air column into vibration.  (It's about setting up a wave, not passage of air. Not THAT much air actually travels through the instrument.)  So the player compensates by playing a bit early.  It's not particularly calculated, he just knows what to do in order to hear the note at the right time.
Comment: @BrianTHOMAS  10 ms  is perceptible rather easily (by the human ear).
Comment: It's even more pronounced with organ pipes. Low pitch 64' pipes can speak as much as a half second later than a high 2' pipe. There's more air to move within the pipe.
Comment: At 343 m/s, sound takes 10ms to travel 5m through a tuba. Not an appreciable delay.
Comment: @ttw it depends very much how the pipes are voiced. You can quite easily change the initial attack for a single pipe speaking middle C from "near enough instantaneous" to "half a second to get going properly" if you want to. 64-ft stops are never going to be used on their own, so a bit of delay doesn't matter. (It does matter for 16-ft stops, but that is fixable by voicing).
Comment: @ttw Just to be clear: the total volume of air hardly moves at all, and does so slowly.  The pressure wave moves at the speed of sound (duh :-) ) .
Comment: And there's not really a pressure wave either.  More a standing wave, vibrating at one of the resonant modes of that particular length of enclosed air column.  I've edited my answer to be more clear.
Comment: Is this also the reason why fast scale playing seems (to me) less clear in some bass instruments?
Comment: I looked up chorus and flanging and phasing and so on, and apparently the human ear cannot distinguish two events occurring less than 10ms apart.
Answer: There is a difference between percussive and continuous-tone instruments: percussive instruments (like a piano or a plucked bass or even a bass drum or its more defined cousin kettle drum) start with a rather prominent part of the vibration while continuous-tone instruments have to build up the the energy of their sustained operation first.  So bass recorders and wind pipes (organ) are among those with the slowest attack.  Reed instruments like bassoons are faster starters.
However, many instruments with a comparatively poignant primary oscillator then feed some resonator, and a resonator still needs to pump up its energy over several oscillations before being in full swing, and in order to resonate, its operation already includes a mechanical delay for one cycle time that retains a significant amount of energy.
So there is a basic slowness for the development of the actual sound.  There also is a basic time/frequency unsharpness relation that limits how fast pitch differences can be determined: this is a mathematical rather than a physical limit.  And finally the detection in the inner ear again works with a semi-resonant contraption relying on a delay line introducing some frequency-related delay to reliable detection.
This is ameliorated somewhat by the listener not making sense of his hearing in real-time but with some delay of perception that allows reconciling faster and slower detected features.
This particularly helps with percussive instruments where a poignant attack gives a good location in time and the associated pitch can be determined only later.  Trills, coloratura, tonally specific fast runs and phrases are still usually not working well for the listener in the lower ranges of bass instruments.
Comment: It's worth noting that the initial transient is often mainly noise, so the pitched element could indeed take longer to percieve even if the overall sound didn't.
Comment: Could it also be that human ears will pick up higher pitched sounds sooner, too? And here, we're considering *only* the attack portion of a sound.


Usar tabela do Banco de Dados, ao invés de tabela criada ao usar Autenticação Individual com Identity

Question: Eu criei uma aplicação em Asp.net MVC usando Identity e deixei marcada a opção para o Visual Studio criar a autenticação de usuários individuais para mim. Acontece que eu só descobri que ele cria um arquivo .mdf que contém um banco de dados e tabelas para armazenar registros de usuários. Eu não sabia disso e acabei criando uma outra tabela para o meu sistema com as regras de negócio e etc. Quando eu coloquei a aplicação no servidor, logicamente, esse arquivo .mdf com o banco de dados e suas tabelas não foram e aí eu não pude usar a autenticação. Daí eu até agora vi que tenho algumas opções:
1 - Criar as mesmas tabelas que exatamente iguais no BD que eu já uso no SQL Server e usar a conexão de "DefaultConnection" para a conexão que estou usando do Entity. Para esta opção, está dando erro na minha aplicação ao tentar criar usuário ou logar (já que coloquei usuários manualmente no BD):
<code>Detalhes da Exceção: System.InvalidOperationException: The entity type ApplicationUser is not part of the model for the current context.

Erro de Origem:

Linha 74:             // Isso não conta falhas de login em relação ao bloqueio de conta
Linha 75:             // Para permitir que falhas de senha acionem o bloqueio da conta, altere para shouldLockout: true
Linha 76:             var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
Linha 77:             switch (result)
Linha 78:             {

Arquivo de Origem: c:\Users\sydvagner.franco\Documents\Visual Studio 2013\Projects\LPGPonto\LPGPonto\Controllers\AccountController.cs    Linha: 76
</code>
2 - Tentar usar os dois banco de dados para essa aplicação. Acho meio bizarro, mas aceitaria se fosse o mais simples. Nesse caso eu migraria o BD para o SQL Server (já vi que isso é possível, mas ainda não tentei) ou colocaria o arquivo .mdf no servidor, alterando o Web.config para acessar esse arquivo no local que eu colocá-lo no servidor, ao invés de em  |DataDirectory| como vem por Default que é a pasta App_Data da aplicação (Essa pasta não aparece depois do deploy do sistema, por isso não existe o arquivo .mdf criado automaticamente para controle de autenticação).
Funcionamento do Sistema
É um sistema de Ponto Eletrônico que tem as tabelas:

DIARIA
FERIADO
FERIAS
FUNÇÃO
FUNCIONÁRIO
LOCAL
REGISTRO (que guarda o IP e a hora do registro de ponto).
AspNetRoles (peguei o script e gerei a tabela igual à criada pelo Identity)
AspNetUsers (peguei o script e gerei a tabela igual à criada pelo Identity)

Tabelas geradas no BD automaticamente para controlar autenticação do usuário

MigrationHistory
AspNetRoles
AspNetUsersLogins
AspNetUserRoles
AspNetUsers

Eu só coloquei as tabelas AspNetUsers e AspNetRoles porque achei que só vou utilizar essas.
Comment: [Naquela resposta que eu dei](http://pt.stackoverflow.com/a/16220/2999), você fez o procedimento pra gerar uma Migration e subir seu banco em um SQL Server?
Comment: Você pode colocar na sua pergunta essa definição das suas tabelas pra que eu possa ter uma ideia de como é o funcionamento desse sistema?
Comment: Exatamente Tiago Silva. O arquivo .mdf foi criado antes de eu mudar. Mas eu já alterei a connection string para usar a mesma conexão criada com o Entity para acessar o BD que eu criei.
Comment: Não fiz isso ainda Cigano, pois já uso um BD, como falei e não queria usar dois BD para uma mesma aplicação. Mas se você me disser que não tem jeito, que terei que fazer isso para dar certo, eu farei.
Comment: @TiagoSilva o meu ApplicationDbContext ficou assim:
public ApplicationDbContext()
            : base("PONTOEntities")
            //: base("DefaultConnection", throwIfV1Schema: false)
        {
        }

A parte comentada era a conexão anterior com DefaultConnection
Comment: @SydinhoFranco Faça quando puder. Você não tem vantagem alguma trabalhando com .mdf.
Comment: Então ok @CiganoMorrisonMendez eu vou fazer isso e dou um retorno.
Comment: @CiganoMorrisonMendez eu tentei fazer a migração, porém deu esse erro: "CREATE DATABASE permission denied in database 'master'." A minha connection string ficou assim: "" Mesmo passando o usuário e senha do "sa" o SQL Server não forneceu acesso para criar as tabelas?
Comment: @CiganoMorrisonMendez tudo certo. No seu tutorial o "DefaultConnection" estava com "Integrated Security=True". Eu troquei pra False e funcionou. Agora estou usando os dois BD para a mesma aplicação.
Answer: Fiz a migração (conforme mostrado aqui) do banco de dados criado automaticamente pelo Identity para controlar a autenticação de usuários no sistema para o meu servidor de BD SQL Server e agora estou usando os dois bancos de dados para a mesma aplicação. Foi o jeito que foi dado por não ter feito a migração desse banco antes e ter utilizado esse mesmo banco para os dados gerais da minha aplicação. Então, a minha dica é que sempre que alguém deixar marcada a opção para o Identity criar a autenticação para usuário, migrar esse banco de dados para o SQL Server e usar esse mesmo banco para inserir outras tabelas da aplicação, para não precisar usar 2 banco de dados para o mesmo sistema.


Is there a subset of the real plane such that every line intersects that subset exactly once?

Question: Consider the real plane $\mathbb{R}^2$. Does there exist a subset $S$ of the real plane, such that every line $l$ in $\mathbb{R}^2$ intersects $S$ at exactly one point?
Answer: No.
Given $2$ distinct points $\mathbf{x}, \mathbf{y} \in S \subseteq \mathbb{R}^2$, consider the line $\ell$ that passes through $\mathbf{x}$ and $\mathbf{y}$. So $S$ can contain at most $1$ point. Obviously, $S \neq \varnothing$, so consider the cases where $|S| = 1$. It's easy to construct a line that misses the given point.
Comment: Nice. +1. The formulation suggests the transfinite induction but it is so misleading...


Rules (not) triggered with Bulk Media Upload

Question: Rules (not) triggered with Bulk Media Upload
I have a node type called 'uploads' that includes a user reference field to make each upload particular/available to a certain user.
I have added a rule so when a new upload is added, they are e-mailed to let them know there's something new for them to see once they're logged in.
This works fine when adding uploads (nodes) one at a time, but I'm also using "Bulk Media Upload" (https://www.drupal.org/project/bulk_media_upload) to allow for multiple uploads/node creation, at which point the rules fail with the following error:
"Unable to get the data value for the variable or parameter id. Error: Unable to get the data property uid as the parent data structure is not set."
I realize that Bulk Media Upload is on/past the outs; but I do need the functionality it provides and am unsure as to why the data isn't available doing things this way when they are doing things one at a time.  The references are made the same way in either case since Bulk Media Upload uses/requires the same values.
Edit - Ok, here's the rule being used:
<code>            { "rules_results_uploaded" : {
                "LABEL" : "Results Uploaded",
                "PLUGIN" : "reaction rule",
                "OWNER" : "rules",
                "REQUIRES" : [ "rules", "php" ],
                "ON" : { "node_insert--uploads" : { "bundle" : "uploads" } },
                "DO" : [
                  { "entity_fetch" : {
                      "USING" : { "type" : "user", "id" : [ "node:field-for-user:uid" ] },
                      "PROVIDE" : { "entity_fetched" : { "entity_fetched" : "Fetched entity" } }
                    }
                  },
                  { "drupal_message" : { "message" : "Receipt of the sample on \u003C?php echo $data[\u0027components\u0027][\u0027sample_received\u0027][\u0027value\u0027][0]; ?\u003E has been acknowledged.  \r\n\r\nAn e-mail will be sent to [entity-fetched:field-practitioner-name] at [entity-fetched:mail]" } },
                  { "mail" : {
                      "to" : "[entity-fetched:mail]",
                      "subject" : "Your Sample Results Have Been Uploaded",
                      "message" : "Dear [entity-fetched:field-practitioner-name],\r\n\r\nNew sample results are now available on your account.",
                      "from" : "email@example.com",
                      "language" : [ "" ]
                    }
                  }
                ]
              }
            }
</code>
Again, the rule works fine when fine when adding a new node of the type 'uploads' one at a time, it just doesn't work using bulk media upload (though triggering multiple times.)  Perhaps I'm misunderstanding how BMU works.
Any thoughts or alternatives still much appreciated.
Comment: please edit your question to include an export of your rule
Answer: As noted, your rule is setup for serial upload operations; BMU sets the entities in a batch process, rather than one reference/file at a time.
You may be able to overcome the race condition resulting from the rule firing and batch processing by triggering the rule on node save rather than individual file uploads while editing the node.  This will ensure each file has a Drupal FID assigned and has been fully added to the files table in Drupal for referencing.


How to populate empty columns in all rows with a value from another row

Question: I have this table:
num | id | value1 | value2 | ..... | valueN
____|____|________|________|_______|_______
 1  |  1 |  val1  | val2   | ..... | valN
 2  |  1 |  blah  | NULL   | ..... | NULL
 1  |  2 | val12  | val22  | ..... | valN2
 2  |  2 | blah2  | NULL   | ..... | NULL

num and id are a primary key. Each row that has 1 num is the row that has all the columns filled, all other rows for that id (where num is higher than 1) have empty columns which I want to fill with corresponding values from columns in the num=1 with the same id.
I could write a script that runs on all num >1 rows and and then runs on every empty column and brings it from the num=1 row, but is there a more SQLy way to do it? Something more general, without iterating every column?
Answer: Well, you can try to update all rows using cross-table UPDATE JOIN
UPDATE mytbl AS a
INNER JOIN (SELECT * FROM mytbl WHERE num = 1) AS b ON a.id = b.id
SET a.value1 = b.value1,
  a.value2 = b.value2,
...
  a.valueN = b.valueN
WHERE  a.num > 1

Answer: To just update the values (and preserve them if already present) the basic query would look like this:
update Table1 t
join (select * from Table1 where num = 1) ones
on t.id = ones.id and t.num != ones.num
set
    t.value1 = IFNULL(t.value1, ones.value1),
    t.value2 = IFNULL(t.value2, ones.value2),
    t.valueN = IFNULL(t.valueN, ones.valueN);

Since it's not possible to do update tablea from tableb set a.* = b.* you will have to include all columns that you want to update in the query, and if I understand your question this is the exact situation you want to avoid.
Using dynamic sql and querying the information schema of the database it's possible to build an update statement that will update all columns (except the ones manually excluded). This method is a bit hackish but should work, however it might not perform well and it might be unsafe.
Given a test table named Table1 set up as your example you can run the following code to update all columns except id and num:
-- base update statement
SET @sql:= 'update Table1 t
join (select * from Table1 where num = 1) ones
on t.id = ones.id and t.num != ones.num
set ';

-- concatenate the base update with the column specific part
SELECT @stmnt := concat(@sql, group_concat(
  't.',
  COLUMN_NAME,
  ' = IFNULL(t.',
  COLUMN_NAME,'
  , ones.',
  COLUMN_NAME,
  ')'))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'Table1'
-- exclude these columns from the update
AND column_name != 'id'
AND column_name != 'num';

-- build a statement and execute it
PREPARE dynamic_statement FROM @stmnt;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement;


How to defense a DDoS powered by end user's browser?

Question: Like what Github.com has just experienced, what if a script provider, such as google ads, google analysis or something similar, add a malicious scripts at the end of their script, and let end users flood into the target? What if he/she forbid the target script to execute? What if he/she let the script request random path of the target domain?
How to defense such an attack?
Comment: The critical point is that the attack source are the end users which we cannot ban.
Comment: In this attack, the GFW operated in reverse, adding a malicious JavaScript to the Baidu web site, but only for visitors outside China. Most small web sites have no chance to survive an attack like this.
Comment: Actually if the GFW change the code for visitors inside China, the tremendous fluency will meanwhile trigger the GFW itself(The target page contains keywords under censorship), which . And I guess it's not that easy to perform such man-in-the-middle attacks inside China. I just found this kind of attack is so low-cost. In China there are so many cross-site scripts providers and CDN providers. It will be terrible if one of them get hijacked.
Comment: China is in bad shape anyway because so many people are still using Windows XP.
Answer: It's not easy. Basically you want to block the traffic as early as possible.
That is normally your firewalls or even earlier your ISP.
With such an attack that is usually not flexible enough as you can only block IP networks.
You can route our entire traffic to a vendor that specializes in DDoS mitigation.
They have huge bandwidth resources.
This obviously needs to be well prepared.
For some of those providers you need to be able to change BGB routes.
Those are called scrubbing centers or clean pipes providers.
They take all your traffic and filter out bad traffic, sending only "clean" traffic to your servers.
There it's a matter of creating rules of catching the attack traffic.
In the easiest case it's always the same URL that gets requested.
=> Drop repeated traffic to that single URL.
This gets more complicated when the URLs are random.
=> If an IP hits a pages that return a 404 more than X times in Y minutes, block it.
And even more complicated when the URLs are random but existing.
Then you need to detect anomaly in traffic.
You will block some of your real users if they are using infected pages that are used to DDoS you.
That's the price to pay to keep your services available to the rest of your users.
Comment: It seems to me the best place to "catch"  this  would be the user's browser. (ie don't allow more than x links to external domains / don't allow links to IP addresses )  As a "side effect" it would eliminate most of the ad and stat link infestation found in most pages.
Comment: But you have no control over 3rd party compromised sites that reload your site in a hidden iframe. You can contact them, sure. But that takes time.


Display wireless channels currently in use

Question: Is there any windows utility to display the wireless channels are currently in use by the available wireless networks?  I'd like to be able to see what existing channels are using so I can try to minimize interference on a new access point without a lot of trial and error.
Answer: inSSIDer
WirelessMon
NetStumbler
Comment: inSSIDer was even more useful than I expected, thanks.
Comment: Glad to help...
Answer: If you're in 2.4GHz, please be aware of a few things:

There are lots of non-802.11 interferers in that band, so just looking at 802.11 networks doesn't necessarily give you a good picture of the band usage. Bluetooth, Wiimotes, microwave ovens, and many cordless phones, baby monitors, wireless webcams / security cams, and wireless room-to-room A/V senders, among many other things, use the same 2.4GHz ISM band as 802.11. None of these other sources of interference would be detected by your typical Wi-Fi network scanner. One special note on cordless phones: Even if they say 5.8GHz, they may only use that in the base-to-handset direction; many such phones still use 2.4GHz in the handset-to-base direction because it requires less power thus less battery usage. Sometimes you can't tell this from the box at the store; it's not until you read the FCC regulatory information fine print at the back of the user manual that you discover this.
Anyone doing HT40 (40MHz-wide 802.11n channels) is taking up two contiguous non-overlapping channels, leaving at most 1 channel (at least in the North America / FCC 11-channel plan) unaffected. For example, if it's doing control on channel 1, channel 5 will be its extension channel, leaving only channels 10 and 11 unaffected. If they're a real jerk and using, say, channels 4 and 8, it doesn't leave any channel unaffected. If your 802.11 card is not N-capable or your WiFi network scanner app is not HT40-savvy, it might not show you this information. I believe that "Super-G" 108mbps equipment (from back before the MIMO/802.11n days) also bonded two contiguous channels together, and might not show up in your typical WiFi network scanner app as occupying both channels.
Simply seeing another network in a scan doesn't mean it will have any real effect on you. It may only mean that you can occasionally see a really weak beacon or probe response from a distant network. Or even if it's a nearby network, it may be sitting idle all the time.

If you really want to get a proper picture of your RF environment, consider getting an actual spectrum analyzer such as a MetaGeek Wi-Spy.
Comment: +1 for great points and in particular Wi-Spy - great little gadget at a fraction of the cost of most spectrum analyzers.
Answer: If you're looking for a cloud-based solution, there's a free, internet based, WiFi Stumbler.
Full Disclosure: I work for Meraki.
Comment: That is so cool!  For anyone who thinks, "How could it possibly work in a web browser?", it is running a Java applet.  Very, very nice.


Value price of Bond

Question: Hi, can you help me with this exercise ? I'm good in maths but don't understand these financial problems. I would be grateful for any help
One morning, Mr. Kowalski purchased a two-year bond with the face value of $1,000, the coupon rate qual to 10% (coupon payable at the end of each period of one year) and the average annual yield (YTM) being 12%.
Additionally he bought ten-year bond with the face value of $1,000, the coupon rate equal to 10% (coupon payable at the end of each period of one year) and the average annual yield (YTM) being 12%
It was unexpectedly announced in the afternoon that the central bank bad increased base inerest rates. Therefore, yields to maturity on the bond market increased; the average annual YTM on the bond purchased by Mr. Kowalski reached 14%. Calculate the price of the bond purchased by Kowalski and the price for which he could sell it in the afternoon (assume that transaction costs equal zero).
Answer: Answer:
YTM $=12$% $=  r$
Coupon $= 10$% of Facevalue $= 100 = C$
Annual payment of coupon in arrears
Maturity amount and the Face Value $= 1000 = M$
Time to Maturity $= T$
Give this,
Price of the Bond $P = \frac{C}{(1+r)^1} + \frac{C}{(1+r)^2}+\cdots + \frac{C+M}{(1+r)^T}$
Apply this formula for Bond 1 and Bond 2 with $T_1 = 2$ and $T_2 = 10$
Price of the Bond 1 $=  966.20$
Price of the Bond 2 $=  887.00$
In the afternoon after the there has been an interest rate hike, r becomes equal to $14$%
Remainder of the numbers remain the same and now compute the price and the results are
Price of the Bond 1 $=  934.13$
Price of the Bond 2 $=  791.36$
Portfolio value before the rate hike $= 1,853.19$
Portfolio value after the rate hike  $= 1,725.49$
Intuitively it is correct because a rise in YTM reduces the price according to price yield relationship.
Goodluck
Comment: you are welcome!!

Value price of Bond


Send all outgoing mail to /dev/null

Question: With sendmail, how would you send all outgoing mail to /dev/null or just prevent email from being queued up or sent at all?
On a development nagios box I want prevent sending of mail so that notifications don't go out. Stopping outbound mail will allow me to test the nagios config as is and prevent spurious notifications.
Comment: Removed solaris tag, as the question, and the solution isn't OS specific at all.
Answer: I did this on my development box by disabling sendmail completely and then having a simple perl script listen on the SMTP port and dump the emails into a directory.  I'm sure it's possible to do with the sendmail configuration, but the perl script was much easier.  Here's it stripped down to the essentials:
#!/usr/bin/perl -w
use Net::SMTP::Server;
use Net::SMTP::Server::Client;

$server = new Net::SMTP::Server || die("$!\n");

while($conn = $server->accept()) {
  my $client = new Net::SMTP::Server::Client($conn) ||
    die("Unable to handle client connection: $!\n");
  $client->process || next;

  # Here's where you can write it out or just dump it. Set $filename to
  # where you want to write it
  open(MAIL,"> $filename") || die "$filename: $1";
  print(MAIL "$client->{MSG}\n");
  close(MAIL);
}

Comment: +1 What an elegant solution, I was about to ask the same question.
Comment: This is an even better solution than I was thinking. Thanks.
Answer: The following sends everything to /dev/null:
LOCAL_RULE_0
R$* < @ $* > $*       $#local $: bit-bucket

This assumes that in your /etc/aliases:
bit-bucket: /dev/null

Comment: Be careful not to just type this in -- there is a TAB between the two sides of the rule.
Comment: What email system are you using and where do you add that rule?
Comment: Standard sendmail from sendmail.org. The rule gets added to sendmail.mc and then sendmail.cf is produced according to your OS / distribution's specifics.
Answer: Try smtp-sink, which is available on Linux. For example:
$ smtp-sink -u postfix -c nynode.com:25 1000

Answer: On a development vm running Joomla, I configured it to send emails to /some/path/sendmail.bash instead of the Sendmail default path /usr/sbin/sendmail. This was an easy way to log mails to a file for later debugging (including decoding base64 parts) using a bash/awk script while also preventing any emails being send by the CMS.
/some/path/sendmail.bash:
#!/bin/bash
read -d '' awkScript << 'EOF'
BEGIN {
    p=1 #print
    multipart=0
    boundary=0
    part=0
    text=0
    encoded=0
    debug=0
}
!multipart && tolower($0) ~ /^content-type:[ \t]*multipart/ {
#works!multipart && /^Content-Type: multipart/ {
    multipart=$2
    if (debug) { print "Multipart Email: " multipart }
}
multipart && !boundary && /boundary=/ {
    split($1,s,"=")
    boundary = s[2]
    gsub(/"/, "", boundary) #remove the surrounding quote
    if (debug) { print "With boundary: " boundary }
}
#start of new part or end of all parts
multipart && ($0 ~ ("^--" boundary "$") || $0 ~ ("^--" boundary "--") ) {
    part=1
    text=0
    encoded=0
    p=1
}
part && !text && tolower($0) ~ /^content-type: text/ {
    text=$2
    if (debug) { print "Text: " text }
}
part && encoded {
    #https://stackoverflow.com/questions/66228621/base64-decode-command-linux-cli-command
    if (/^\s*$/) { #skip decoding blank lines
        print $0
    } else {
        system("echo '" $0 "' | base64 -d")
    }
}
p #if p then print current line

part && text && !encoded && tolower($0) ~ /^content-transfer-encoding: base64/ {
    encoded=$2
    if (debug) { print "Encoded: " encoded }
    p=0 #make sure this line prints so test after it has printed
}

END {
   #print "END"
}
EOF
#echo $awkScript
awk "$awkScript" >> /tmp/sendmail.log
#awk "$awkScript"

Send all outgoing mail to /dev/null


Is it possible to get  form submission diff with Diff module

Question: Diff module, from what i've seen works with node revision differences, not node edit submission diff.
Is diffing any entity-related form submission possible programmatically through Diff module API? Suppose i alter node_form_submit() in my module and i want to record in watchdog the watchdog message the diff if this is a node edit event.
I try with diff_entity_diff($old_entity, $new_entity, $context) but i get no title changes and i'm not sure how to render this output.
Or in other words, which is the best way to get the diff of the submitted values of any form? (compare form_states)
Thanks
Answer: Problem is - diff compares entities and their revisions. But node_form_submit() happens before revision is created. If you will inspect node_save, you will see no hooks are called after actual save.
To get your code executed and be sure revision is there, it would be tempting to use Rules, but existing bug "After updating existing content" runs before content is saved. shows it has just the same issues as hooks. Maintainers say:

We just rely on the hooks drupal provides us here.

So now you have 2 options:

Give up on using diff module and just borrow some of it's code (it's open source after all)
On save, set a hidden field "test with diff" to true, and on cron make actual testing. With */5 minutes CRON it will be almost as good, as instantaneous test.


Dificuldade em passar dados do Flask para o JS

Question: Tenho uma aplicação feita com o framework Flask.
Em um formulário de Login, tenho o interesse de enviar uma informação do Python para o Javascript. Tentei fazer isso assim:
@app.route("/compras/", methods=["POST", "GET"])
def compras():
   global resposta
   output = request.get_json()
   result = json.loads(output)
   resposta = sqlite_funcs.confereUsuario(result['usuario'], result['senha'])
   # resposta = {'value': resposta}
   # resposta = json.dumps(resposta)
   return render_template('index.html', resposta=resposta), print(resposta)

O valor de "resposta" é printado corretamente no terminal. Para testar dentro do HTML:
{% if resposta is defined and resposta|length > 0 %}

{% endif %}

E por último, que é o que mais me interessa, uma parte do código JS que está dentro de uma função que contém um formulário SweetAlert:
.then(() => {
      let usr = resposta;
      console.log(usr);
      let usuario = JSON.parse(usr);
  });

Sou iniciante em programação, estou aprendendo por meio de aplicações Web simples. O foco da pergunta é entender como funciona o envio de dados no sentido Python -> Javascript.
No sentido contrário eu consegui, salvei informações inputadas pelo usuário no Sqlite desta forma.
Atualização:
Fiz um projeto TESTE contendo apenas um campo Input e um Botão Submit, ambos estão dentro de uma tag (sendo compras a função do endpoint que recebe as informações inputadas). Ao digitar algo e clicar no botão, um alert aparece com o que foi escrito e um "h1" renderiza na página.
Para comparar, eu comentei o Input e o Botão e adicionei uma tag script contendo o SweetAlert, mudei o método de requisição para JSON e adicionei um "print(informacoes_inputadas)" no endpoit do Python para conferir se estava recebendo as informações do formulário. Neste caso, as informações são realmente printadas no terminal (o que indica que elas chegaram no endpoit), mas não aparece o alert e nem é renderizado o "h1" na página.
Comment: já tentou dentro da tag script do html fazer `var resposta ={{ resposta }}`?
Comment: @RicardoPontual já sim... e não foi. Eu acredito que estou errando na rota "compras" do Flask...
Answer: Eu agradeço a todos pelas respostas.
O caminho para solução foi entender melhor como que funciona o AJAX no SweetAlert. Adicionei ".done(response)" logo apóx o AJAX, o que fez retornar a resposta da minha rota python. (Literalmente: response = return reposta  --> Sendo resposta o valor retornado pela função python).
Segue o código HTML com o SweetAlert:

{% block content %}
  {% if variavel is defined %}

Testing {{ variavel|tojson|safe }}

  {% endif %}
{% endblock %}

Segue o endpoit que recebe o usuário e senha e retorna o "response":
@app.route("/compras", methods=["POST", "GET"])
def compras():
    if request.method == 'POST':
        output = request.get_json()
        msg_ = json.loads(output)
        print(msg_, "1")
        try:
            if msg_ =='':
                flash(f"Digite algo para pesquisar", "error")
                return render_template('index.html')
            else:
                **return json.dumps(msg_)**
        except sqlite3.OperationalError as e:
            flash(f"Peça não encontrada, digite novamente !", "warning")
            return render_template('index.html', msg_=0), print(type(e), e)
    else: return print("error")

Antes eu estava retornando "render_template('index.html', response=response)" e não funcionava. Coloquei o "done((response) => console.log(response))" e percebi que todo o código 'index.html' estava sendo exposto no console. Tirei a render_template e deixei apenas "return json_dumps(response)" e mantive o console.log. Agora a variável "response" apareceu no console já formatada!
Comment: pois é cara, mas você utilizou a minha solução como base...
Comment: @Danizavtz não po... eu só li a documentação do "tojson", mas você realmente me ajudou, marquei sua resposta.
Comment: eu ja fiz isso em alguns projetos :)
Answer: Uma maneira de resolver o problema é utilizando uma variável auxiliar para fazer o parse das informações.
Desta forma, um código que pode resolver o problema é o seguinte:
você deve usar o JSON.parse dos dados recebidos no seu template html.

Para executar este fluxo, basta utilizar a documentação do filtro padrão tojson
Answer: Atualizado
No Flask basta usar a variável enviada entre {{ }}, ou seja, `{{ sua_variavel}}``
Veja o exemplo:

Hello World

  <button onclick="alert('Variavel: ' + someJavaScriptVar)" />

Outra possibilidade é usar |tojson|safe (veja aqui) conforme abaixo

No Django a solução seria fazer com que o JS pegue o valor em um bloco específico de variáveis que usam o pipe (|) conforme abaixo.
{% block vars_to_js %}
  {{ sua_variavrel|json_script:"variable_para_js" }}
{% endblock %}

(....seu código HTML aqui....)

Comment: Eu queria achar uma solução sem ter que adicionar nada no código HTML, mas sim trazendo a variável diretamente pro JS. Mesmo assim, eu tentei fazer desta forma (vai que trazia alguma ideia) e, infelizmente, não foi. Acredito que o "json_script" seja um filtro do Django Template, pois ao rodar na minha aplicação em FLASK aparece um erro do Jinja2: "jinja2.exceptions.TemplateSyntaxError: expected token 'end of print statement', got ':'"
Comment: Opa, pode ser que seja do DJANGO Template sim, porém eu tinha uma forte ideia que seria do JINJA2
Comment: Atualizei o post o Flask possui um `tojson`
Comment: Paulo, primeiramente devo te agradecer pela ajuda e disposição. O conhecimento do "tojson" foi muito útil!

Seguindo com o problema: O formulário por onde as informações são inputadas é um SweetAlert. Fiz um teste para ver se o problema era com a configuração dele:
- Fiz um projeto Teste simples apenas com um campo de input = consegui receber as informações chamando o endpoint pelo "onclick" do botão subtmit;
- Tirei o input e o botão e adicionei o SweetAlert no lugar e tentei receber as informações = as informações não são recebidas!
Comment: O mais engraçado é que eu sei que as informações chegaram no endpoit, pois eu coloquei um "print(informações)" e deu certo. Meu foco é, dependendo dessas "informações" um função JS vai ser rodada, por isso que eu não tenho interesse de passar pelo HTML, mas sim mandar diretamente as "informações" do endpois Flask (que eu sei que ta la por conta do print) para a função JS que vai renderizar outro popup depois.


Example for: $Cov(X,Y)=0$ but $Cov(h(X),Y)\neq0$ for some function $h(.)$.

Question: Can you help me find a simple example for this particular situation?
$X$ and $Y$ are random variables such that $Cov(X,Y)=0$ but $Cov(h(X),Y)\neq0$
for some function $h(.)$.
Thank you
Answer: Try: $X\sim\mathcal U\{-1,0,1\}, Y=X^2, h:s\mapsto s^2$
$\mathsf {Cov}(X,X^2)=0, \mathsf {Cov}(X^2,X^2)=1$
Comment: As @rjann says,  $\mathsf {Cov}(X^2,X^2)=\dfrac29$ rather than $1$
Answer: I was just checking Graham's answer.It's a really nice simple example, but I found different values:
Assume $X$ takes value $-1$ with probability $1/3,$ $0$ with probability
$1/3$ and 1 with probability $1/3$. Therefore
\begin{align*}
E\left(X\right)=-1\times\frac{1}{3}+0\times\frac{1}{3}+1\times\frac{1}{3}=0,
\end{align*}
\begin{align*}
E\left(X^{2}\right) & =\left(-1\right)^{2}\times\frac{1}{3}+0\times\frac{1}{3}+\frac{1}{3}\\
 & =\frac{2}{3},
\end{align*}
\begin{align*}
E\left(X^{3}\right) & =\left(-1\right)^{3}\times\frac{1}{3}+0\times\frac{1}{3}+\frac{1}{3}\\
 & =0
\end{align*}
and
\begin{align*}
E\left(X^{4}\right) & =\left(-1\right)^{4}\times\frac{1}{3}+0\times\frac{1}{3}+\frac{1}{3}\\
 & =\frac{2}{3}.
\end{align*}
Let $Y=X^{2}$. Then
\begin{align*}
Cov(X,Y) & =Cov\left(X,X^{2}\right)\\
 & =E\left(X^{3}\right)-E\left(X\right)E\left(X^{2}\right)\\
 & =0
\end{align*}
and
\begin{align*}
Cov(X^{2},Y) & =Cov\left(X^{2},X^{2}\right)\\
 & =E\left(X^{4}\right)-\left(E\left(X^{2}\right)\right)^{2}\\
 & =\frac{2}{3}-\left(\frac{2}{3}\right)^{2}\\
 & =\frac{2}{3}\left(1-\frac{2}{3}\right)\\
 & =\frac{2}{9}.
\end{align*}


find pattern in the following sequence

Question: I would like to represent the following with a simple function.
the pattern is this
$1,3,5,6,7,9,10,11,12,13,14,15,17,\dots,n$
Note all the numbers with an integer result for a logarithm with base 2 are not present in the series ($2,4,8,16,\ldots$ etc are not present in the series).
Can you help me find a pattern and represent the summation with a simple function.
Thanks
Comment: I am unable to figure out yet but will let you know if it works..can you write me your answer in plain english because the code hasn't been interpreted by the site.
Comment: $$f(n)=\left(\sum_{k=1}^n k\right)-\left(\sum_{k=1}^{\lfloor \log_2(n)\rfloor}2^k \right)=\frac{n(n+1)}{2}-\left(\sum_{k=1}^{\lfloor\log_2(n)\rfloor}2^k\right)$$

I'm not sure whether the latter sum can be simplified further. Is this sufficient enough for you?
Comment: I have edited the comment. Does it appear clearly now?
Comment: Great work...thanks for your help
Answer: The sequence is sums of two or more consecutive nonnegative integers.
http://oeis.org/A138591

find pattern in the following sequence


colorbox custom caption via field collection

Question: I want to have a content type with a field collection of an image and a text field. The image is to be displayed via Colorbox, the text field is to be used as the caption for the image.
I am sure I achieved this without problems before.
When I want to chose the relevant token for the custom image caption in cbox, the token browser does not allow me to use the other field. Only the current date, page use, files, random and site information token groups are available (see image below).
What am i doing wrong?
Answer: One needs to enable the entity API / entity token (included in Entity API) modules. The field collection text fields become available to tokens and can thus be used as captions.


Adding validation to existing forms using #element_validate

Question: Problem
I'm using #element_validate to validate an input on a custom form which creates a node. I'm using element_validate_integer_positive as the function to validate. It works perfectly.
It partly works when I try to hook the same code into the existing node edit form. The form still breaks and displays the correct message but it also throws two errors due to missing values. How can I remove these errors?
So far
Here's the form code from my custom module. This works as expected.
$form['field_total_vacation'] = array(
  '#type' => 'textfield',
  '#title' => t('Total Vacation'),
  '#size' => 5,
  '#element_validate' => array('element_validate_integer_positive'),
);

Here's my hook into the node edit form:
function viewspagehack_form_alter(&$form, $form_state, $form_id) {
  if ($form_id === 'job_advert_node_form') {

    $form['field_total_vacation']['#weight']             = 19;
    $form['field_total_vacation']['#element_validate']   = array('element_validate_integer_positive');
    }
  }

If I enter a non-positive integer into field_total_vacation on the node edit form, it still breaks and throws the correct message: "Total Vacation must be a positive integer" but it also throws:
Notice: Undefined index: #value in element_validate_integer_positive() (line 4190 of C:\XAMPP\htdocs\drupal\includes\form.inc).
Notice: Undefined index: #title in element_validate_integer_positive() (line 4192 of C:\XAMPP\htdocs\drupal\includes\form.inc).

This is because element_validate_integer_positive() takes $element as it's first input and the function then calls:
$element['#value']
$element['#title']

But this error doesn't throw on my custom form which also doesn't take an input. What's going on?
EDIT
I moved #element_validate to here, this means it now has access to #title:
$form['field_total_vacation']['und']['0']['#element_validate']   = array('element_validate_integer_positive');

This removes the title error but leaves the value error. I can't understand why this function takes #value from $element.
function element_validate_integer_positive($element, &$form_state) {
   $value = $element['#value'];

None of the form elements have #value, #value only seems to appear in $form_state. But yet it works in my custom form and not on the node edit.
Comment: Does [this](http://drupal.stackexchange.com/questions/27767) help?
Comment: @Clive Partly. I spotted that #value was hiding a couple levels down as you mentioned in that post. But the `#value` error still exists and I can't understand where my custom form is even getting `#value` from. Added an edit to my main question.
Answer: the method that work is this
function MYMODULE_form_NODE_FORMID_alter(&$form, &$form_state) {
  dpm($form);
  $form['body'][LANGUAGE_NONE][0][['#element_validate'][] = 'MYMODULE_validate_breads_node_form_alter';
}

/**
 * Implements callback function().
 * Specific alteration for views exposed forms
 */
function MYMODULE_validate_NODE_FORMID_alter($element, &$form, &$form_state) {
  if (empty($element['#value'])) {
    form_error($element, t('Text'));
  }
}

Comment: The callback function signature should be: `function myelement_validate($element, &$form_state, $form)` (switch $form and $form_state parameters and don't pass $form byref).
Answer: I ended up using the format of Jonathan's answer, although I added an extra validation function as opposed to putting it in #element_validate
function mymodule_form_alter (&$form, $form_state) {
  if ($form_id === 'node_edit_form_id') {
    $form['#validate'][] = 'mymodule_editjobadvert_validate';
  }
}

Two things to note about this. First student_age appears twice because the field can have multiple values and I need to check both.
Second each if checks if the value is a number or empty. Because empty is also ok.
function mymodule_editnode_validate ($form, $form_state) {
  /*element validate doesn't work when adding with form_alter for some reason. http://drupal.stackexchange.com/questions/86990/adding-validation-to-existing-forms-using-element-validate*/
  if(is_numeric($form_state['values']['field_total_vacation']['und']['0']['value']) || $form_state['values']['field_total_vacation']['und']['0']['value'] == NULL ) {
        } else {
          form_set_error('field_total_vacation', "Total Vacation must be a number");
    };
  if(is_numeric($form_state['values']['field_student_age']['und']['0']['value']) || $form_state['values']['field_student_age']['und']['0']['value'] == NULL ) {
        } else {
          form_set_error('field_student_age', "Student age must be a number");
    };
  if(is_numeric($form_state['values']['field_student_age']['und']['1']['value']) || $form_state['values']['field_student_age']['und']['0']['value'] == NULL ) {
        } else {
          form_set_error('field_student_age', "Student age must be a number");
    };
}

Answer: for Drupal 8 -9 here is an example of adding validation to all of a field type:
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMOD_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  $textarea_fields = [
    'text_with_summary',
    'text_long',
  ];
  if (in_array($field_definition->getType(), $textarea_fields)) {
    if (!empty($element['#element_validate'])) {
      $element['#element_validate'][] = '_MYMOD_textfield_validate';
    }
    else {
      $element['#element_validate']= ['_MYMOD_textfield_validate'];
    }
  }
}

/**
 * Implements hook_validate().
 */
function _MYMOD_textfield_validate($element, $form_state) {
  $max_length = 5000;
  if (!empty($element['#value'])) {
    $value = $element['#value'];
    if (strlen($value) > $max_length) {
      $form_state->setError($element, t('Sorry there is a max input value of 5000 characters'));
    }
  }
}


SSTP SERVER without certificate check

Question: Is it possible to make a SSTP server where clients don't need certificates?  If I want to use linux or microtik routeros as a client, do I have to do something extra in the SSTP server (Windows Server 2008)?
Answer: All the references to SSTP, including in the standard itself refer to certificate based authentication for at least the server.

SSTP SERVER without certificate check


Exercise 5-15 from Spivak's Calculus on Manifolds

Question: I came across the following question (Exercise 5-15) in Spivak's Calculus on Manifolds and am not sure how to solve it.
Let $M$ be an $(n-1)$-dimensional manifold in $\mathbb{R}^n$. Let $M(\epsilon)$ be the set of end-points of normal vectors (in both directions) of length $\epsilon$ and suppose $\epsilon$ is small enough so that $M(\epsilon)$ is also an $(n-1)$-dimensional manifolds. Show that $M(\epsilon)$ is orientable (even if $M$ is not). What is $M(\epsilon)$ if $M$ is the Mobius strip?
I have thought about this problem for quite some time now and can't seem to figure it out. Also, how do we know that $M(\epsilon)$ is a manifold for sufficiently small $\epsilon$? Note that I am currently using Lee's Introduction to Smooth Manifolds, so any of the tools presented in that text can be used here.
UPDATE: This seems to be almost the same thing as the oriented double covering presented in Lee's text. Can that be applied here?
Answer: Presumably $M$ must be compact, since there are non-compact submanifolds of $\Bbb R^n$ for which $M(\epsilon)$ need not be a manifold for any $\epsilon > 0$ (for example, $\left\{\left(x, \sin\frac 1x\right)\ \middle|\ x > 0\right\}$ in $\Bbb R^2$).
But if $M$ is compact, then the curvature of $M$ is bounded and disparate parts of $M$ have a minimum separation. So if $\epsilon$ is small enough, the offset of $M$ by $\epsilon$ will neither pinch nor intersect itself.
$M(\epsilon)$ offsets $M$ by $\epsilon$ in either direction. If $M$ is orientable, then $M(\epsilon)$ will be two disjoint copies of $M$ (near copies - there is some distortion from the offset), which will each be orientable as well.
If $M$ is not orientable, then we can see what happens by considering the Möbius strip. When you offset it, the two sides meet at the twist, so $M(\epsilon)$ is connected. But whereas $M$ has only one twist, $M(\epsilon)$ has two twists, one on each side of the twist in $M$. A strip with two twists is orientable. Think of sliding a normal vector of length $\epsilon$ along the Möbius strip. The tip of the vector is a point of $M(\epsilon)$. If you slide the vector all the way around the strip, you come back to the starting point, but with the normal pointing in the opposite direction. This is why the strip is not orientable. But the tip of the vector in $M(\epsilon)$ has not returned to its starting point. It now lies on the part of $M(\epsilon)$ opposite of where it started. To get it back to its starting point, you have to move the vector around the strip a second time, so it points in the same direction again, as does the normal to $M(\epsilon)$ at its tip. This is why $M(\epsilon)$ remains orientable. The same thing holds for any unorientable manifold.
Comment: This is a nice way to think about the problem. However, is there any way to explicitly prove that $M(\epsilon)$ is orientable? That is, give it an orientation.
Comment: I only intended to give you a heuristic description that I hoped would help you in understanding the problem so that you could find your own solution. I'm not sure how Spivak defines orientation (there are multiple equivalent versions) or what tools he has developed. I will say that my description at the end should lead you to a general proof.
Comment: It might help to realize that $M(\epsilon)$ is a double cover of $M$ ($\epsilon$ is chosen small enough that this is true). The cover map can be used to relate the orientations on $M$ and $M(\epsilon)$.
Comment: I actually just finished reading Lee's Introduction to Smooth Manifolds, so I am trying to solve it using tools from that text. Maybe his section on orientations and covering maps will be useful.


Integration of $\frac{1}{\sin x+\cos x}$

Question: I'm given this $\int\frac{1}{\sin x+\cos x}dx$.
My attempt,
$\sin x+\cos x=R\cos (x-\alpha)$
$R\cos \alpha=1$ and $R\sin \alpha=1$
$R=\sqrt{1^2+1^2}=\sqrt{2}$,
$\tan\alpha=1$
$\alpha=\frac{\pi}{4}$
So, $\sin x+\cos x=\sqrt{2}\cos (x-\frac{\pi}{4})$
$\int\frac{1}{\sin x+\cos x}dx=\int \frac{1}{\sqrt{2}\cos (x-\frac{\pi}{4})}dx$
$=\frac{1}{\sqrt{2}}\int \sec (x-\frac{\pi}{4})dx$
$=\frac{1}{\sqrt{2}} \ln \left | \sec (x-\frac{\pi}{4})+\tan (x-\frac{\pi}{4}) \right |+c$
Am I correct? Is there another way to solve this integral? Thanks in advance.
Comment: I think that what you did was the most efficient way.
Answer: Try using the substitution $t=\tan\frac x2$
Answer: Your computations are correct. Now, if you make the substitution $t = \tan\left(\frac{x}{2}\right)$, you get
\begin{align}
\cos x &= \frac{1-t^{2}}{1+t^{2}} \\
\sin x &= \frac{2t}{1+t^{2}} \\
dx &= \frac{2 \, dt}{1+t^{2}}
\end{align} then
\begin{align}
\int \frac{dx}{\cos x + \sin x }
&= -\int  \frac{dt}{t^{2}-2t-1 } = \frac{1}{\sqrt{2}}\rm arctanh \left(\frac{t-1}{\sqrt{2}}\right)+C.
\end{align}
Answer: Another method would be to multiply by $\cos x-\sin x$ on the top and bottom to get
$\displaystyle\int\frac{\cos x-\sin x}{\cos 2x} dx=\int\frac{\cos x}{1-2\sin^2 x} dx-\int\frac{\sin x}{2\cos^2 x-1} dx$, and then use
$\displaystyle\int\frac{1}{1-2u^2}du=\frac{\sqrt{2}}{4}\ln\bigg|\frac{1+\sqrt{2}u}{1-\sqrt{2}u}\bigg|+C=\frac{\sqrt{2}}{2}\tanh^{-1}(\sqrt{2}u)+C$ to find both terms.


merge multiple nested array of nested objects in es6?

Question: i have an array like this:
[
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

now i want to have all items in data in one array, an end result like this:
[
  { a: "a", b: "b" },
  { x: "x", y: "y" },
  { c: "c", d: "d" },
  { z: "z", f: "f" },
  { d: "d", e: "e" },
  { g: "g", h: "h" },
];

i don't wanna use lodash which i found on suggested questions, hope to use only es6
Answer: Simply, using Array.prototype.flatMap, you can make all items in data in one array.

const input = [
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

const output = input.flatMap((item) => item.data);
console.log(output);
Answer: You maybe are looking for this:

const params = [
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

const result = params.map(p => p.data).flat();
console.log(result)
Answer: Use array reduce method.
let a = [
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

let ret = a.reduce((p, c) => p.concat(c.data), []);
console.log(ret);

Answer: let data = [
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

let final =[]
let newData = data.map(el => el.data.map(e => final.push(e)))
console.log(final)

Answer: May use reduce with spread-operator:

const arr = [
  {
    data: [
      { a: "a", b: "b" },
      { x: "x", y: "y" },
    ],
  },
  {
    data: [
      { c: "c", d: "d" },
      { z: "z", f: "f" },
    ],
  },
  {
    data: [
      { d: "d", e: "e" },
      { g: "g", h: "h" },
    ],
  },
];

const newArr = arr.reduce((acc, rec) => [...acc, ...rec.data], [])
Comment: Hi and welcome to stackoverflow, you might want to edit in an explanation why your solution works, and what it does. As it stands it's just a slab of code without much explanation even if it does seem correct.


How to configure PayloadValidatingInterceptor using annotation

Question: I am trying to develop a Spring webservice and followed this tutorial https://spring.io/guides/gs/producing-web-service/
The project structure(and the configuration class names) are same as mentioned in the tutorial.
I am trying to do all possible configuration using annotation and want to avoid all xml based configuration. So far I even avoided applicationContext.xml and web.xml by using java configuration. However, now I want to introduce XSD validation as shown in this tutorial:
http://stack-over-flow.blogspot.com/2012/03/spring-ws-schema-validation-using.html i.e. by extending the PayloadValidatingInterceptor class.As shown in the tutorial, this custom validator interceptor then needs to be registered using the following xml configuration:
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
 <property name="interceptors">
  <list>
    <ref bean="validatingInterceptor"/>
  </list>
 </property>
</bean>

<bean id="validatingInterceptor" class="com.test.ValidationInterceptor ">
     <property name="schema" value="/jaxb/test.xsd"/>
</bean>

However, I am not sue how to do the above configuration using annotation. i.e. setting the XSD file to the interceptor. I have tried overriding the "addInterceptor" of the WsConfigurerAdaptor class to register the interceptor. Please let me know if I need to do that or what is the correct way of doing the entire thing using annotations.
Answer: I'm working with spring-boot and i was looking for a way to do the same, and i found this:
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

  @Override
  public void addInterceptors(List<EndpointInterceptor> interceptors) {
    PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor();
    validatingInterceptor.setValidateRequest(true);
    validatingInterceptor.setValidateResponse(true);
    validatingInterceptor.setXsdSchema(resourceSchema());
    interceptors.add(validatingInterceptor);
  }

  @Bean
  public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
    MessageDispatcherServlet servlet = new MessageDispatcherServlet();
    servlet.setApplicationContext(applicationContext);
    servlet.setTransformWsdlLocations(true);
    return new ServletRegistrationBean(servlet, "/api/*");
  }

  @Bean(name = "registros")
  public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
    DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
    wsdl11Definition.setPortTypeName("ResourcePort");
    wsdl11Definition.setLocationUri("/api");
    wsdl11Definition.setTargetNamespace("http://resource.com/schema");
    wsdl11Definition.setSchema(resourceSchema());
    return wsdl11Definition;
  }

  @Bean
  public XsdSchema resourceSchema() {
    return new SimpleXsdSchema(new ClassPathResource("registro.xsd"));
  }
}

In this example the addInterceptors method is the important, the others 3 are basic to expose a WSDL API.
Maybe it'll be useful for someone else.
Comment: I have more than 1 url and they have different  xsd for validation, how to do that?
Comment: Use an approach of 2 different war to separate both configurations is not an option?
Comment: Thanks for the reply. Actually, I am working on spring boot application and this is part of same. I have already post a detail question https://stackoverflow.com/questions/51208567/how-to-do-xsd-validation-for-incoming-request-when-we-have-more-than-1-url]
Comment: upvote on your answer since this is rarerly availble soloution over internet
Answer: I could solve it using following:
@Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
    interceptors.add(validationInterceptor());
}
@Bean
ValidationInterceptor validationInterceptor() {
        final ValidationInterceptor payloadValidatingInterceptor = new ValidationInterceptor();
        payloadValidatingInterceptor.setSchema(new ClassPathResource(
                "XSD/Pay.xsd"));
        return payloadValidatingInterceptor;
    }

and then I had to read the schema file from the validator class using the following
SchemaFactory schemaFactory = SchemaFactory.newInstance(getSchemaLanguage());
        Schema schema = schemaFactory.newSchema(getSchemas()[0].getURL());
        Validator validator = schema.newValidator();

Comment: Voted down because code fragment has no context.  Not indicated which class to put into.  See Julio Villlane's answer below for more complete code.
Answer: I was able to solve it by following way.
@Override
    public void addInterceptors(List<EndpointInterceptor> interceptors) {
        HotelDirectUpdateRQValidator validatingInterceptor = new HotelDirectUpdateRQValidator();
        validatingInterceptor.setValidateRequest(true);
        validatingInterceptor.setValidateResponse(false);
        validatingInterceptor.setXsdSchemaCollection(new XsdSchemaCollection() {
            @Override
            public XsdSchema[] getXsdSchemas() {
                return null;
            }

            @Override
            public XmlValidator createValidator() {
                try {
                    return XmlValidatorFactory.createValidator(getSchemas(), "http://www.w3.org/2001/XMLSchema");
                } catch (Exception e) {
                    LOGGER.error("Failed to create validator e={}", e);
                }
                return null;
            }

            public Resource[] getSchemas() {
                return new Resource[]{
                        new ClassPathResource("/schemas/OTA/OTA_HotelRateAmountNotifAndHotelAvailNotifRQValidate.xsd"),
                        new ClassPathResource("/schemas/HotelDirectUpdateRQ.xsd")
                };
            }
        });

        interceptors.add(validatingInterceptor);
    }

Answer: Configure your validator interceptor class in spring.xml like below:
<sws:interceptors>

    <bean id="validatingInterceptor"
            class="com.kalra.xsd.validator.WSDLValidator">
            <property name="xsdSchema" ref="types" />
            <property name="validateRequest" value="true" />
            <property name="validateResponse" value="true" />
    </bean>

</sws:interceptors>

Need to add your bean validatingInterceptor in this tag sws:interceptors so that interceptor will automatically register. For sws prefix need to add xmlns is "xmlns:sws="http://www.springframework.org/schema/web-services" in spring.xml
we should write wsdlvalidator child class of PayloadValidatingInterceptor for our own QNAME to show in response after fault exception otherwise it will pick default qname of sprint ws.
WSDLValidator code snapshot:
import javax.xml.namespace.QName;
import org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor;

public class WSDLValidator extends PayloadValidatingInterceptor {

    public WSDLValidator(){
    }

    @Override
    public QName getDetailElementName() {
        return new QName(Constants.XMLNamespaces.TNS_URI, "SoapValidationFault");
    }

}

SoapValidationFault is complex type declaration in XSD and TNS_URI is target namespace defined in wsdl and xsd.


Separate the host-side and CUDA-device-side versions of library

Question: I have a library with some __host__  __device__ functions. I also have an #ifdef __CUDACC__ gadget which makes sure that a regular C++ compiler doesn't see the __host__ __device__ and can thus compile those functions.
Now, I want to use the compiled host-side version of my library's function in a plain-vanilla C++ static library file (.a on Linux) - and I would even like that library to be compilable when CUDA is unavailable; and I want the compiled device-side versions in a separate static library.
I am almost there (I think), but am stuck with a linking error. Here are toy sources for such a library, a test program (which calls both the device-side and the host-side version of a function) and the build commands I use.
What am I getting wrong?

my_lib.hpp (Library  header):

#ifdef __CUDACC__
__host__ __device__
#endif
void foo(int*x, int* y);
int bar();

my_lib.cu (Library  source):

#include "my_lib.hpp"

#ifdef __CUDACC__
__host__ __device__
#endif
void foo(int*x, int* y)  { *x = *y; }

int bar() { return 5; }

main.cu (test program):

#include "my_lib.hpp"

__global__ void my_kernel() {
  int z { 78 };
  int w { 90 };
  foo(&z,&w);
}

int main() {
  int z { 123 };
  int w { 456 };
  foo(&z,&w);
  my_kernel<<<1,1>>>();
  cudaDeviceSynchronize();
  cudaDeviceReset();
}

My build commands:
c++ -c -x c++ -o my_lib-noncuda.o my_lib.cu
ar qc my_lib-noncuda.a my_lib-noncuda.o
ranlib my_lib-noncuda.a
nvcc -dc -o my_lib-cuda.o my_lib.cu
ar qc my_lib-cuda.a my_lib-cuda.o
ranlib my_lib-cuda.a
nvcc -dc -o main.rdc.o main.cu
nvcc -dlink -o main.o main.rdc.o my_lib-cuda.a
c++ -o main main.o my_lib-noncuda.a -lcudart

And the errors I get - on the last, linking, command:
/usr/bin/ld: main.o: in function `__cudaRegisterLinkedBinary_39_tmpxft_00003f88_00000000_6_main_cpp1_ii_e7ab3416':
link.stub:(.text+0x5a): undefined reference to `__fatbinwrap_39_tmpxft_00003f88_00000000_6_main_cpp1_ii_e7ab3416'
/usr/bin/ld: main.o: in function `__cudaRegisterLinkedBinary_41_tmpxft_00003f69_00000000_6_my_lib_cpp1_ii_ab44b3f6':
link.stub:(.text+0xaa): undefined reference to `__fatbinwrap_41_tmpxft_00003f69_00000000_6_my_lib_cpp1_ii_ab44b3f6'
collect2: error: ld returned 1 exit status

Notes:

I use CUDA 10.1 and g++ 9.2.1 on Devuan GNU/Linux.
This is a "follow-up" to a deleted question; @talonmies commented I had better show exactly what I did; and that changed the question somewhat.
Somewhat-related question: this one.
Comment: That example is broken beyond the errors you describe. There should be no main emitted anywhere in that build sequence either and there should be a main not found error as well, unless I read this wrongly
Comment: @talonmies: Now I'm showing you what I'm doing exactly.
Comment: @talonmies: Well, the errors are what they are, although I see what you mean about `main()` and `-dc`. The thing is, if I drop the `-dc`, I get a compilation error: `nvcc -o main.o main.cu` results in `Unresolved extern function '_Z3fooPiS_'`.
Comment: I'm confused about what you want to do. I thought you want to link a "plain-vanilla C++ static library file" to a C++ program. But as I see it you would like to use a C++ compiler in the last step for linking only and still have all the CUDA stuff present.

Maybe this is what you are looking for: https://devblogs.nvidia.com/separate-compilation-linking-cuda-device-code/ - Section "Advanced Usage: Using a Different Linker"
Comment: @Shadow: Not quite. I want to have a "split library": One `.a` file of host-side versions of functions, which I could use in regular C++ linking regardless of CUDA; and another `.a` file, of device-side versions of functions, which I can link with my CUDA code that calls these functions from within a kernel. The test program exemplifies the second kind of use.
Answer: Here is how you could create two libraries, one containing only CUDA-device functions and the other containing only host functions.
You could omit the "complicated" #if and the #ifndef guard. But then you would have also the "non-CUDA-code" in your library my_lib-cuda.a.
For the other issues see @talonmies community wiki answer or refer to the link I already posted in the comments: https://devblogs.nvidia.com/separate-compilation-linking-cuda-device-code/ - Section "Advanced Usage: Using a Different Linker".
my_lib.cu
#include "my_lib.hpp"

#ifdef __CUDA_ARCH__
__device__
#endif
#if (defined __CUDA_ARCH__) || (not defined __CUDACC__)
void foo(int*x, int* y)  { *x = *y; }
#endif

#ifndef __CUDACC__
int bar() { return 5; }
#endif

The build process of the libraries stays the same: (only changed ar qc to ar rc to replace existing files so you don't get an error when rebuilding without deleting the library beforehand)
c++ -c -x c++ -o my_lib-noncuda.o my_lib.cu
ar rc my_lib-noncuda.a my_lib-noncuda.o
ranlib my_lib-noncuda.a
nvcc -dc -o my_lib-cuda.o my_lib.cu
ar rc my_lib-cuda.a my_lib-cuda.o
ranlib my_lib-cuda.a

Building a CUDA program: (simplified by using only nvcc and not c++, alternatively have a look at @talonmies community wiki answer)
nvcc -dc main.cu -o main.o
nvcc main.o my_lib-cuda.a my_lib-noncuda.a -o main

The link to my_lib-noncuda.a can be omitted if you also omit the #if and #ifndef in my_lib.cu as described above.
Building a C++ program: (given that there are #ifdef __CUDACC__ guards around the CUDA code in main.cu)
c++ -x c++ -c main.cu -o main.o
c++ main.o my_lib-noncuda.a -o main

Comment: The thing is, that if I take this approach, I'll get clashes. That is, suppose my application directly uses my_lib on the device side and other_lib on the host side. Now, other_lib in turn uses my_lib on the host side. When I'll try and link everything together the host-side functions will be found in two conflicting places, won't they?
Comment: If you do it as I have done, my_lib would consist of only device or only host code. So your example would not make sense. And conflicts are always something you have to look out for and with what I have done there are no additional potential conflicts.
Comment: So, this fails. That is, the second of the two lines for building the CUDA program fails, with: `nvlink error   : Multiple definition of '_Z3fooPiS_' in 'my_lib-cuda.a:my_lib-cuda.rdc.o', first defined in 'my_lib-cuda.a:my_lib-cuda.o'
nvlink fatal   : merge_elf failed` - unless your changes are relative to what @talonmies wrote.
Comment: Oh. You're right. But only if I repeat some compilation steps. On the first compilation everything works fine for me. But that seems to be a problem of creating the library. On the second run `my_lib-cuda.a` is not rewritten but appended.
Comment: Indeed, the problem is with the way I create the two libraries in the question. I need to do something else... but remember that the separation of host and device code is the crux of the question, not the compilation of the example program.
Comment: Yes. But isn't that exactly what I'm doing? The library `my_lib-cuda.a` only contains device code and `my_lib-noncuda.a` only contains host code.
Comment: I have added the missing parts. But building the libraries really stays the same. Of course you could also split also the main file like @talonmies did but I left that out as I understood your question as "how to have an only-device- and an only-host-library". And in your example you choose to not include the kernel in the device-library so I thought that the content and the structure of the main file is not of importance.
Comment: Ok, now that it works for me, +1. But I don't quite understand _why_ this works: (1.) How can the switches to the `ar` commands affect the linking in a later command? There's no need for replacement until later. (2.) how come nvcc is willing to accept a `__device__`-only function in the `.cu`, when the header says `__host__ __device__`?
Comment: (1) The library is kind of just a collection of implementations. It does not care if it holds two implementations for the same function. But when you actually need to call the function, that is when you link against the library, you will get a linking error. Therefore you need to make sure to not just blindly append files (that is "implementations of functions") but to only append them if they are not already present. I honestly don't no when "appending" option instead of "replace if already present or add if not present" is ever a useful thing.
Comment: (2) You can actually have two completely different implementations of the function. (See my first or second version of the answer). And of course it is always OK to have some declarations without definitions as long as you add the definitions before you actually use them (which is done in the linking step). In summary you could say: The host version and the device version of `foo` are two completely different and independent functions. It may just be convenient for you to have a host and a device function with the same name (and maybe also save a few lines of duplicate code).
Comment: And won't I have a problem writing `__host__ __device__` functions later, which call `bar()`?
Comment: Only a host function can call `bar` (which is a host function) of course. But that's always the case. Or do you mean `__host__ __device__` functions which call `foo`? I see no problem with that.
Answer: Let us modify your example into what I think your actual usage case would be. The modification places main() into a .cpp file, to be compiled by g++, and the CUDA code into a separate .cu file, to be compiled by nvcc. This is important to making your two-library setup work; and justifiable, because the "main contains CUDA kernels requiring separate compilation and linkage" is a peculiar corner case for the nvcc compilation model.
The restructured code:
main.cu:
include "my_lib.hpp"

__global__ void my_kernel() {
  int z { 78 };
  int w { 90 };
  foo(&z,&w);
}

int cudamain()
{
  my_kernel<<<1,1>>>();
  return 0;
}

main.cpp:
#include <cuda_runtime_api.h>
#include "my_lib.hpp"

extern int cudamain();

int main() {
  int z { 123 };
  int w { 456 };
  foo(&z,&w);
  cudamain();
  cudaDeviceSynchronize();
  cudaDeviceReset();
}

all other files remain as in the question.
The commands required to build the program are now:
c++ -c -x c++ -o my_lib-noncuda.o my_lib.cu
ar qc my_lib-noncuda.a my_lib-noncuda.o
ranlib my_lib-noncuda.a

nvcc -std=c++11 -dc -o my_lib-cuda.rdc.o my_lib.cu
ar qc my_lib-cuda.a my_lib-cuda.rdc.o
ranlib my_lib-cuda.a

# Until this line - identical to what you have tried in your question

nvcc -std=c++11 -c -rdc=true main.cu -o main.cu.o
nvcc -dlink -o main.o main.cu.o my_lib-cuda.a

c++ -std=c++11 -o main main.cpp main.o main.cu.o -I/path/to/cuda/include \
    -L/path/to/cuda/lib64 my_lib-cuda.a my_lib-noncuda.a -lcudart -lcudadevrt

The important thing to keep in mind there are host side components which need to be carried forward in the build. Thus you must pass the nvcc output of the CUDA host code to the main linkage, and you must also add your CUDA side library to the main linkage. Otherwise the host-side runtime API support for your code will be missing. Note also you must link the device runtime library to make this work.
Comment: Linking against `my_lib-noncuda.a` is not necessary here, or is it?
Comment: Yes. The main calls the host version of the host/device function
Comment: I just copied the exact code and compilation commands and only removed the link against `my_lib-noncuda.a`. I got no error.
Comment: I didn't look at the host side of things to be honest, just the missing dependencies and lack of main
Comment: @talonmies; There is still duplication with the libraries - which is a problem in my own build attempt in the question. Like @Shadow suggests - `my_lib-cuda.a` has both the host-side and device-side versions of `foo()`, as well as the host-side version of `bar()`. And if you switch the linking order in your last build command - first the `-cuda.a`, then the `-noncuda.a` (which is quite likely to happen inadvertently with build system generators or just naively) - you get errors:
Comment: `/usr/bin/ld: my_lib-cuda.a(my_lib-cuda.rdc.o): in function \`foo(int*, int*)':
tmpxft_00001859_00000000-5_my_lib.cudafe1.cpp:(.text+0x16): multiple definition of \`foo(int*, int*)'; my_lib-noncuda.a(my_lib-noncuda.o):my_lib.cu:(.text+0x0): first defined here
/usr/bin/ld: my_lib-cuda.a(my_lib-cuda.rdc.o): in function \`bar()':
tmpxft_00001859_00000000-5_my_lib.cudafe1.cpp:(.text+0x31): multiple definition of \`bar()'; my_lib-noncuda.a(my_lib-noncuda.o):my_lib.cu:(.text+0x1b): first defined here
collect2: error: ld returned 1 exit status`
Comment: @talonmies; Also - you're right about my intended use, so the modification is basically acceptable :-)
Comment: Your TLDR comment edit was incorrect and I have removed it. The fix isn't caused by the separation of main and cuda, it is caused by the additional objects that are required to be linked. I you split the main and compile and link as you were doing, the error will still persist. My only point was that you would need to do something very different if you want kernels to link in the same translation unit as your main. And I [don't get duplicate symbol errors using this exact recipe on this exact code](https://pastebin.com/f2JUUtRp)


Swagger.json is displayed but the UI not

Question: I have ASP.Net 6.0 project and I have configured Swagger as follows:
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo {
        Title = "MyApi",
        Version = "v1"
    });
    c.CustomSchemaIds(x => x.FullName);
    c.ResolveConflictingActions(x => x.First());
});

and:
app.UseStaticFiles();

app.UseSwagger();
app.UseSwaggerUI(c =>
{
#if DEBUG
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyAPI");
#else
    c.SwaggerEndpoint("/MyApp/swagger/v1/swagger.json", "MyAPI");
#endif
    c.RoutePrefix = string.Empty;
});

The swagger.json is being served from the correct endpoint. But the UI endpoint returns 404 Not Found.
What is the correct way to show the UI?
Answer: After testing, I feel that this may be an option that needs to be optimized. Your code is correct, but now we encountered strange behavior.
So I analyzed, why does c.RoutePrefix = string.Empty; not take effect in VS2022 at startup? But when I directly access https://localhost:port, the function is normal.
This seems to be related to the settings in VS2022, so I found the settings below and found the settings for Url.

Then I delete the swagger value, and the issue was fixed.
Comment: I spent way too long looking for this, thanks!