问:
How can I implement, choose and rank the best continuous distribution based on given data?
I have done some research about finding the best continuous distribution based on given data and I have found several StackOverflow questions like the following:

Fitting Empirical Distribution

Finding Probability Distribution and Parameters for real data

In addition, from ResearchGate:

best goodness of fit test for a distribution - 1

best goodness of fit test for a distribution - 2

Furthermore, From Article:

Evaluating wind speed probability distribution models with a novel goodness of fit metric

Question 1:

However, from all of this research, I still can't decide which of the goodness of fit metric would help me to select the best distribution model for a given data. I have coded my approach for two statistical tests (Kolmogorov-Smirnov and Anderson-Darling) I am not sure if my approach is correct for these tests,

```<code>from statsmodels.stats.diagnostic import normal_ad as adnormtest
from statsmodels.stats.diagnostic import anderson_statistic as adtest
def get_hist(data, data_size):
    ## Used as input to the distribution function:
    #### General code:
    bins_formulas = ['auto', 'fd', 'scott', 'rice', 'sturges', 'doane', 'sqrt']
    bins = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))

    # Obtaining the histogram of data:
    # Hist = histogram(a=data, bins=bins, range=(min(data), max(data)), normed=True)
    Hist, bin_edges = histogram(a=data, bins=bins, range=(min(data), max(data)), density=True)
    bin_mid = (bin_edges + np.roll(bin_edges, -1))[:-1] / 2.0  # go from bin edges to bin middles
    return bin_mid

def get_best_distribution(data):
    dist_names = ['beta', 'burr', 'cauchy', 'chi2', 'erlang', 'expon', 'f', 'fisk', 'frechet_r', 'frechet_l', 'gamma',
              'genextreme', 'gengamma', 'genpareto', 'genlogistic', 'gumbel_r', 'gumbel_l', 'hypsecant', 'invgauss',
              'johnsonsu', 'laplace', 'levy', 'logistic', 'lognorm', 'loglaplace', 'maxwell', 'mielke', 'nakagami',
              'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'rayleigh', 'reciprocal', 'rice', 't',
              'triang', 'trapz', 'truncnorm', 'vonmises', 'weibull_min', 'weibull_max']
    dist_results = []
    params = {}
    for dist_name in dist_names:
        dist = getattr(st, dist_name)
        param = dist.fit(data)
        params[dist_name] = param

        # Applying the Kolmogorov-Smirnov test
        D, p = st.kstest(data, dist_name, args=param)
        print("p value for " + dist_name + " = " + str(p))
        dist_results.append((dist_name, p))

        # Applying the Anderson-Darling test:
        D_ad = adtest(x=data, dist=dist, fit=False, params=param)
        print("Anderson-Darling test Statistics value for " + dist_name + " = " + str(D_ad))
        dist_ad_results.append((dist_name, D_ad))

        # Applying the Anderson-Darling test:
        D_ad, p_ad = adnormtest(x=data)
        print("Anderson-Darling test Statistics value for " + dist_name + "  = " + str(D_ad))
        print("p value (AD test) for  = " + str(p_ad))
        dist_ad_results.append((dist_name, p_ad))

    # select the best fitted distribution
    best_dist, best_p = (max(dist_results, key=lambda item: item[1]))
    # store the name of the best fit and its p value

    print("Best fitting distribution: " + str(best_dist))
    print("Best p value: " + str(best_p))
    print("Parameters for the best fit: " + str(params[best_dist]))
    return best_dist, best_p, params[best_dist]

def make_pdf(dist, params, size):
    """Generate distributions's Probability Distribution Function """

    # Separate parts of parameters
    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]

    # Get sane start and end points of distribution
    start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale)
    end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.99, loc=loc, scale=scale)

    # Build PDF and turn into pandas Series
    x = np.linspace(start, end, size)
    y = dist.pdf(x, loc=loc, scale=scale, *arg)
    pdf = pd.Series(y, x)
    return pdf, x, y
</code>```

Question 2:

Also, I want to know how can I can create a table-like structure that would contain all the goodness-to-fit tests like:

Chi-Squared test

AIC

BIC

BICc

R-squared

Kolmogorov-Smirnov

Anderson-Darling

with ranking like in the following photo?

Side question:

I ran the above code to my data and it keeps on giving me the most common distribution is:

```<code>Accessing PDF using the given data list:
p value for beta = 0.9999999998034483
Best fitting distribution: beta
Best p value: 0.9999999998034483
Parameters for the best fit: (0.9509290548145051, 0.9040404230936319, -1.0539119566209405, 2.053911956620941)
</code>```

But, if I observed the histogram, beta distribution does not go well with my data. What could be the reason for this error?

Edit 1:

I managed to redesign the get_best_disfribution function and got an idea of using dataframe as to print the test statistical results into the following code, so, based on my previous question, how can I do the ranking into the dataframe (same as the photo)?

Code:

```<code>def get_best_distribution_3(data, method, plot=False):
    dist_names = ['alpha', 'anglit', 'arcsine', 'beta', 'betaprime', 'bradford', 'burr', 'cauchy', 'chi', 'chi2', 'cosine', 'dgamma', 'dweibull', 'erlang', 'expon', 'exponweib', 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'frechet_r', 'frechet_l', 'genlogistic', 'genpareto', 'genexpon', 'genextreme', 'gausshyper', 'gamma', 'gengamma', 'genhalflogistic', 'gilbrat',  'gompertz', 'gumbel_r', 'gumbel_l', 'halfcauchy', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb', 'johnsonsu', 'ksone', 'kstwobign', 'laplace', 'logistic', 'loggamma', 'loglaplace', 'lognorm', 'lomax', 'maxwell', 'mielke', 'moyal', 'nakagami', 'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rdist', 'reciprocal', 'rayleigh', 'rice', 'recipinvgauss', 'semicircular', 't', 'triang', 'truncexpon', 'truncnorm', 'tukeylambda', 'uniform', 'vonmises', 'wald', 'weibull_min', 'weibull_max', 'wrapcauchy']

    # Applying the Goodness-to-fit tests to select the best distribution that fits the data:
    dist_results = []
    dist_IC_results = []
    params = {}
    params_IC = {}
    params_SSE = {}
    chi_square = []

    # Best holders
    best_distribution = st.norm
    best_params = (0.0, 1.0)
    best_r2 = np.inf
    best_sse = np.inf

    # Set up 50 bins for chi-square test
    # Observed data will be approximately evenly distrubuted aross all bins
    percentile_bins = np.linspace(0, 100, 51)
    percentile_cutoffs = np.percentile(data, percentile_bins)
    observed_frequency, bins = (np.histogram(data, bins=percentile_cutoffs))
    cum_observed_frequency = np.cumsum(observed_frequency)
    size = data

    for dist_name in dist_names:
        dist = getattr(st, dist_name)
        param = dist.fit(data)
        params[dist_name] = param
        N_len = len(list(data))

        # Obtaining the histogram:
        Hist_data, bin_data = make_hist(data=data)

        # fit dist to data
        params_dist = dist.fit(data)

        # Separate parts of parameters
        arg = params_dist[:-2]
        loc = params_dist[-2]
        scale = params_dist[-1]

        # Calculate fitted PDF and error with fit in distribution
        pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)

########################################################################################################################
######################################## Sum of Square Error (SSE) test ################################################
########################################################################################################################
        # Applying SSE:
        sse = np.sum(np.power(Hist_data - pdf, 2.0))

        # identify if this distribution is better
        if best_sse > sse > 0:
            best_distribution = dist
            best_sse_val = sse

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
##################################################### R Square (R^2) test ##############################################
########################################################################################################################
        # Applying R^2:
        r2 = compute_r2_test(y_true=Hist_data, y_predicted=pdf)

        # identify if this distribution is better
        if best_r2 > r2 > 0:
            best_distribution = dist
            best_r2_val = r2

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
######################################## Information Criteria (IC) test ################################################
########################################################################################################################
        # Obtaining the log of the pdf:
        loglik = np.sum(dist.logpdf(bin_data, *params_dist))
        k = len(params_dist[:])
        n = len(data)
        aic = 2 * k - 2 * loglik
        bic = n * np.log(sse / n) + k * np.log(n)
        dist_IC_results.append((dist_name, aic))
        # dist_IC_results.append((dist_name, bic))

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
################################################ Chi-Square (Chi^2) test ###############################################
########################################################################################################################
        # Get expected counts in percentile bins
        # This is based on a 'cumulative distrubution function' (cdf)
        cdf_fitted = dist.cdf(percentile_cutoffs, *arg, loc=loc, scale=scale)
        expected_frequency = []
        for bin in range(len(percentile_bins) - 1):
            expected_cdf_area = cdf_fitted[bin + 1] - cdf_fitted[bin]
            expected_frequency.append(expected_cdf_area)

        # calculate chi-squared
        expected_frequency = np.array(expected_frequency) * size
        cum_expected_frequency = np.cumsum(expected_frequency)
        ss = sum(((cum_expected_frequency - cum_observed_frequency) ** 2) / cum_observed_frequency)
        chi_square.append(ss)

        # Applying the Chi-Square test:
        # D, p = scipy.stats.chisquare(f_obs=pdf, f_exp=Hist_data)
        # print("Chi-Square test Statistics value for " + dist_name + " = " + str(D))
        print("p value for " + dist_name + " = " + str(chi_square))
        dist_results.append((dist_name, chi_square))

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
########################################## Kolmogorov-Smirnov (KS) test ################################################
########################################################################################################################
        # Applying the Kolmogorov-Smirnov test:
        D, p = st.kstest(data, dist_name, args=param)
        # D, p = st.kstest(data, dist_name, args=param, N=N_len, alternative='greater')
        # print("Kolmogorov-Smirnov test Statistics value for " + dist_name + " = " + str(D))
        print("p value for " + dist_name + " = " + str(p))
        dist_results.append((dist_name, p))

########################################################################################################################
########################################################################################################################
########################################################################################################################

    print('\n################################ Sum of Square Error test parameters ####################################')
    best_dist = best_distribution
    print("Best fitting distribution (SSE test) :" + str(best_dist))
    print("Best SSE value (SSE test) :" + str(best_sse_val))
    print("Parameters for the best fit (SSE test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    print('\n############################## R Square test parameters ################################################')
    best_dist = best_distribution
    print("Best fitting distribution (R^2 test) :" + str(best_dist))
    print("Best R^2 value (R^2 test) :" + str(best_r2_val))
    print("Parameters for the best fit (R^2 test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    print('\n############################ Information Criteria (IC) test parameters ##################################')
    # select the best fitted distribution and store the name of the best fit and its IC value
    best_dist, best_ic = (min(dist_IC_results, key=lambda item: item[1]))
    print("Best fitting distribution (IC test) :" + str(best_dist))
    print("Best IC value (IC test) :" + str(best_ic))
    print("Parameters for the best fit (IC test) :" + str(params[best_dist]))
    print( '########################################################################################################\n')

    print('\n#################################### Chi-Square test parameters #######################################')
    # select the best fitted distribution and store the name of the best fit and its p value
    best_dist, best_chi_val = (min(dist_results, key=lambda item: item[1]))
    print("Best fitting distribution (Chi^2 test) :" + str(best_dist))
    print("Best p value (Chi^2 test) :" + str(best_chi_val))
    print("Parameters for the best fit (Chi^2 test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    print('\n################################ Kolmogorov-Smirnov test parameters #####################################')
    # select the best fitted distribution and store the name of the best fit and its p value
    best_dist, best_p = (max(dist_results, key=lambda item: item[1]))
    print("Best fitting distribution (KS test) :" + str(best_dist))
    print("Best p value (KS test) :" + str(best_p))
    print("Parameters for the best fit (KS test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    # Collate results and sort by goodness of fit (best at top)
    results = pd.DataFrame()
    results['Distribution'] = dist_names
    results['SSE'] = sse
    results['chi_square'] = chi_square
    results['R^2_value'] = r2
    results['p_value'] = p
    results['AIC_value'] = aic
    results['BIC_value'] = bic
    results.sort_values(['chi_square'], inplace=True)

    # Plotting the distribution with histogram:
    if plot:
        bins_val = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))
        plt.hist(x=data, bins=bins_val, range=(min(data), max(data)), density=True)
        # pylab.hist(x=data, bins=bins_val, range=(min(data), max(data)))
        best_param = params[best_dist]
        best_dist_p = getattr(st, best_dist)
        pdf, x_axis_pdf, y_axis_pdf = make_pdf(dist=best_dist_p, params=best_param, size=len(data))
        plt.plot(x_axis_pdf, y_axis_pdf, color='red', label='Best dist ={0}'.format(best_dist))
        plt.legend()
        plt.title('Histogram and Distribution plot of data')
        # plt.show()
        plt.show(block=False)
        plt.pause(5)  # Pauses the program for 5 seconds
        plt.close('all')

    return best_dist, _, params[best_dist]
</code>```

答:
I managed to redesign the distribution function with selection of which Goodness-to-fit test that you need:</p>

```<code>import numpy as np
import pandas as pd
import scipy.stats as st
import matplotlib.pyplot as plt
import pylab

def make_hist(data):
    #### General code:
    bins_formulas = ['auto', 'fd', 'scott', 'rice', 'sturges', 'doane', 'sqrt']
    bins = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))
    # print('Bin value = ', bins)

    # Obtaining the histogram of data:
    Hist, bin_edges = histogram(a=data, bins=bins, range=(min(data), max(data)), density=True)
    bin_mid = (bin_edges + np.roll(bin_edges, -1))[:-1] / 2.0  # go from bin edges to bin middles
    return Hist, bin_mid

def make_pdf(dist, params, size):
    """Generate distributions's Probability Distribution Function """

    # Separate parts of parameters
    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]

    # Get sane start and end points of distribution
    start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale)
    end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.99, loc=loc, scale=scale)

    # Build PDF and turn into pandas Series
    x = np.linspace(start, end, size)
    y = dist.pdf(x, loc=loc, scale=scale, *arg)
    pdf = pd.Series(y, x)
    return pdf, x, y

def compute_r2_test(y_true, y_predicted):
    sse = sum((y_true - y_predicted)**2)
    tse = (len(y_true) - 1) * np.var(y_true, ddof=1)
    r2_score = 1 - (sse / tse)
    return r2_score, sse, tse

def get_best_distribution_2(data, method, plot=False):
    dist_names = ['alpha', 'anglit', 'arcsine', 'beta', 'betaprime', 'bradford', 'burr', 'cauchy', 'chi', 'chi2', 'cosine', 'dgamma', 'dweibull', 'erlang', 'expon', 'exponweib', 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'frechet_r', 'frechet_l', 'genlogistic', 'genpareto', 'genexpon', 'genextreme', 'gausshyper', 'gamma', 'gengamma', 'genhalflogistic', 'gilbrat',  'gompertz', 'gumbel_r', 'gumbel_l', 'halfcauchy', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb', 'johnsonsu', 'ksone', 'kstwobign', 'laplace', 'logistic', 'loggamma', 'loglaplace', 'lognorm', 'lomax', 'maxwell', 'mielke', 'moyal', 'nakagami', 'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rdist', 'reciprocal', 'rayleigh', 'rice', 'recipinvgauss', 'semicircular', 't', 'triang', 'truncexpon', 'truncnorm', 'tukeylambda', 'uniform', 'vonmises', 'wald', 'weibull_min', 'weibull_max', 'wrapcauchy']

    # Applying the Goodness-to-fit tests to select the best distribution that fits the data:
    dist_results = []
    dist_IC_results = []
    params = {}
    params_IC = {}
    params_SSE = {}

    if method == 'sse':
########################################################################################################################
######################################## Sum of Square Error (SSE) test ################################################
########################################################################################################################
        # Best holders
        best_distribution = st.norm
        best_params = (0.0, 1.0)
        best_sse = np.inf

        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param
            N_len = len(list(data))
            # Obtaining the histogram:
            Hist_data, bin_data = make_hist(data=data)

            # fit dist to data
            params_dist = dist.fit(data)

            # Separate parts of parameters
            arg = params_dist[:-2]
            loc = params_dist[-2]
            scale = params_dist[-1]

            # Calculate fitted PDF and error with fit in distribution
            pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)
            sse = np.sum(np.power(Hist_data - pdf, 2.0))

            # identify if this distribution is better
            if best_sse > sse > 0:
                best_distribution = dist
                best_params = params_dist
                best_stat_test_val = sse

        print('\n################################ Sum of Square Error test parameters #####################################')
        best_dist = best_distribution
        print("Best fitting distribution (SSE test) :" + str(best_dist))
        print("Best SSE value (SSE test) :" + str(best_stat_test_val))
        print("Parameters for the best fit (SSE test) :" + str(params[best_dist]))
        print('###########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'r2':
########################################################################################################################
##################################################### R Square (R^2) test ##############################################
########################################################################################################################
    # Best holders
    best_distribution = st.norm
    best_params = (0.0, 1.0)
    best_r2 = np.inf

    for dist_name in dist_names:
        dist = getattr(st, dist_name)
        param = dist.fit(data)
        params[dist_name] = param
        N_len = len(list(data))
        # Obtaining the histogram:
        Hist_data, bin_data = make_hist(data=data)

        # fit dist to data
        params_dist = dist.fit(data)

        # Separate parts of parameters
        arg = params_dist[:-2]
        loc = params_dist[-2]
        scale = params_dist[-1]

        # Calculate fitted PDF and error with fit in distribution
        pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)
        r2 = compute_r2_test(y_true=Hist_data, y_predicted=pdf)

        # identify if this distribution is better
        if best_r2 > r2 > 0:
            best_distribution = dist
            best_params = params_dist
            best_stat_test_val = r2

    print('\n############################## R Square test parameters ###########################################')
    best_dist = best_distribution
    print("Best fitting distribution (R^2 test) :" + str(best_dist))
    print("Best R^2 value (R^2 test) :" + str(best_stat_test_val))
    print("Parameters for the best fit (R^2 test) :" + str(params[best_dist]))
    print('#####################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'ic':
########################################################################################################################
######################################## Information Criteria (IC) test ################################################
########################################################################################################################
        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param
            N_len = len(list(data))

            # Obtaining the histogram:
            Hist_data, bin_data = make_hist(data=data)

            # fit dist to data
            params_dist = dist.fit(data)

            # Separate parts of parameters
            arg = params_dist[:-2]
            loc = params_dist[-2]
            scale = params_dist[-1]

            # Calculate fitted PDF and error with fit in distribution
            pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)
            sse = np.sum(np.power(Hist_data - pdf, 2.0))

            # Obtaining the log of the pdf:
            loglik = np.sum(dist.logpdf(bin_data, *params_dist))
            k = len(params_dist[:])
            n = len(data)
            aic = 2 * k - 2 * loglik
            bic = n * np.log(sse / n) + k * np.log(n)
            dist_IC_results.append((dist_name, aic))
            # dist_IC_results.append((dist_name, bic))

        # select the best fitted distribution and store the name of the best fit and its IC value
        best_dist, best_ic = (min(dist_IC_results, key=lambda item: item[1]))

        print('\n############################ Information Criteria (IC) test parameters ##################################')
        print("Best fitting distribution (IC test) :" + str(best_dist))
        print("Best IC value (IC test) :" + str(best_ic))
        print("Parameters for the best fit (IC test) :" + str(params[best_dist]))
        print('###########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'chi':
########################################################################################################################
################################################ Chi-Square (Chi^2) test ###############################################
########################################################################################################################
        # Set up 50 bins for chi-square test
        # Observed data will be approximately evenly distrubuted aross all bins
        percentile_bins = np.linspace(0,100,51)
        percentile_cutoffs = np.percentile(data, percentile_bins)
        observed_frequency, bins = (np.histogram(data, bins=percentile_cutoffs))
        cum_observed_frequency = np.cumsum(observed_frequency)

        chi_square = []
        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param

            # Obtaining the histogram:
            Hist_data, bin_data = make_hist(data=data)

            # fit dist to data
            params_dist = dist.fit(data)

            # Separate parts of parameters
            arg = params_dist[:-2]
            loc = params_dist[-2]
            scale = params_dist[-1]

            # Calculate fitted PDF and error with fit in distribution
            pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)

            # Get expected counts in percentile bins
            # This is based on a 'cumulative distrubution function' (cdf)
            cdf_fitted = dist.cdf(percentile_cutoffs, *arg, loc=loc, scale=scale)
            expected_frequency = []
            for bin in range(len(percentile_bins) - 1):
                expected_cdf_area = cdf_fitted[bin + 1] - cdf_fitted[bin]
                expected_frequency.append(expected_cdf_area)

            # calculate chi-squared
            expected_frequency = np.array(expected_frequency) * size
            cum_expected_frequency = np.cumsum(expected_frequency)
            ss = sum(((cum_expected_frequency - cum_observed_frequency) ** 2) / cum_observed_frequency)
            chi_square.append(ss)

            # Applying the Chi-Square test:
            # D, p = scipy.stats.chisquare(f_obs=pdf, f_exp=Hist_data)
            # print("Chi-Square test Statistics value for " + dist_name + " = " + str(D))
            print("p value for " + dist_name + " = " + str(chi_square))
            dist_results.append((dist_name, chi_square))

        # select the best fitted distribution and store the name of the best fit and its p value
        best_dist, best_stat_test_val = (min(dist_results, key=lambda item: item[1]))

        print('\n#################################### Chi-Square test parameters #######################################')
        print("Best fitting distribution (Chi^2 test) :" + str(best_dist))
        print("Best p value (Chi^2 test) :" + str(best_stat_test_val))
        print("Parameters for the best fit (Chi^2 test) :" + str(params[best_dist]))
        print('#########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'ks':
########################################################################################################################
########################################## Kolmogorov-Smirnov (KS) test ################################################
########################################################################################################################
        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param

            # Applying the Kolmogorov-Smirnov test:
            D, p = st.kstest(data, dist_name, args=param)
            # D, p = st.kstest(data, dist_name, args=param, N=N_len, alternative='greater')
            # print("Kolmogorov-Smirnov test Statistics value for " + dist_name + " = " + str(D))
            print("p value for " + dist_name + " = " + str(p))
            dist_results.append((dist_name, p))

        # select the best fitted distribution and store the name of the best fit and its p value
        best_dist, best_stat_test_val = (max(dist_results, key=lambda item: item[1]))

        print('\n################################ Kolmogorov-Smirnov test parameters #####################################')
        print("Best fitting distribution (KS test) :" + str(best_dist))
        print("Best p value (KS test) :" + str(best_stat_test_val))
        print("Parameters for the best fit (KS test) :" + str(params[best_dist]))
        print('###########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    # Collate results and sort by goodness of fit (best at top)
    results = pd.DataFrame()
    results['Distribution'] = dist_names
    results['chi_square'] = chi_square
    # results['p_value'] = p_values
    results.sort_values(['chi_square'], inplace=True)

    # Plotting the distribution with histogram:
    if plot:
        bins_val = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))
        plt.hist(x=data, bins=bins_val, range=(min(data), max(data)), density=True)
        # pylab.hist(x=data, bins=bins_val, range=(min(data), max(data)))
        best_param = params[best_dist]
        best_dist_p = getattr(st, best_dist)
        pdf, x_axis_pdf, y_axis_pdf = make_pdf(dist=best_dist_p, params=best_param, size=len(data))
        plt.plot(x_axis_pdf, y_axis_pdf, color='red', label='Best dist ={0}'.format(best_dist))
        plt.legend()
        plt.title('Histogram and Distribution plot of data')
        # plt.show()
        plt.show(block=False)
        plt.pause(5)  # Pauses the program for 5 seconds
        plt.close('all')

    return best_dist, best_stat_test_val, params[best_dist]
</code>```

Body:
I have done some research about finding the best continuous distribution based on given data and I have found several StackOverflow questions like the following:

Fitting Empirical Distribution

Finding Probability Distribution and Parameters for real data

In addition, from ResearchGate:

best goodness of fit test for a distribution - 1

best goodness of fit test for a distribution - 2

Furthermore, From Article:

Evaluating wind speed probability distribution models with a novel goodness of fit metric

Question 1:

However, from all of this research, I still can't decide which of the goodness of fit metric would help me to select the best distribution model for a given data. I have coded my approach for two statistical tests (Kolmogorov-Smirnov and Anderson-Darling) I am not sure if my approach is correct for these tests,

from statsmodels.stats.diagnostic import normal_ad as adnormtest
from statsmodels.stats.diagnostic import anderson_statistic as adtest
def get_hist(data, data_size):
    ## Used as input to the distribution function:
    #### General code:
    bins_formulas = ['auto', 'fd', 'scott', 'rice', 'sturges', 'doane', 'sqrt']
    bins = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))

    # Obtaining the histogram of data:
    # Hist = histogram(a=data, bins=bins, range=(min(data), max(data)), normed=True)
    Hist, bin_edges = histogram(a=data, bins=bins, range=(min(data), max(data)), density=True)
    bin_mid = (bin_edges + np.roll(bin_edges, -1))[:-1] / 2.0  # go from bin edges to bin middles
    return bin_mid

def get_best_distribution(data):
    dist_names = ['beta', 'burr', 'cauchy', 'chi2', 'erlang', 'expon', 'f', 'fisk', 'frechet_r', 'frechet_l', 'gamma',
              'genextreme', 'gengamma', 'genpareto', 'genlogistic', 'gumbel_r', 'gumbel_l', 'hypsecant', 'invgauss',
              'johnsonsu', 'laplace', 'levy', 'logistic', 'lognorm', 'loglaplace', 'maxwell', 'mielke', 'nakagami',
              'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'rayleigh', 'reciprocal', 'rice', 't',
              'triang', 'trapz', 'truncnorm', 'vonmises', 'weibull_min', 'weibull_max']
    dist_results = []
    params = {}
    for dist_name in dist_names:
        dist = getattr(st, dist_name)
        param = dist.fit(data)
        params[dist_name] = param

        # Applying the Kolmogorov-Smirnov test
        D, p = st.kstest(data, dist_name, args=param)
        print("p value for " + dist_name + " = " + str(p))
        dist_results.append((dist_name, p))

        # Applying the Anderson-Darling test:
        D_ad = adtest(x=data, dist=dist, fit=False, params=param)
        print("Anderson-Darling test Statistics value for " + dist_name + " = " + str(D_ad))
        dist_ad_results.append((dist_name, D_ad))

        # Applying the Anderson-Darling test:
        D_ad, p_ad = adnormtest(x=data)
        print("Anderson-Darling test Statistics value for " + dist_name + "  = " + str(D_ad))
        print("p value (AD test) for  = " + str(p_ad))
        dist_ad_results.append((dist_name, p_ad))

    # select the best fitted distribution
    best_dist, best_p = (max(dist_results, key=lambda item: item[1]))
    # store the name of the best fit and its p value

    print("Best fitting distribution: " + str(best_dist))
    print("Best p value: " + str(best_p))
    print("Parameters for the best fit: " + str(params[best_dist]))
    return best_dist, best_p, params[best_dist]

def make_pdf(dist, params, size):
    """Generate distributions's Probability Distribution Function """

    # Separate parts of parameters
    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]

    # Get sane start and end points of distribution
    start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale)
    end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.99, loc=loc, scale=scale)

    # Build PDF and turn into pandas Series
    x = np.linspace(start, end, size)
    y = dist.pdf(x, loc=loc, scale=scale, *arg)
    pdf = pd.Series(y, x)
    return pdf, x, y

Question 2:

Also, I want to know how can I can create a table-like structure that would contain all the goodness-to-fit tests like:

Chi-Squared test

AIC

BIC

BICc

R-squared

Kolmogorov-Smirnov

Anderson-Darling

with ranking like in the following photo?

Side question:

I ran the above code to my data and it keeps on giving me the most common distribution is:

Accessing PDF using the given data list:
p value for beta = 0.9999999998034483
Best fitting distribution: beta
Best p value: 0.9999999998034483
Parameters for the best fit: (0.9509290548145051, 0.9040404230936319, -1.0539119566209405, 2.053911956620941)

But, if I observed the histogram, beta distribution does not go well with my data. What could be the reason for this error?

Edit 1:

I managed to redesign the get_best_disfribution function and got an idea of using dataframe as to print the test statistical results into the following code, so, based on my previous question, how can I do the ranking into the dataframe (same as the photo)?

Code:

def get_best_distribution_3(data, method, plot=False):
    dist_names = ['alpha', 'anglit', 'arcsine', 'beta', 'betaprime', 'bradford', 'burr', 'cauchy', 'chi', 'chi2', 'cosine', 'dgamma', 'dweibull', 'erlang', 'expon', 'exponweib', 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'frechet_r', 'frechet_l', 'genlogistic', 'genpareto', 'genexpon', 'genextreme', 'gausshyper', 'gamma', 'gengamma', 'genhalflogistic', 'gilbrat',  'gompertz', 'gumbel_r', 'gumbel_l', 'halfcauchy', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb', 'johnsonsu', 'ksone', 'kstwobign', 'laplace', 'logistic', 'loggamma', 'loglaplace', 'lognorm', 'lomax', 'maxwell', 'mielke', 'moyal', 'nakagami', 'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rdist', 'reciprocal', 'rayleigh', 'rice', 'recipinvgauss', 'semicircular', 't', 'triang', 'truncexpon', 'truncnorm', 'tukeylambda', 'uniform', 'vonmises', 'wald', 'weibull_min', 'weibull_max', 'wrapcauchy']

    # Applying the Goodness-to-fit tests to select the best distribution that fits the data:
    dist_results = []
    dist_IC_results = []
    params = {}
    params_IC = {}
    params_SSE = {}
    chi_square = []

    # Best holders
    best_distribution = st.norm
    best_params = (0.0, 1.0)
    best_r2 = np.inf
    best_sse = np.inf

    # Set up 50 bins for chi-square test
    # Observed data will be approximately evenly distrubuted aross all bins
    percentile_bins = np.linspace(0, 100, 51)
    percentile_cutoffs = np.percentile(data, percentile_bins)
    observed_frequency, bins = (np.histogram(data, bins=percentile_cutoffs))
    cum_observed_frequency = np.cumsum(observed_frequency)
    size = data

    for dist_name in dist_names:
        dist = getattr(st, dist_name)
        param = dist.fit(data)
        params[dist_name] = param
        N_len = len(list(data))

        # Obtaining the histogram:
        Hist_data, bin_data = make_hist(data=data)

        # fit dist to data
        params_dist = dist.fit(data)

        # Separate parts of parameters
        arg = params_dist[:-2]
        loc = params_dist[-2]
        scale = params_dist[-1]

        # Calculate fitted PDF and error with fit in distribution
        pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)

########################################################################################################################
######################################## Sum of Square Error (SSE) test ################################################
########################################################################################################################
        # Applying SSE:
        sse = np.sum(np.power(Hist_data - pdf, 2.0))

        # identify if this distribution is better
        if best_sse > sse > 0:
            best_distribution = dist
            best_sse_val = sse

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
##################################################### R Square (R^2) test ##############################################
########################################################################################################################
        # Applying R^2:
        r2 = compute_r2_test(y_true=Hist_data, y_predicted=pdf)

        # identify if this distribution is better
        if best_r2 > r2 > 0:
            best_distribution = dist
            best_r2_val = r2

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
######################################## Information Criteria (IC) test ################################################
########################################################################################################################
        # Obtaining the log of the pdf:
        loglik = np.sum(dist.logpdf(bin_data, *params_dist))
        k = len(params_dist[:])
        n = len(data)
        aic = 2 * k - 2 * loglik
        bic = n * np.log(sse / n) + k * np.log(n)
        dist_IC_results.append((dist_name, aic))
        # dist_IC_results.append((dist_name, bic))

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
################################################ Chi-Square (Chi^2) test ###############################################
########################################################################################################################
        # Get expected counts in percentile bins
        # This is based on a 'cumulative distrubution function' (cdf)
        cdf_fitted = dist.cdf(percentile_cutoffs, *arg, loc=loc, scale=scale)
        expected_frequency = []
        for bin in range(len(percentile_bins) - 1):
            expected_cdf_area = cdf_fitted[bin + 1] - cdf_fitted[bin]
            expected_frequency.append(expected_cdf_area)

        # calculate chi-squared
        expected_frequency = np.array(expected_frequency) * size
        cum_expected_frequency = np.cumsum(expected_frequency)
        ss = sum(((cum_expected_frequency - cum_observed_frequency) ** 2) / cum_observed_frequency)
        chi_square.append(ss)

        # Applying the Chi-Square test:
        # D, p = scipy.stats.chisquare(f_obs=pdf, f_exp=Hist_data)
        # print("Chi-Square test Statistics value for " + dist_name + " = " + str(D))
        print("p value for " + dist_name + " = " + str(chi_square))
        dist_results.append((dist_name, chi_square))

########################################################################################################################
########################################################################################################################
########################################################################################################################

########################################################################################################################
########################################## Kolmogorov-Smirnov (KS) test ################################################
########################################################################################################################
        # Applying the Kolmogorov-Smirnov test:
        D, p = st.kstest(data, dist_name, args=param)
        # D, p = st.kstest(data, dist_name, args=param, N=N_len, alternative='greater')
        # print("Kolmogorov-Smirnov test Statistics value for " + dist_name + " = " + str(D))
        print("p value for " + dist_name + " = " + str(p))
        dist_results.append((dist_name, p))

########################################################################################################################
########################################################################################################################
########################################################################################################################

    print('\n################################ Sum of Square Error test parameters ####################################')
    best_dist = best_distribution
    print("Best fitting distribution (SSE test) :" + str(best_dist))
    print("Best SSE value (SSE test) :" + str(best_sse_val))
    print("Parameters for the best fit (SSE test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    print('\n############################## R Square test parameters ################################################')
    best_dist = best_distribution
    print("Best fitting distribution (R^2 test) :" + str(best_dist))
    print("Best R^2 value (R^2 test) :" + str(best_r2_val))
    print("Parameters for the best fit (R^2 test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    print('\n############################ Information Criteria (IC) test parameters ##################################')
    # select the best fitted distribution and store the name of the best fit and its IC value
    best_dist, best_ic = (min(dist_IC_results, key=lambda item: item[1]))
    print("Best fitting distribution (IC test) :" + str(best_dist))
    print("Best IC value (IC test) :" + str(best_ic))
    print("Parameters for the best fit (IC test) :" + str(params[best_dist]))
    print( '########################################################################################################\n')

    print('\n#################################### Chi-Square test parameters #######################################')
    # select the best fitted distribution and store the name of the best fit and its p value
    best_dist, best_chi_val = (min(dist_results, key=lambda item: item[1]))
    print("Best fitting distribution (Chi^2 test) :" + str(best_dist))
    print("Best p value (Chi^2 test) :" + str(best_chi_val))
    print("Parameters for the best fit (Chi^2 test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    print('\n################################ Kolmogorov-Smirnov test parameters #####################################')
    # select the best fitted distribution and store the name of the best fit and its p value
    best_dist, best_p = (max(dist_results, key=lambda item: item[1]))
    print("Best fitting distribution (KS test) :" + str(best_dist))
    print("Best p value (KS test) :" + str(best_p))
    print("Parameters for the best fit (KS test) :" + str(params[best_dist]))
    print('#########################################################################################################\n')

    # Collate results and sort by goodness of fit (best at top)
    results = pd.DataFrame()
    results['Distribution'] = dist_names
    results['SSE'] = sse
    results['chi_square'] = chi_square
    results['R^2_value'] = r2
    results['p_value'] = p
    results['AIC_value'] = aic
    results['BIC_value'] = bic
    results.sort_values(['chi_square'], inplace=True)

    # Plotting the distribution with histogram:
    if plot:
        bins_val = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))
        plt.hist(x=data, bins=bins_val, range=(min(data), max(data)), density=True)
        # pylab.hist(x=data, bins=bins_val, range=(min(data), max(data)))
        best_param = params[best_dist]
        best_dist_p = getattr(st, best_dist)
        pdf, x_axis_pdf, y_axis_pdf = make_pdf(dist=best_dist_p, params=best_param, size=len(data))
        plt.plot(x_axis_pdf, y_axis_pdf, color='red', label='Best dist ={0}'.format(best_dist))
        plt.legend()
        plt.title('Histogram and Distribution plot of data')
        # plt.show()
        plt.show(block=False)
        plt.pause(5)  # Pauses the program for 5 seconds
        plt.close('all')

    return best_dist, _, params[best_dist]

Body:
I managed to redesign the distribution function with selection of which Goodness-to-fit test that you need:

import numpy as np
import pandas as pd
import scipy.stats as st
import matplotlib.pyplot as plt
import pylab

def make_hist(data):
    #### General code:
    bins_formulas = ['auto', 'fd', 'scott', 'rice', 'sturges', 'doane', 'sqrt']
    bins = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))
    # print('Bin value = ', bins)

    # Obtaining the histogram of data:
    Hist, bin_edges = histogram(a=data, bins=bins, range=(min(data), max(data)), density=True)
    bin_mid = (bin_edges + np.roll(bin_edges, -1))[:-1] / 2.0  # go from bin edges to bin middles
    return Hist, bin_mid

def make_pdf(dist, params, size):
    """Generate distributions's Probability Distribution Function """

    # Separate parts of parameters
    arg = params[:-2]
    loc = params[-2]
    scale = params[-1]

    # Get sane start and end points of distribution
    start = dist.ppf(0.01, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.01, loc=loc, scale=scale)
    end = dist.ppf(0.99, *arg, loc=loc, scale=scale) if arg else dist.ppf(0.99, loc=loc, scale=scale)

    # Build PDF and turn into pandas Series
    x = np.linspace(start, end, size)
    y = dist.pdf(x, loc=loc, scale=scale, *arg)
    pdf = pd.Series(y, x)
    return pdf, x, y

def compute_r2_test(y_true, y_predicted):
    sse = sum((y_true - y_predicted)**2)
    tse = (len(y_true) - 1) * np.var(y_true, ddof=1)
    r2_score = 1 - (sse / tse)
    return r2_score, sse, tse

def get_best_distribution_2(data, method, plot=False):
    dist_names = ['alpha', 'anglit', 'arcsine', 'beta', 'betaprime', 'bradford', 'burr', 'cauchy', 'chi', 'chi2', 'cosine', 'dgamma', 'dweibull', 'erlang', 'expon', 'exponweib', 'exponpow', 'f', 'fatiguelife', 'fisk', 'foldcauchy', 'foldnorm', 'frechet_r', 'frechet_l', 'genlogistic', 'genpareto', 'genexpon', 'genextreme', 'gausshyper', 'gamma', 'gengamma', 'genhalflogistic', 'gilbrat',  'gompertz', 'gumbel_r', 'gumbel_l', 'halfcauchy', 'halflogistic', 'halfnorm', 'hypsecant', 'invgamma', 'invgauss', 'invweibull', 'johnsonsb', 'johnsonsu', 'ksone', 'kstwobign', 'laplace', 'logistic', 'loggamma', 'loglaplace', 'lognorm', 'lomax', 'maxwell', 'mielke', 'moyal', 'nakagami', 'ncx2', 'ncf', 'nct', 'norm', 'pareto', 'pearson3', 'powerlaw', 'powerlognorm', 'powernorm', 'rdist', 'reciprocal', 'rayleigh', 'rice', 'recipinvgauss', 'semicircular', 't', 'triang', 'truncexpon', 'truncnorm', 'tukeylambda', 'uniform', 'vonmises', 'wald', 'weibull_min', 'weibull_max', 'wrapcauchy']

    # Applying the Goodness-to-fit tests to select the best distribution that fits the data:
    dist_results = []
    dist_IC_results = []
    params = {}
    params_IC = {}
    params_SSE = {}

    if method == 'sse':
########################################################################################################################
######################################## Sum of Square Error (SSE) test ################################################
########################################################################################################################
        # Best holders
        best_distribution = st.norm
        best_params = (0.0, 1.0)
        best_sse = np.inf

        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param
            N_len = len(list(data))
            # Obtaining the histogram:
            Hist_data, bin_data = make_hist(data=data)

            # fit dist to data
            params_dist = dist.fit(data)

            # Separate parts of parameters
            arg = params_dist[:-2]
            loc = params_dist[-2]
            scale = params_dist[-1]

            # Calculate fitted PDF and error with fit in distribution
            pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)
            sse = np.sum(np.power(Hist_data - pdf, 2.0))

            # identify if this distribution is better
            if best_sse > sse > 0:
                best_distribution = dist
                best_params = params_dist
                best_stat_test_val = sse

        print('\n################################ Sum of Square Error test parameters #####################################')
        best_dist = best_distribution
        print("Best fitting distribution (SSE test) :" + str(best_dist))
        print("Best SSE value (SSE test) :" + str(best_stat_test_val))
        print("Parameters for the best fit (SSE test) :" + str(params[best_dist]))
        print('###########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'r2':
########################################################################################################################
##################################################### R Square (R^2) test ##############################################
########################################################################################################################
    # Best holders
    best_distribution = st.norm
    best_params = (0.0, 1.0)
    best_r2 = np.inf

    for dist_name in dist_names:
        dist = getattr(st, dist_name)
        param = dist.fit(data)
        params[dist_name] = param
        N_len = len(list(data))
        # Obtaining the histogram:
        Hist_data, bin_data = make_hist(data=data)

        # fit dist to data
        params_dist = dist.fit(data)

        # Separate parts of parameters
        arg = params_dist[:-2]
        loc = params_dist[-2]
        scale = params_dist[-1]

        # Calculate fitted PDF and error with fit in distribution
        pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)
        r2 = compute_r2_test(y_true=Hist_data, y_predicted=pdf)

        # identify if this distribution is better
        if best_r2 > r2 > 0:
            best_distribution = dist
            best_params = params_dist
            best_stat_test_val = r2

    print('\n############################## R Square test parameters ###########################################')
    best_dist = best_distribution
    print("Best fitting distribution (R^2 test) :" + str(best_dist))
    print("Best R^2 value (R^2 test) :" + str(best_stat_test_val))
    print("Parameters for the best fit (R^2 test) :" + str(params[best_dist]))
    print('#####################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'ic':
########################################################################################################################
######################################## Information Criteria (IC) test ################################################
########################################################################################################################
        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param
            N_len = len(list(data))

            # Obtaining the histogram:
            Hist_data, bin_data = make_hist(data=data)

            # fit dist to data
            params_dist = dist.fit(data)

            # Separate parts of parameters
            arg = params_dist[:-2]
            loc = params_dist[-2]
            scale = params_dist[-1]

            # Calculate fitted PDF and error with fit in distribution
            pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)
            sse = np.sum(np.power(Hist_data - pdf, 2.0))

            # Obtaining the log of the pdf:
            loglik = np.sum(dist.logpdf(bin_data, *params_dist))
            k = len(params_dist[:])
            n = len(data)
            aic = 2 * k - 2 * loglik
            bic = n * np.log(sse / n) + k * np.log(n)
            dist_IC_results.append((dist_name, aic))
            # dist_IC_results.append((dist_name, bic))

        # select the best fitted distribution and store the name of the best fit and its IC value
        best_dist, best_ic = (min(dist_IC_results, key=lambda item: item[1]))

        print('\n############################ Information Criteria (IC) test parameters ##################################')
        print("Best fitting distribution (IC test) :" + str(best_dist))
        print("Best IC value (IC test) :" + str(best_ic))
        print("Parameters for the best fit (IC test) :" + str(params[best_dist]))
        print('###########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'chi':
########################################################################################################################
################################################ Chi-Square (Chi^2) test ###############################################
########################################################################################################################
        # Set up 50 bins for chi-square test
        # Observed data will be approximately evenly distrubuted aross all bins
        percentile_bins = np.linspace(0,100,51)
        percentile_cutoffs = np.percentile(data, percentile_bins)
        observed_frequency, bins = (np.histogram(data, bins=percentile_cutoffs))
        cum_observed_frequency = np.cumsum(observed_frequency)

        chi_square = []
        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param

            # Obtaining the histogram:
            Hist_data, bin_data = make_hist(data=data)

            # fit dist to data
            params_dist = dist.fit(data)

            # Separate parts of parameters
            arg = params_dist[:-2]
            loc = params_dist[-2]
            scale = params_dist[-1]

            # Calculate fitted PDF and error with fit in distribution
            pdf = dist.pdf(bin_data, loc=loc, scale=scale, *arg)

            # Get expected counts in percentile bins
            # This is based on a 'cumulative distrubution function' (cdf)
            cdf_fitted = dist.cdf(percentile_cutoffs, *arg, loc=loc, scale=scale)
            expected_frequency = []
            for bin in range(len(percentile_bins) - 1):
                expected_cdf_area = cdf_fitted[bin + 1] - cdf_fitted[bin]
                expected_frequency.append(expected_cdf_area)

            # calculate chi-squared
            expected_frequency = np.array(expected_frequency) * size
            cum_expected_frequency = np.cumsum(expected_frequency)
            ss = sum(((cum_expected_frequency - cum_observed_frequency) ** 2) / cum_observed_frequency)
            chi_square.append(ss)

            # Applying the Chi-Square test:
            # D, p = scipy.stats.chisquare(f_obs=pdf, f_exp=Hist_data)
            # print("Chi-Square test Statistics value for " + dist_name + " = " + str(D))
            print("p value for " + dist_name + " = " + str(chi_square))
            dist_results.append((dist_name, chi_square))

        # select the best fitted distribution and store the name of the best fit and its p value
        best_dist, best_stat_test_val = (min(dist_results, key=lambda item: item[1]))

        print('\n#################################### Chi-Square test parameters #######################################')
        print("Best fitting distribution (Chi^2 test) :" + str(best_dist))
        print("Best p value (Chi^2 test) :" + str(best_stat_test_val))
        print("Parameters for the best fit (Chi^2 test) :" + str(params[best_dist]))
        print('#########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    if method == 'ks':
########################################################################################################################
########################################## Kolmogorov-Smirnov (KS) test ################################################
########################################################################################################################
        for dist_name in dist_names:
            dist = getattr(st, dist_name)
            param = dist.fit(data)
            params[dist_name] = param

            # Applying the Kolmogorov-Smirnov test:
            D, p = st.kstest(data, dist_name, args=param)
            # D, p = st.kstest(data, dist_name, args=param, N=N_len, alternative='greater')
            # print("Kolmogorov-Smirnov test Statistics value for " + dist_name + " = " + str(D))
            print("p value for " + dist_name + " = " + str(p))
            dist_results.append((dist_name, p))

        # select the best fitted distribution and store the name of the best fit and its p value
        best_dist, best_stat_test_val = (max(dist_results, key=lambda item: item[1]))

        print('\n################################ Kolmogorov-Smirnov test parameters #####################################')
        print("Best fitting distribution (KS test) :" + str(best_dist))
        print("Best p value (KS test) :" + str(best_stat_test_val))
        print("Parameters for the best fit (KS test) :" + str(params[best_dist]))
        print('###########################################################################################################\n')

########################################################################################################################
########################################################################################################################
########################################################################################################################

    # Collate results and sort by goodness of fit (best at top)
    results = pd.DataFrame()
    results['Distribution'] = dist_names
    results['chi_square'] = chi_square
    # results['p_value'] = p_values
    results.sort_values(['chi_square'], inplace=True)

    # Plotting the distribution with histogram:
    if plot:
        bins_val = np.histogram_bin_edges(a=data, bins='fd', range=(min(data), max(data)))
        plt.hist(x=data, bins=bins_val, range=(min(data), max(data)), density=True)
        # pylab.hist(x=data, bins=bins_val, range=(min(data), max(data)))
        best_param = params[best_dist]
        best_dist_p = getattr(st, best_dist)
        pdf, x_axis_pdf, y_axis_pdf = make_pdf(dist=best_dist_p, params=best_param, size=len(data))
        plt.plot(x_axis_pdf, y_axis_pdf, color='red', label='Best dist ={0}'.format(best_dist))
        plt.legend()
        plt.title('Histogram and Distribution plot of data')
        # plt.show()
        plt.show(block=False)
        plt.pause(5)  # Pauses the program for 5 seconds
        plt.close('all')

    return best_dist, best_stat_test_val, params[best_dist]


来源: stackexchange

问:
MVC render partial view foreach inside a popup modal in another view
i have this foreach in my partial view and i want to render partial view inside a popup modal in another view every thing is rendered except the foreach so it doesn't bring the products from the database
here's the partial view code:

```<code>@model IEnumerable<InternetApp.Models.Cart>
<h2>this is my Partial view</h2>
<h1>@Html.DisplayNameFor(model => model.product.name)</h1>
@foreach (var item in Model)
{

    <h3>
        @Html.DisplayFor(modelItem => item.product.name)
    </h3>
    <h3>
        @Html.DisplayFor(modelItem => item.product.price)
    </h3>

}
</code>```

and this is how i render my partial view inside the modal in the other view:

```<code>        <div class="modal-body ">
            @Html.Partial("_ShowCart",new List<InternetApp.Models.Cart>())
        </div>
</code>```

why the foreach is not rendered and how should i solve it ?

答:
If the parent view has the same model, pass your Model into the @Html.Partial tag. Otherwise, if the parent view has the collection inside of it pass it like Model.CartItems, where CartItems is the name you gave the collection.

Example:

You have a page with a shopping cart (the view). In order to show users their shopping cart on the page, you query a database (or possibly local storage) inside your controller and use the view's model to transfer those shopping cart items to your view. However, your view also shows the users address information and other relevant e-cart things, so you want to put the shopping cart logic in it's own page (a partial view) - this is where you're at today.

```<code>// CartViewModel.cs

public class CartViewModel
{
    public IEnumerable<InternetApp.Models.Cart> CartItems { get; set; } // Your collection of cart items.
    // Other things pertaining to the user's cart.
}
</code>```

```<code>// CartController.cs
public ActionResult ViewCart(int userId)
{
   var viewModel = new ViewCartViewModel {
       CartItems = _database.CartItems.GetAllForUser(userId)
   }

   return View(viewModel); // Passing the model to the view.
}
</code>```

```<code><div class="modal-body ">
    @Html.Partial("_ShowCart", Model.CartItems) // Because you filled CartItems in the controller, it has items in it.
</div>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i have this foreach in my partial view and i want to render partial view inside a popup modal in another view every thing is rendered except the foreach so it doesn't bring the products from the database
here's the partial view code:

@model IEnumerable<InternetApp.Models.Cart>

this is my Partial view

@Html.DisplayNameFor(model => model.product.name)

@foreach (var item in Model)
{

        @Html.DisplayFor(modelItem => item.product.name)

        @Html.DisplayFor(modelItem => item.product.price)

}

and this is how i render my partial view inside the modal in the other view:

            @Html.Partial("_ShowCart",new List<InternetApp.Models.Cart>())

why the foreach is not rendered and how should i solve it ?

Body:
If the parent view has the same model, pass your Model into the @Html.Partial tag. Otherwise, if the parent view has the collection inside of it pass it like Model.CartItems, where CartItems is the name you gave the collection.

Example:

You have a page with a shopping cart (the view). In order to show users their shopping cart on the page, you query a database (or possibly local storage) inside your controller and use the view's model to transfer those shopping cart items to your view. However, your view also shows the users address information and other relevant e-cart things, so you want to put the shopping cart logic in it's own page (a partial view) - this is where you're at today.

// CartViewModel.cs

public class CartViewModel
{
    public IEnumerable<InternetApp.Models.Cart> CartItems { get; set; } // Your collection of cart items.
    // Other things pertaining to the user's cart.
}

// CartController.cs
public ActionResult ViewCart(int userId)
{
   var viewModel = new ViewCartViewModel {
       CartItems = _database.CartItems.GetAllForUser(userId)
   }

   return View(viewModel); // Passing the model to the view.
}

<div class="modal-body ">
    @Html.Partial("_ShowCart", Model.CartItems) // Because you filled CartItems in the controller, it has items in it.
</div>


问:
How to compare cell against a set of cells and get an associated value
I need to compare the date of a cell against a column that has multiple date and I see which one it matches and get the associated value. Here I put an image to explain myself better:

Column D is where I need to put the formula, which compares the dates in column A on sheet 1 with the dates in column A on sheet 2. If it matches, I need to multiply the values in column C on sheet 1 by the values in column B of sheet 2.

Here another image with an example to be clearer

I have a little idea that would be something like:

```<code>= YES (ERROR (MATCH (Sheet1! A4; Sheet2! A2: A32; 0)); Sheet1! C4 * X
</code>```

In the x it should go B3, but I don't know how to get that cell in the search above.

答:
Try this:

```<code>=VLOOKUP(A3,sheet2!A:B,2)*C3
</code>```

I have recreated your spreadsheets below.

Body:
I need to compare the date of a cell against a column that has multiple date and I see which one it matches and get the associated value. Here I put an image to explain myself better:

Column D is where I need to put the formula, which compares the dates in column A on sheet 1 with the dates in column A on sheet 2. If it matches, I need to multiply the values in column C on sheet 1 by the values in column B of sheet 2.

Here another image with an example to be clearer

I have a little idea that would be something like:

= YES (ERROR (MATCH (Sheet1! A4; Sheet2! A2: A32; 0)); Sheet1! C4 * X

In the x it should go B3, but I don't know how to get that cell in the search above.

Body:
Try this:

=VLOOKUP(A3,sheet2!A:B,2)*C3

I have recreated your spreadsheets below.


问:
How to properly configure websocket with springboot and reactjs?
I can establish a websocket connection with my springboot server but I can't access the endpoint from @MessageMapping when I'm trying to send a message. Here are my configurations:

```<code>@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/simulator")
            .setAllowedOrigins("http://myiphere:3000")
            .withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/endpoint");
    registry.setApplicationDestinationPrefixes("/app");
}
</code>```

And a simple controller :

```<code>@RestController
@RequestMapping("/api")
public class MyController {

 @MessageMapping("/hello/")
 @SendTo("/endpoint/greeting")
 public Greeting getCurrentLocation() {
     System.out.println("hello here");
     return GenericBuilder.of(Greeting::new)
                          .with(Greeting::setContent, "hello from server")
                          .build();
 }

}
</code>```

I'm using the socketjs-client library in ReactJS by following this tutorial :

```<code>import SockJS from "sockjs-client";
import Stomp from "stompjs";

let stompClient;

const connect = () => {
    const socket = new SockJS("http://myiphere:8081/simulator");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("Connected " + frame);
        stompClient.subscribe("http://myiphere:8081/endpoint/greeting", function (greeting) {
        console.log("hi" + JSON.parse(greeting.body).content);
        });
    });
};

const sendSomething = () => {
    stompClient.send("http://myiphere:8081/app/hello/", {});
};
</code>```

And some buttons with onClick events bound to the methods above. The connection is working, I'm getting "connected" messages in browser console but when I'm trying to click the button with sendSomething() I'm not getting anything in the browser's console nor server's console.

答:
Solved.

The problem was the absolute url path in the send() method.

P.S.: And I've been looking for an answer for this problem on many sites and found out that there is no need to use absolute path for subscribe() url.

P.P.S.: In case that someone else have these problems, look for extra / too. You have to be careful when you're setting the url. The pattern from JS should match the one from SpringBoot.

Body:
I can establish a websocket connection with my springboot server but I can't access the endpoint from @MessageMapping when I'm trying to send a message. Here are my configurations:

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/simulator")
            .setAllowedOrigins("http://myiphere:3000")
            .withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableSimpleBroker("/endpoint");
    registry.setApplicationDestinationPrefixes("/app");
}

And a simple controller :

@RestController
@RequestMapping("/api")
public class MyController {

 @MessageMapping("/hello/")
 @SendTo("/endpoint/greeting")
 public Greeting getCurrentLocation() {
     System.out.println("hello here");
     return GenericBuilder.of(Greeting::new)
                          .with(Greeting::setContent, "hello from server")
                          .build();
 }

}

I'm using the socketjs-client library in ReactJS by following this tutorial :

import SockJS from "sockjs-client";
import Stomp from "stompjs";

let stompClient;

const connect = () => {
    const socket = new SockJS("http://myiphere:8081/simulator");
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log("Connected " + frame);
        stompClient.subscribe("http://myiphere:8081/endpoint/greeting", function (greeting) {
        console.log("hi" + JSON.parse(greeting.body).content);
        });
    });
};

const sendSomething = () => {
    stompClient.send("http://myiphere:8081/app/hello/", {});
};

And some buttons with onClick events bound to the methods above. The connection is working, I'm getting "connected" messages in browser console but when I'm trying to click the button with sendSomething() I'm not getting anything in the browser's console nor server's console.


问:
GLMM Convergence issues with lme4
I am modelling the number of jobs over month 1-112 (taken over ~10 years) for each Hospital. The number of jobs over time vary depending on the hospital so I have defined the following multilevel model as a starting point:

```<code>glmer.nb(Jobs ~ 1 + Region + Month + ( Month | factor(Region)),
                     data = df_month_region,
                     family = poisson(link = "log"))
</code>```

My data looks very similar to this:

```<code>df <- data.frame(
  Region = rep(1:14, each=112),
  Month = rep(seq(1,112,1),14),
  Job = rpois(112*14, 0.7)
)
</code>```

I would like to know:

1) Does modelling my data in this format makes sense? Would it make more sense to have a column for year and month separately?

2) How do I overcome this error: "Model failed to converge with max|grad| = 0.00361688 (tol = 0.001, component 1)Model is nearly unidentifiable: very large eigenvalue"? - I have followed the steps here: https://rstudio-pubs-static.s3.amazonaws.com/33653_57fc7b8e5d484c909b615d8633c01d51.html as commonly recommended on this site but I am starting to think the underlying problem lies perhaps with how I have setup my dataframe or my model?

答:
Okay, so based on the additional information you provided in your comment, I'm going to expand upon Pablo's answer. Since you are really only interested in the change in number of jobs over time, your only fixed effect should be Month. Now, you also say that you have the different hospitals and the regions those hospitals are in. That means that you need to have a nested random effects structure, where you have different hospitals that belong to the different regions. You can read more about nested random effects here:

http://errickson.net/stats-notes/vizrandomeffects.html

https://stats.stackexchange.com/questions/228800/crossed-vs-nested-random-effects-how-do-they-differ-and-how-are-they-specified

So, the final model that you should run will look like this:

```<code>job_model <- glmer(Jobs ~ Month + (1|Region/Hospital),
                     data = df_month_region,
                     family = poisson(link = "log"))
</code>```

In order to see if Month improves the model significantly, you should also fit the following model for comparison.

```<code>job_model_null <- glmer(Jobs ~ 1 + (1|Region/Hospital),
                     data = df_month_region,
                     family = poisson(link = "log"))
</code>```

And then you compare them with the likelihood ratio test using the anova() function like so:

```<code>anova(job_model, job_model_null)
</code>```

EDIT:
If you wish to fit a random slope for Month to the random effects, it would look like this:

```<code>job_model <- glmer(Jobs ~ Month + (1+Month|Region/Hospital),
                     data = df_month_region,
                     family = poisson(link = "log"))
</code>```

Title: GLMM Convergence issues with lme4

Body:
I am modelling the number of jobs over month 1-112 (taken over ~10 years) for each Hospital. The number of jobs over time vary depending on the hospital so I have defined the following multilevel model as a starting point:

glmer.nb(Jobs ~ 1 + Region + Month + ( Month | factor(Region)),
                     data = df_month_region,
                     family = poisson(link = "log"))

My data looks very similar to this:

df <- data.frame(
  Region = rep(1:14, each=112),
  Month = rep(seq(1,112,1),14),
  Job = rpois(112*14, 0.7)
)

I would like to know:

1) Does modelling my data in this format makes sense? Would it make more sense to have a column for year and month separately?

2) How do I overcome this error: "Model failed to converge with max|grad| = 0.00361688 (tol = 0.001, component 1)Model is nearly unidentifiable: very large eigenvalue"? - I have followed the steps here: https://rstudio-pubs-static.s3.amazonaws.com/33653_57fc7b8e5d484c909b615d8633c01d51.html as commonly recommended on this site but I am starting to think the underlying problem lies perhaps with how I have setup my dataframe or my model?

Body:
Okay, so based on the additional information you provided in your comment, I'm going to expand upon Pablo's answer. Since you are really only interested in the change in number of jobs over time, your only fixed effect should be Month. Now, you also say that you have the different hospitals and the regions those hospitals are in. That means that you need to have a nested random effects structure, where you have different hospitals that belong to the different regions. You can read more about nested random effects here:

http://errickson.net/stats-notes/vizrandomeffects.html

https://stats.stackexchange.com/questions/228800/crossed-vs-nested-random-effects-how-do-they-differ-and-how-are-they-specified

So, the final model that you should run will look like this:

job_model <- glmer(Jobs ~ Month + (1|Region/Hospital),
                     data = df_month_region,
                     family = poisson(link = "log"))

In order to see if Month improves the model significantly, you should also fit the following model for comparison.

job_model_null <- glmer(Jobs ~ 1 + (1|Region/Hospital),
                     data = df_month_region,
                     family = poisson(link = "log"))

And then you compare them with the likelihood ratio test using the anova() function like so:

anova(job_model, job_model_null)

EDIT:
If you wish to fit a random slope for Month to the random effects, it would look like this:

job_model <- glmer(Jobs ~ Month + (1+Month|Region/Hospital),
                     data = df_month_region,
                     family = poisson(link = "log"))


问:
Multiple results in the same Embed | Discord.py
How do i include multiple results in the same embed?

Heres the code btw

```<code>@client.command()
async def list(ctx):
    role = discord.utils.get(ctx.guild.roles, name="mute")
    for member in ctx.guild.members:
        if role in member.roles:
            embed = discord.Embed(title="Mute members")
            embed.add_field(name="Name", value=f"**{member.name}**",inline=False)
            embed.add_field(name="ID", value=f"{member.id}",inline=True)
            await ctx.send(embed=embed)
            empty = False
    if empty:
        await ctx.send("Nobody has the role {}".format(role.mention))
</code>```

The thing now is. When there are multiples mute members, the bot sends different embeds. and i want all the results in the same embeds

答:
Here's an example using a fair amount of list comprehension:

@client.command()
async def list(ctx):
    role = discord.utils.get(ctx.guild.roles, name="mute")
    muted = [(m.name, m.id) for m in ctx.guild.members if "mute" in [r.name for r in m.roles]]
    if len(muted) > 0:
        embed = discord.Embed(title="Muted members")
        embed.add_field(name="Names", value=f"**{', '.join([i[0] for i in muted])}**",inline=False)
        embed.add_field(name="ID", value=f"{', '.join([str(i[1]) for i in muted])}",inline=True)
        await ctx.send(embed=embed)
    else:
        await ctx.send(f"Nobody has the role {role.mention}")
```

It makes a list of tuples, in the format:

 [("name", 112233445566778899), ....

Which are then retrieved later through another comprehension, getting the first element of each tuple as the name, and the second element as the ID.

The ID has to be converted to a string for .join() to work, hence str(i[1]).

References:

Member.name

Member.id

List comprehension in Python

Member.roles

Role.name

Body:
How do i include multiple results in the same embed?

Heres the code btw

@client.command()
async def list(ctx):
    role = discord.utils.get(ctx.guild.roles, name="mute")
    for member in ctx.guild.members:
        if role in member.roles:
            embed = discord.Embed(title="Mute members")
            embed.add_field(name="Name", value=f"**{member.name}**",inline=False)
            embed.add_field(name="ID", value=f"{member.id}",inline=True)
            await ctx.send(embed=embed)
            empty = False
    if empty:
        await ctx.send("Nobody has the role {}".format(role.mention))

The thing now is. When there are multiples mute members, the bot sends different embeds. and i want all the results in the same embeds

Body:
Here's an example using a fair amount of list comprehension:

@client.command()
async def list(ctx):
    role = discord.utils.get(ctx.guild.roles, name="mute")
    muted = [(m.name, m.id) for m in ctx.guild.members if "mute" in [r.name for r in m.roles]]
    if len(muted) > 0:
        embed = discord.Embed(title="Muted members")
        embed.add_field(name="Names", value=f"**{', '.join([i[0] for i in muted])}**",inline=False)
        embed.add_field(name="ID", value=f"{', '.join([str(i[1]) for i in muted])}",inline=True)
        await ctx.send(embed=embed)
    else:
        await ctx.send(f"Nobody has the role {role.mention}")

It makes a list of tuples, in the format:

 [("name", 112233445566778899), ....

Which are then retrieved later through another comprehension, getting the first element of each tuple as the name, and the second element as the ID.

The ID has to be converted to a string for .join() to work, hence str(i[1]).

References:

Member.name

Member.id

List comprehension in Python

Member.roles

Role.name


问:
Laravel: Is there a way to remove DB query clauses?
Let us say my shop model has a products relationship as follows:

```<code>// shop model class

public function products()
{
    return $this->hasMany(Model\Product::class)
        ->orderBy('name');
}
</code>```

Is there a way that client code, such as my controller, can remove the orderBy() clause?

答:
For reset

```<code>$qry->getQuery()->groups = [];
$qry->getQuery()->wheres = [];
</code>```

For remove last where or group by column

```<code>array_pop($qry->getQuery()->groups);

array_pop($qry->getQuery()->wheres);
</code>```

Body:
Let us say my shop model has a products relationship as follows:

// shop model class

public function products()
{
    return $this->hasMany(Model\Product::class)
        ->orderBy('name');
}

Is there a way that client code, such as my controller, can remove the orderBy() clause?

Body:
For reset

$qry->getQuery()->groups = [];
$qry->getQuery()->wheres = [];

For remove last where or group by column

array_pop($qry->getQuery()->groups);

array_pop($qry->getQuery()->wheres);


问:
JS Practise background switching from white to blue
I am coding along with a course and I've triple checked that my code matches the instructors but when I run it it only changes the background of the webpage to blue instead of switching back and forth from white to blue every second like the instructor demonstrates. It also doesn't run at all when using Visual Studio so I had to switch to code pen and tried it in the console of Google chrome browser. Just want to know where it goes wrong or how to alter it to do the switching back and forth. Thank you.</p>

```<code> var body = document.querySelector("body");
 var isBlue = false;

setInterval(function(){
    if (isBlue) {
      body.style.background = "white";
    } else {
     body.style.background = "#3498db";
    }
  isBlue = isBlue;
 }, 1000);
</code>```

答:
This line at the end of your function:

```<code>isBlue = isBlue;
</code>```

doesn't do anything. isBlue is boolean, meaning if its false, you're setting it to false again, if it's true, you're setting it to true.

By putting an exclamation point at the beginning of the value, you're creating an expression, which means, return the opposite of this boolean's current state:

```<code> isBlue = !isBlue;
</code>```

Now, when it is false, it will be set to "not false," or true, and if it's true, it will be set to "not true," or false.

Also, you don't need querySelector() to get the body element. It's available with document.body.

var body = document.body;
var isBlue = false;

setInterval(function() {
  if (isBlue) {
    body.style.background = "white";
  } else {
    body.style.background = "#3498db";
  }
  isBlue = !isBlue; //change this
}, 1000);```

Body:
I am coding along with a course and I've triple checked that my code matches the instructors but when I run it it only changes the background of the webpage to blue instead of switching back and forth from white to blue every second like the instructor demonstrates. It also doesn't run at all when using Visual Studio so I had to switch to code pen and tried it in the console of Google chrome browser. Just want to know where it goes wrong or how to alter it to do the switching back and forth. Thank you.

 var body = document.querySelector("body");
 var isBlue = false;

setInterval(function(){
    if (isBlue) {
      body.style.background = "white";
    } else {
     body.style.background = "#3498db";
    }
  isBlue = isBlue;
 }, 1000);

Body:
This line at the end of your function:

isBlue = isBlue;

doesn't do anything. isBlue is boolean, meaning if its false, you're setting it to false again, if it's true, you're setting it to true.

By putting an exclamation point at the beginning of the value, you're creating an expression, which means, return the opposite of this boolean's current state:

 isBlue = !isBlue;

Now, when it is false, it will be set to "not false," or true, and if it's true, it will be set to "not true," or false.

Also, you don't need querySelector() to get the body element. It's available with document.body.

var body = document.body;
var isBlue = false;

setInterval(function() {
  if (isBlue) {
    body.style.background = "white";
  } else {
    body.style.background = "#3498db";
  }
  isBlue = !isBlue; //change this
}, 1000);


问:
Upgrading from Azure Storage SDK v6.0.0.0 to v12.4.2 for .NET Framework
I have a service that is referring to Azure SDK 3.0 in turn using Microsoft.WindowsAzure.Storage.dll of version 6.0.0.0. The service is built on .NET Framework and now when I want to to upgrade the Azure Storage SDK(Blobs, Common and Queues) to version 12.4.2, the library is published in .NET Standard

Per my understanding, I can't refer a .NET Standard library in a .NET Framework Library. I searched all over the internet but I couldn't find any way other than migrating my whole service to .NET Core.NET Standard.

Is there any other way to upgrade the latest version of Azure Storage SDKs?

答:
Is there any other way to upgrade the latest version of Azure Storage SDKs?

Direct upgrade from version 6 to 12 is not possible as SDK version 12 is actually quite different than older versions (9 or below).

Firstly, now the SDK is split in many SDKs and there are different SDKs for each service (Blobs, Files and Queues). Thus you would need to reference different Nuget packages in your source code.

Secondly, there have been many breaking changes in the SDKs thus simply referencing the Nuget packages for version 12 is just not sufficient. You will need to rewrite the code unfortunately.


问:
EPPlus Problem Creating List Validation from Table on another spreadsheet
I've created a table on one worksheet (list of state names) and named the table "tblStates". Then, on a second worksheet, there is a column for State where I want list validation for those cells, in which each cell has a dropdown offering the state names from the "tblStates" table. So for the State column in the 2nd worksheet, I created a table named "tblGeoStates" and added list validation to the column that references "=tblStates". (I referenced this article/video, although I don't have a 2nd dependent list, but just wanted to do the first part of this: Contexture Video)

By following the steps from the link above, I've performed these steps manually in Excel and it works perfectly, however, when coding it via EPPlus, it doesn't work. The tables in each worksheet are present and named correctly. The list validation has been applied to the table in the 2nd worksheet and a dropdown appears on each cell in tblGeoStates. But there are no values being displayed.

Worksheet 1 with tblStates table

Worksheet 2 with tblGeoStates table with list validation that references the first table

When I try to click on the list validation dialog to close it, I receive this validation error from Excel - None of this happens in the manually created workbook and everything appears to be the same

Code using EPPlus that generates each table and then the list validation on the 2nd table.

```<code>        // Add Named Table for States column so we can reference it in another sheet
        using (ExcelRange r = ws.Cells[$"B6:B57"])
        {
            ExcelTableCollection tblcollection = ws.Tables;
            ExcelTable table = tblcollection.Add(r, "tblStates");
        }

        // Add Named Table for GeoStates column and validation that references tblStates
        using (ExcelRange r = ws.Cells["F:F"]) // also tried "F2:F1048576 so the header isn't included
        {
            ExcelTableCollection tblcollection = ws.Tables;
            ExcelTable table = tblcollection.Add(r, "tblGeoStates");
            table.ShowFilter = false;

            var v1 = r.DataValidation.AddListDataValidation();
            v1.ShowErrorMessage = true;
            v1.ErrorStyle = ExcelDataValidationWarningStyle.warning;
            v1.ErrorTitle = "An invalid value was entered";
            v1.Error = "Select a value from the list";
            v1.Formula.ExcelFormula = "=tblStates"; // tried w & w/o = sign
        }
</code>```

I've tried a few different things like including the header or not in the selected range for the tables; AllowedBlanks or not, showed filter or not, etc.

I've examined the underlying XML of both the manually created workbook as well as the one generated programmatically with EPPlus and they appear different.

This is the EPPlus auto-generated one (doesn't work):

```<code><dataValidation sqref="F1:F1048576" errorStyle="warning" error="Select a value from the list" errorTitle="An invalid value was entered" showErrorMessage="1" type="list">
<formula1>tblStates</formula1>
</dataValidation>
</code>```

And this is the one I did manually (and works):

```<code><dataValidation xr:uid="{895EE9F3-E8D3-45B6-AD98-9A095C448064}" sqref="F1:F1048576" showErrorMessage="1" showInputMessage="1" type="list" allowBlank="1">
<formula1>tblStates</formula1>
</dataValidation>
</code>```

答: I had a similar error, but the problem was due to IExcelDataValidationList.Error value greater than 255 characters. </p>

Body:
I've created a table on one worksheet (list of state names) and named the table "tblStates". Then, on a second worksheet, there is a column for State where I want list validation for those cells, in which each cell has a dropdown offering the state names from the "tblStates" table. So for the State column in the 2nd worksheet, I created a table named "tblGeoStates" and added list validation to the column that references "=tblStates". (I referenced this article/video, although I don't have a 2nd dependent list, but just wanted to do the first part of this: Contexture Video)

By following the steps from the link above, I've performed these steps manually in Excel and it works perfectly, however, when coding it via EPPlus, it doesn't work. The tables in each worksheet are present and named correctly. The list validation has been applied to the table in the 2nd worksheet and a dropdown appears on each cell in tblGeoStates. But there are no values being displayed.

Worksheet 1 with tblStates table

Worksheet 2 with tblGeoStates table with list validation that references the first table

When I try to click on the list validation dialog to close it, I receive this validation error from Excel - None of this happens in the manually created workbook and everything appears to be the same

Code using EPPlus that generates each table and then the list validation on the 2nd table.

        // Add Named Table for States column so we can reference it in another sheet
        using (ExcelRange r = ws.Cells[$"B6:B57"])
        {
            ExcelTableCollection tblcollection = ws.Tables;
            ExcelTable table = tblcollection.Add(r, "tblStates");
        }

        // Add Named Table for GeoStates column and validation that references tblStates
        using (ExcelRange r = ws.Cells["F:F"]) // also tried "F2:F1048576 so the header isn't included
        {
            ExcelTableCollection tblcollection = ws.Tables;
            ExcelTable table = tblcollection.Add(r, "tblGeoStates");
            table.ShowFilter = false;

            var v1 = r.DataValidation.AddListDataValidation();
            v1.ShowErrorMessage = true;
            v1.ErrorStyle = ExcelDataValidationWarningStyle.warning;
            v1.ErrorTitle = "An invalid value was entered";
            v1.Error = "Select a value from the list";
            v1.Formula.ExcelFormula = "=tblStates"; // tried w & w/o = sign
        }

I've tried a few different things like including the header or not in the selected range for the tables; AllowedBlanks or not, showed filter or not, etc.

I've examined the underlying XML of both the manually created workbook as well as the one generated programmatically with EPPlus and they appear different.

This is the EPPlus auto-generated one (doesn't work):

<dataValidation sqref="F1:F1048576" errorStyle="warning" error="Select a value from the list" errorTitle="An invalid value was entered" showErrorMessage="1" type="list">
<formula1>tblStates</formula1>
</dataValidation>

And this is the one I did manually (and works):

<dataValidation xr:uid="{895EE9F3-E8D3-45B6-AD98-9A095C448064}" sqref="F1:F1048576" showErrorMessage="1" showInputMessage="1" type="list" allowBlank="1">
<formula1>tblStates</formula1>
</dataValidation>